babylon.max.js 2.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.Forward = function () {
  834. return new Vector3(0, 0, 1.0);
  835. };
  836. Vector3.Right = function () {
  837. return new Vector3(1.0, 0, 0);
  838. };
  839. Vector3.Left = function () {
  840. return new Vector3(-1.0, 0, 0);
  841. };
  842. Vector3.TransformCoordinates = function (vector, transformation) {
  843. var result = Vector3.Zero();
  844. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  845. return result;
  846. };
  847. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  848. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  849. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  850. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  851. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  852. result.x = x / w;
  853. result.y = y / w;
  854. result.z = z / w;
  855. };
  856. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  857. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  858. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  859. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  860. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  861. result.x = rx / rw;
  862. result.y = ry / rw;
  863. result.z = rz / rw;
  864. };
  865. Vector3.TransformNormal = function (vector, transformation) {
  866. var result = Vector3.Zero();
  867. Vector3.TransformNormalToRef(vector, transformation, result);
  868. return result;
  869. };
  870. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  871. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  872. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  873. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  874. result.x = x;
  875. result.y = y;
  876. result.z = z;
  877. };
  878. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  879. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  880. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  881. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  882. };
  883. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  884. var squared = amount * amount;
  885. var cubed = amount * squared;
  886. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  887. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  888. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  889. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  890. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  891. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  892. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  893. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  894. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Clamp = function (value, min, max) {
  898. var x = value.x;
  899. x = (x > max.x) ? max.x : x;
  900. x = (x < min.x) ? min.x : x;
  901. var y = value.y;
  902. y = (y > max.y) ? max.y : y;
  903. y = (y < min.y) ? min.y : y;
  904. var z = value.z;
  905. z = (z > max.z) ? max.z : z;
  906. z = (z < min.z) ? min.z : z;
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  910. var squared = amount * amount;
  911. var cubed = amount * squared;
  912. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  913. var part2 = (-2.0 * cubed) + (3.0 * squared);
  914. var part3 = (cubed - (2.0 * squared)) + amount;
  915. var part4 = cubed - squared;
  916. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  917. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  918. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  919. return new Vector3(x, y, z);
  920. };
  921. Vector3.Lerp = function (start, end, amount) {
  922. var result = new Vector3(0, 0, 0);
  923. Vector3.LerpToRef(start, end, amount, result);
  924. return result;
  925. };
  926. Vector3.LerpToRef = function (start, end, amount, result) {
  927. result.x = start.x + ((end.x - start.x) * amount);
  928. result.y = start.y + ((end.y - start.y) * amount);
  929. result.z = start.z + ((end.z - start.z) * amount);
  930. };
  931. Vector3.Dot = function (left, right) {
  932. return (left.x * right.x + left.y * right.y + left.z * right.z);
  933. };
  934. Vector3.Cross = function (left, right) {
  935. var result = Vector3.Zero();
  936. Vector3.CrossToRef(left, right, result);
  937. return result;
  938. };
  939. Vector3.CrossToRef = function (left, right, result) {
  940. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  941. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  942. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  943. result.copyFrom(Tmp.Vector3[0]);
  944. };
  945. Vector3.Normalize = function (vector) {
  946. var result = Vector3.Zero();
  947. Vector3.NormalizeToRef(vector, result);
  948. return result;
  949. };
  950. Vector3.NormalizeToRef = function (vector, result) {
  951. result.copyFrom(vector);
  952. result.normalize();
  953. };
  954. Vector3.Project = function (vector, world, transform, viewport) {
  955. var cw = viewport.width;
  956. var ch = viewport.height;
  957. var cx = viewport.x;
  958. var cy = viewport.y;
  959. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  960. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  961. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  962. world.multiplyToRef(transform, matrix);
  963. matrix.multiplyToRef(viewportMatrix, matrix);
  964. return Vector3.TransformCoordinates(vector, matrix);
  965. };
  966. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  967. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  968. world.multiplyToRef(transform, matrix);
  969. matrix.invert();
  970. source.x = source.x / viewportWidth * 2 - 1;
  971. source.y = -(source.y / viewportHeight * 2 - 1);
  972. var vector = Vector3.TransformCoordinates(source, matrix);
  973. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  974. if (MathTools.WithinEpsilon(num, 1.0)) {
  975. vector = vector.scale(1.0 / num);
  976. }
  977. return vector;
  978. };
  979. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  980. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  981. world.multiplyToRef(view, matrix);
  982. matrix.multiplyToRef(projection, matrix);
  983. matrix.invert();
  984. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  985. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  986. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  987. if (MathTools.WithinEpsilon(num, 1.0)) {
  988. vector = vector.scale(1.0 / num);
  989. }
  990. return vector;
  991. };
  992. Vector3.Minimize = function (left, right) {
  993. var min = left.clone();
  994. min.MinimizeInPlace(right);
  995. return min;
  996. };
  997. Vector3.Maximize = function (left, right) {
  998. var max = left.clone();
  999. max.MaximizeInPlace(right);
  1000. return max;
  1001. };
  1002. Vector3.Distance = function (value1, value2) {
  1003. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1004. };
  1005. Vector3.DistanceSquared = function (value1, value2) {
  1006. var x = value1.x - value2.x;
  1007. var y = value1.y - value2.y;
  1008. var z = value1.z - value2.z;
  1009. return (x * x) + (y * y) + (z * z);
  1010. };
  1011. Vector3.Center = function (value1, value2) {
  1012. var center = value1.add(value2);
  1013. center.scaleInPlace(0.5);
  1014. return center;
  1015. };
  1016. /**
  1017. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1018. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1019. * to something in order to rotate it from its local system to the given target system.
  1020. */
  1021. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1022. var rotation = Vector3.Zero();
  1023. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1024. return rotation;
  1025. };
  1026. /**
  1027. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1028. */
  1029. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1030. var u = axis1.normalize();
  1031. var w = axis3.normalize();
  1032. // world axis
  1033. var X = Axis.X;
  1034. var Y = Axis.Y;
  1035. // equation unknowns and vars
  1036. var yaw = 0.0;
  1037. var pitch = 0.0;
  1038. var roll = 0.0;
  1039. var x = 0.0;
  1040. var y = 0.0;
  1041. var z = 0.0;
  1042. var t = 0.0;
  1043. var sign = -1.0;
  1044. var nbRevert = 0;
  1045. var cross = Tmp.Vector3[0];
  1046. var dot = 0.0;
  1047. // step 1 : rotation around w
  1048. // Rv3(u) = u1, and u1 belongs to plane xOz
  1049. // Rv3(w) = w1 = w invariant
  1050. var u1 = Tmp.Vector3[1];
  1051. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1052. z = 1.0;
  1053. }
  1054. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1055. x = 1.0;
  1056. }
  1057. else {
  1058. t = w.z / w.x;
  1059. x = -t * Math.sqrt(1 / (1 + t * t));
  1060. z = Math.sqrt(1 / (1 + t * t));
  1061. }
  1062. u1.x = x;
  1063. u1.y = y;
  1064. u1.z = z;
  1065. u1.normalize();
  1066. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1067. cross.normalize();
  1068. if (Vector3.Dot(w, cross) < 0) {
  1069. sign = 1.0;
  1070. }
  1071. dot = Vector3.Dot(u, u1);
  1072. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1073. roll = Math.acos(dot) * sign;
  1074. if (Vector3.Dot(u1, X) < 0) {
  1075. roll = Math.PI + roll;
  1076. u1 = u1.scaleInPlace(-1);
  1077. nbRevert++;
  1078. }
  1079. // step 2 : rotate around u1
  1080. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1081. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1082. var w2 = Tmp.Vector3[2];
  1083. var v2 = Tmp.Vector3[3];
  1084. x = 0.0;
  1085. y = 0.0;
  1086. z = 0.0;
  1087. sign = -1.0;
  1088. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1089. x = 1.0;
  1090. }
  1091. else {
  1092. t = u1.z / u1.x;
  1093. x = -t * Math.sqrt(1 / (1 + t * t));
  1094. z = Math.sqrt(1 / (1 + t * t));
  1095. }
  1096. w2.x = x;
  1097. w2.y = y;
  1098. w2.z = z;
  1099. w2.normalize();
  1100. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1101. v2.normalize();
  1102. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1103. cross.normalize();
  1104. if (Vector3.Dot(u1, cross) < 0) {
  1105. sign = 1.0;
  1106. }
  1107. dot = Vector3.Dot(w, w2);
  1108. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1109. pitch = Math.acos(dot) * sign;
  1110. if (Vector3.Dot(v2, Y) < 0) {
  1111. pitch = Math.PI + pitch;
  1112. nbRevert++;
  1113. }
  1114. // step 3 : rotate around v2
  1115. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1116. sign = -1.0;
  1117. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1118. cross.normalize();
  1119. if (Vector3.Dot(cross, Y) < 0) {
  1120. sign = 1.0;
  1121. }
  1122. dot = Vector3.Dot(u1, X);
  1123. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1124. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1125. if (dot < 0 && nbRevert < 2) {
  1126. yaw = Math.PI + yaw;
  1127. }
  1128. ref.x = pitch;
  1129. ref.y = yaw;
  1130. ref.z = roll;
  1131. };
  1132. return Vector3;
  1133. }());
  1134. BABYLON.Vector3 = Vector3;
  1135. //Vector4 class created for EulerAngle class conversion to Quaternion
  1136. var Vector4 = (function () {
  1137. function Vector4(x, y, z, w) {
  1138. this.x = x;
  1139. this.y = y;
  1140. this.z = z;
  1141. this.w = w;
  1142. }
  1143. Vector4.prototype.toString = function () {
  1144. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1145. };
  1146. Vector4.prototype.getClassName = function () {
  1147. return "Vector4";
  1148. };
  1149. Vector4.prototype.getHashCode = function () {
  1150. var hash = this.x || 0;
  1151. hash = (hash * 397) ^ (this.y || 0);
  1152. hash = (hash * 397) ^ (this.z || 0);
  1153. hash = (hash * 397) ^ (this.w || 0);
  1154. return hash;
  1155. };
  1156. // Operators
  1157. Vector4.prototype.asArray = function () {
  1158. var result = [];
  1159. this.toArray(result, 0);
  1160. return result;
  1161. };
  1162. Vector4.prototype.toArray = function (array, index) {
  1163. if (index === undefined) {
  1164. index = 0;
  1165. }
  1166. array[index] = this.x;
  1167. array[index + 1] = this.y;
  1168. array[index + 2] = this.z;
  1169. array[index + 3] = this.w;
  1170. return this;
  1171. };
  1172. Vector4.prototype.addInPlace = function (otherVector) {
  1173. this.x += otherVector.x;
  1174. this.y += otherVector.y;
  1175. this.z += otherVector.z;
  1176. this.w += otherVector.w;
  1177. return this;
  1178. };
  1179. Vector4.prototype.add = function (otherVector) {
  1180. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1181. };
  1182. Vector4.prototype.addToRef = function (otherVector, result) {
  1183. result.x = this.x + otherVector.x;
  1184. result.y = this.y + otherVector.y;
  1185. result.z = this.z + otherVector.z;
  1186. result.w = this.w + otherVector.w;
  1187. return this;
  1188. };
  1189. Vector4.prototype.subtractInPlace = function (otherVector) {
  1190. this.x -= otherVector.x;
  1191. this.y -= otherVector.y;
  1192. this.z -= otherVector.z;
  1193. this.w -= otherVector.w;
  1194. return this;
  1195. };
  1196. Vector4.prototype.subtract = function (otherVector) {
  1197. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1198. };
  1199. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1200. result.x = this.x - otherVector.x;
  1201. result.y = this.y - otherVector.y;
  1202. result.z = this.z - otherVector.z;
  1203. result.w = this.w - otherVector.w;
  1204. return this;
  1205. };
  1206. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1207. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1208. };
  1209. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1210. result.x = this.x - x;
  1211. result.y = this.y - y;
  1212. result.z = this.z - z;
  1213. result.w = this.w - w;
  1214. return this;
  1215. };
  1216. Vector4.prototype.negate = function () {
  1217. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1218. };
  1219. Vector4.prototype.scaleInPlace = function (scale) {
  1220. this.x *= scale;
  1221. this.y *= scale;
  1222. this.z *= scale;
  1223. this.w *= scale;
  1224. return this;
  1225. };
  1226. Vector4.prototype.scale = function (scale) {
  1227. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1228. };
  1229. Vector4.prototype.scaleToRef = function (scale, result) {
  1230. result.x = this.x * scale;
  1231. result.y = this.y * scale;
  1232. result.z = this.z * scale;
  1233. result.w = this.w * scale;
  1234. };
  1235. Vector4.prototype.equals = function (otherVector) {
  1236. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1237. };
  1238. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1239. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1240. return otherVector
  1241. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1242. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1243. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1244. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1245. };
  1246. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1247. return this.x === x && this.y === y && this.z === z && this.w === w;
  1248. };
  1249. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1250. this.x *= otherVector.x;
  1251. this.y *= otherVector.y;
  1252. this.z *= otherVector.z;
  1253. this.w *= otherVector.w;
  1254. return this;
  1255. };
  1256. Vector4.prototype.multiply = function (otherVector) {
  1257. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1258. };
  1259. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1260. result.x = this.x * otherVector.x;
  1261. result.y = this.y * otherVector.y;
  1262. result.z = this.z * otherVector.z;
  1263. result.w = this.w * otherVector.w;
  1264. return this;
  1265. };
  1266. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1267. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1268. };
  1269. Vector4.prototype.divide = function (otherVector) {
  1270. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1271. };
  1272. Vector4.prototype.divideToRef = function (otherVector, result) {
  1273. result.x = this.x / otherVector.x;
  1274. result.y = this.y / otherVector.y;
  1275. result.z = this.z / otherVector.z;
  1276. result.w = this.w / otherVector.w;
  1277. return this;
  1278. };
  1279. Vector4.prototype.MinimizeInPlace = function (other) {
  1280. if (other.x < this.x)
  1281. this.x = other.x;
  1282. if (other.y < this.y)
  1283. this.y = other.y;
  1284. if (other.z < this.z)
  1285. this.z = other.z;
  1286. if (other.w < this.w)
  1287. this.w = other.w;
  1288. return this;
  1289. };
  1290. Vector4.prototype.MaximizeInPlace = function (other) {
  1291. if (other.x > this.x)
  1292. this.x = other.x;
  1293. if (other.y > this.y)
  1294. this.y = other.y;
  1295. if (other.z > this.z)
  1296. this.z = other.z;
  1297. if (other.w > this.w)
  1298. this.w = other.w;
  1299. return this;
  1300. };
  1301. // Properties
  1302. Vector4.prototype.length = function () {
  1303. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1304. };
  1305. Vector4.prototype.lengthSquared = function () {
  1306. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1307. };
  1308. // Methods
  1309. Vector4.prototype.normalize = function () {
  1310. var len = this.length();
  1311. if (len === 0)
  1312. return this;
  1313. var num = 1.0 / len;
  1314. this.x *= num;
  1315. this.y *= num;
  1316. this.z *= num;
  1317. this.w *= num;
  1318. return this;
  1319. };
  1320. Vector4.prototype.toVector3 = function () {
  1321. return new Vector3(this.x, this.y, this.z);
  1322. };
  1323. Vector4.prototype.clone = function () {
  1324. return new Vector4(this.x, this.y, this.z, this.w);
  1325. };
  1326. Vector4.prototype.copyFrom = function (source) {
  1327. this.x = source.x;
  1328. this.y = source.y;
  1329. this.z = source.z;
  1330. this.w = source.w;
  1331. return this;
  1332. };
  1333. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1334. this.x = x;
  1335. this.y = y;
  1336. this.z = z;
  1337. this.w = w;
  1338. return this;
  1339. };
  1340. // Statics
  1341. Vector4.FromArray = function (array, offset) {
  1342. if (!offset) {
  1343. offset = 0;
  1344. }
  1345. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1346. };
  1347. Vector4.FromArrayToRef = function (array, offset, result) {
  1348. result.x = array[offset];
  1349. result.y = array[offset + 1];
  1350. result.z = array[offset + 2];
  1351. result.w = array[offset + 3];
  1352. };
  1353. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1354. result.x = array[offset];
  1355. result.y = array[offset + 1];
  1356. result.z = array[offset + 2];
  1357. result.w = array[offset + 3];
  1358. };
  1359. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1360. result.x = x;
  1361. result.y = y;
  1362. result.z = z;
  1363. result.w = w;
  1364. };
  1365. Vector4.Zero = function () {
  1366. return new Vector4(0, 0, 0, 0);
  1367. };
  1368. Vector4.Normalize = function (vector) {
  1369. var result = Vector4.Zero();
  1370. Vector4.NormalizeToRef(vector, result);
  1371. return result;
  1372. };
  1373. Vector4.NormalizeToRef = function (vector, result) {
  1374. result.copyFrom(vector);
  1375. result.normalize();
  1376. };
  1377. Vector4.Minimize = function (left, right) {
  1378. var min = left.clone();
  1379. min.MinimizeInPlace(right);
  1380. return min;
  1381. };
  1382. Vector4.Maximize = function (left, right) {
  1383. var max = left.clone();
  1384. max.MaximizeInPlace(right);
  1385. return max;
  1386. };
  1387. Vector4.Distance = function (value1, value2) {
  1388. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1389. };
  1390. Vector4.DistanceSquared = function (value1, value2) {
  1391. var x = value1.x - value2.x;
  1392. var y = value1.y - value2.y;
  1393. var z = value1.z - value2.z;
  1394. var w = value1.w - value2.w;
  1395. return (x * x) + (y * y) + (z * z) + (w * w);
  1396. };
  1397. Vector4.Center = function (value1, value2) {
  1398. var center = value1.add(value2);
  1399. center.scaleInPlace(0.5);
  1400. return center;
  1401. };
  1402. return Vector4;
  1403. }());
  1404. BABYLON.Vector4 = Vector4;
  1405. var Size = (function () {
  1406. function Size(width, height) {
  1407. this.width = width;
  1408. this.height = height;
  1409. }
  1410. Size.prototype.toString = function () {
  1411. return "{W: " + this.width + ", H: " + this.height + "}";
  1412. };
  1413. Size.prototype.getClassName = function () {
  1414. return "Size";
  1415. };
  1416. Size.prototype.getHashCode = function () {
  1417. var hash = this.width || 0;
  1418. hash = (hash * 397) ^ (this.height || 0);
  1419. return hash;
  1420. };
  1421. Size.prototype.copyFrom = function (src) {
  1422. this.width = src.width;
  1423. this.height = src.height;
  1424. };
  1425. Size.prototype.copyFromFloats = function (width, height) {
  1426. this.width = width;
  1427. this.height = height;
  1428. };
  1429. Size.prototype.multiplyByFloats = function (w, h) {
  1430. return new Size(this.width * w, this.height * h);
  1431. };
  1432. Size.prototype.clone = function () {
  1433. return new Size(this.width, this.height);
  1434. };
  1435. Size.prototype.equals = function (other) {
  1436. if (!other) {
  1437. return false;
  1438. }
  1439. return (this.width === other.width) && (this.height === other.height);
  1440. };
  1441. Object.defineProperty(Size.prototype, "surface", {
  1442. get: function () {
  1443. return this.width * this.height;
  1444. },
  1445. enumerable: true,
  1446. configurable: true
  1447. });
  1448. Size.Zero = function () {
  1449. return new Size(0, 0);
  1450. };
  1451. Size.prototype.add = function (otherSize) {
  1452. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1453. return r;
  1454. };
  1455. Size.prototype.substract = function (otherSize) {
  1456. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1457. return r;
  1458. };
  1459. Size.Lerp = function (start, end, amount) {
  1460. var w = start.width + ((end.width - start.width) * amount);
  1461. var h = start.height + ((end.height - start.height) * amount);
  1462. return new Size(w, h);
  1463. };
  1464. return Size;
  1465. }());
  1466. BABYLON.Size = Size;
  1467. var Quaternion = (function () {
  1468. function Quaternion(x, y, z, w) {
  1469. if (x === void 0) { x = 0; }
  1470. if (y === void 0) { y = 0; }
  1471. if (z === void 0) { z = 0; }
  1472. if (w === void 0) { w = 1; }
  1473. this.x = x;
  1474. this.y = y;
  1475. this.z = z;
  1476. this.w = w;
  1477. }
  1478. Quaternion.prototype.toString = function () {
  1479. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1480. };
  1481. Quaternion.prototype.getClassName = function () {
  1482. return "Quaternion";
  1483. };
  1484. Quaternion.prototype.getHashCode = function () {
  1485. var hash = this.x || 0;
  1486. hash = (hash * 397) ^ (this.y || 0);
  1487. hash = (hash * 397) ^ (this.z || 0);
  1488. hash = (hash * 397) ^ (this.w || 0);
  1489. return hash;
  1490. };
  1491. Quaternion.prototype.asArray = function () {
  1492. return [this.x, this.y, this.z, this.w];
  1493. };
  1494. Quaternion.prototype.equals = function (otherQuaternion) {
  1495. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1496. };
  1497. Quaternion.prototype.clone = function () {
  1498. return new Quaternion(this.x, this.y, this.z, this.w);
  1499. };
  1500. Quaternion.prototype.copyFrom = function (other) {
  1501. this.x = other.x;
  1502. this.y = other.y;
  1503. this.z = other.z;
  1504. this.w = other.w;
  1505. return this;
  1506. };
  1507. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1508. this.x = x;
  1509. this.y = y;
  1510. this.z = z;
  1511. this.w = w;
  1512. return this;
  1513. };
  1514. Quaternion.prototype.add = function (other) {
  1515. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1516. };
  1517. Quaternion.prototype.subtract = function (other) {
  1518. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1519. };
  1520. Quaternion.prototype.scale = function (value) {
  1521. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1522. };
  1523. Quaternion.prototype.multiply = function (q1) {
  1524. var result = new Quaternion(0, 0, 0, 1.0);
  1525. this.multiplyToRef(q1, result);
  1526. return result;
  1527. };
  1528. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1529. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1530. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1531. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1532. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1533. result.copyFromFloats(x, y, z, w);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.multiplyInPlace = function (q1) {
  1537. this.multiplyToRef(q1, this);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateToRef = function (ref) {
  1541. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1542. return this;
  1543. };
  1544. Quaternion.prototype.conjugateInPlace = function () {
  1545. this.x *= -1;
  1546. this.y *= -1;
  1547. this.z *= -1;
  1548. return this;
  1549. };
  1550. Quaternion.prototype.conjugate = function () {
  1551. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1552. return result;
  1553. };
  1554. Quaternion.prototype.length = function () {
  1555. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1556. };
  1557. Quaternion.prototype.normalize = function () {
  1558. var length = 1.0 / this.length();
  1559. this.x *= length;
  1560. this.y *= length;
  1561. this.z *= length;
  1562. this.w *= length;
  1563. return this;
  1564. };
  1565. Quaternion.prototype.toEulerAngles = function (order) {
  1566. if (order === void 0) { order = "YZX"; }
  1567. var result = Vector3.Zero();
  1568. this.toEulerAnglesToRef(result, order);
  1569. return result;
  1570. };
  1571. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1572. if (order === void 0) { order = "YZX"; }
  1573. var qz = this.z;
  1574. var qx = this.x;
  1575. var qy = this.y;
  1576. var qw = this.w;
  1577. var sqw = qw * qw;
  1578. var sqz = qz * qz;
  1579. var sqx = qx * qx;
  1580. var sqy = qy * qy;
  1581. var zAxisY = qy * qz - qx * qw;
  1582. var limit = .4999999;
  1583. if (zAxisY < -limit) {
  1584. result.y = 2 * Math.atan2(qy, qw);
  1585. result.x = Math.PI / 2;
  1586. result.z = 0;
  1587. }
  1588. else if (zAxisY > limit) {
  1589. result.y = 2 * Math.atan2(qy, qw);
  1590. result.x = -Math.PI / 2;
  1591. result.z = 0;
  1592. }
  1593. else {
  1594. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1595. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1596. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1597. }
  1598. return this;
  1599. };
  1600. Quaternion.prototype.toRotationMatrix = function (result) {
  1601. var xx = this.x * this.x;
  1602. var yy = this.y * this.y;
  1603. var zz = this.z * this.z;
  1604. var xy = this.x * this.y;
  1605. var zw = this.z * this.w;
  1606. var zx = this.z * this.x;
  1607. var yw = this.y * this.w;
  1608. var yz = this.y * this.z;
  1609. var xw = this.x * this.w;
  1610. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1611. result.m[1] = 2.0 * (xy + zw);
  1612. result.m[2] = 2.0 * (zx - yw);
  1613. result.m[3] = 0;
  1614. result.m[4] = 2.0 * (xy - zw);
  1615. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1616. result.m[6] = 2.0 * (yz + xw);
  1617. result.m[7] = 0;
  1618. result.m[8] = 2.0 * (zx + yw);
  1619. result.m[9] = 2.0 * (yz - xw);
  1620. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1621. result.m[11] = 0;
  1622. result.m[12] = 0;
  1623. result.m[13] = 0;
  1624. result.m[14] = 0;
  1625. result.m[15] = 1.0;
  1626. return this;
  1627. };
  1628. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1629. Quaternion.FromRotationMatrixToRef(matrix, this);
  1630. return this;
  1631. };
  1632. // Statics
  1633. Quaternion.FromRotationMatrix = function (matrix) {
  1634. var result = new Quaternion();
  1635. Quaternion.FromRotationMatrixToRef(matrix, result);
  1636. return result;
  1637. };
  1638. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1639. var data = matrix.m;
  1640. var m11 = data[0], m12 = data[4], m13 = data[8];
  1641. var m21 = data[1], m22 = data[5], m23 = data[9];
  1642. var m31 = data[2], m32 = data[6], m33 = data[10];
  1643. var trace = m11 + m22 + m33;
  1644. var s;
  1645. if (trace > 0) {
  1646. s = 0.5 / Math.sqrt(trace + 1.0);
  1647. result.w = 0.25 / s;
  1648. result.x = (m32 - m23) * s;
  1649. result.y = (m13 - m31) * s;
  1650. result.z = (m21 - m12) * s;
  1651. }
  1652. else if (m11 > m22 && m11 > m33) {
  1653. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1654. result.w = (m32 - m23) / s;
  1655. result.x = 0.25 * s;
  1656. result.y = (m12 + m21) / s;
  1657. result.z = (m13 + m31) / s;
  1658. }
  1659. else if (m22 > m33) {
  1660. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1661. result.w = (m13 - m31) / s;
  1662. result.x = (m12 + m21) / s;
  1663. result.y = 0.25 * s;
  1664. result.z = (m23 + m32) / s;
  1665. }
  1666. else {
  1667. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1668. result.w = (m21 - m12) / s;
  1669. result.x = (m13 + m31) / s;
  1670. result.y = (m23 + m32) / s;
  1671. result.z = 0.25 * s;
  1672. }
  1673. };
  1674. Quaternion.Inverse = function (q) {
  1675. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1676. };
  1677. Quaternion.Identity = function () {
  1678. return new Quaternion(0, 0, 0, 1);
  1679. };
  1680. Quaternion.RotationAxis = function (axis, angle) {
  1681. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1682. };
  1683. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1684. var sin = Math.sin(angle / 2);
  1685. axis.normalize();
  1686. result.w = Math.cos(angle / 2);
  1687. result.x = axis.x * sin;
  1688. result.y = axis.y * sin;
  1689. result.z = axis.z * sin;
  1690. return result;
  1691. };
  1692. Quaternion.FromArray = function (array, offset) {
  1693. if (!offset) {
  1694. offset = 0;
  1695. }
  1696. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1697. };
  1698. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1699. var q = new Quaternion();
  1700. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1701. return q;
  1702. };
  1703. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1704. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1705. var halfRoll = roll * 0.5;
  1706. var halfPitch = pitch * 0.5;
  1707. var halfYaw = yaw * 0.5;
  1708. var sinRoll = Math.sin(halfRoll);
  1709. var cosRoll = Math.cos(halfRoll);
  1710. var sinPitch = Math.sin(halfPitch);
  1711. var cosPitch = Math.cos(halfPitch);
  1712. var sinYaw = Math.sin(halfYaw);
  1713. var cosYaw = Math.cos(halfYaw);
  1714. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1715. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1716. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1717. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1718. };
  1719. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1720. var result = new Quaternion();
  1721. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1722. return result;
  1723. };
  1724. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1725. // Produces a quaternion from Euler angles in the z-x-z orientation
  1726. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1727. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1728. var halfBeta = beta * 0.5;
  1729. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1730. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1732. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. };
  1734. Quaternion.Slerp = function (left, right, amount) {
  1735. var result = Quaternion.Identity();
  1736. Quaternion.SlerpToRef(left, right, amount, result);
  1737. return result;
  1738. };
  1739. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1740. var num2;
  1741. var num3;
  1742. var num = amount;
  1743. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1744. var flag = false;
  1745. if (num4 < 0) {
  1746. flag = true;
  1747. num4 = -num4;
  1748. }
  1749. if (num4 > 0.999999) {
  1750. num3 = 1 - num;
  1751. num2 = flag ? -num : num;
  1752. }
  1753. else {
  1754. var num5 = Math.acos(num4);
  1755. var num6 = (1.0 / Math.sin(num5));
  1756. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1757. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1758. }
  1759. result.x = (num3 * left.x) + (num2 * right.x);
  1760. result.y = (num3 * left.y) + (num2 * right.y);
  1761. result.z = (num3 * left.z) + (num2 * right.z);
  1762. result.w = (num3 * left.w) + (num2 * right.w);
  1763. };
  1764. return Quaternion;
  1765. }());
  1766. BABYLON.Quaternion = Quaternion;
  1767. var Matrix = (function () {
  1768. function Matrix() {
  1769. this.m = new Float32Array(16);
  1770. }
  1771. // Properties
  1772. Matrix.prototype.isIdentity = function () {
  1773. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1774. return false;
  1775. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1776. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1777. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1778. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1779. return false;
  1780. return true;
  1781. };
  1782. Matrix.prototype.determinant = function () {
  1783. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1784. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1785. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1786. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1787. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1788. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1789. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1790. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1791. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1792. };
  1793. // Methods
  1794. Matrix.prototype.toArray = function () {
  1795. return this.m;
  1796. };
  1797. Matrix.prototype.asArray = function () {
  1798. return this.toArray();
  1799. };
  1800. Matrix.prototype.invert = function () {
  1801. this.invertToRef(this);
  1802. return this;
  1803. };
  1804. Matrix.prototype.reset = function () {
  1805. for (var index = 0; index < 16; index++) {
  1806. this.m[index] = 0;
  1807. }
  1808. return this;
  1809. };
  1810. Matrix.prototype.add = function (other) {
  1811. var result = new Matrix();
  1812. this.addToRef(other, result);
  1813. return result;
  1814. };
  1815. Matrix.prototype.addToRef = function (other, result) {
  1816. for (var index = 0; index < 16; index++) {
  1817. result.m[index] = this.m[index] + other.m[index];
  1818. }
  1819. return this;
  1820. };
  1821. Matrix.prototype.addToSelf = function (other) {
  1822. for (var index = 0; index < 16; index++) {
  1823. this.m[index] += other.m[index];
  1824. }
  1825. return this;
  1826. };
  1827. Matrix.prototype.invertToRef = function (other) {
  1828. var l1 = this.m[0];
  1829. var l2 = this.m[1];
  1830. var l3 = this.m[2];
  1831. var l4 = this.m[3];
  1832. var l5 = this.m[4];
  1833. var l6 = this.m[5];
  1834. var l7 = this.m[6];
  1835. var l8 = this.m[7];
  1836. var l9 = this.m[8];
  1837. var l10 = this.m[9];
  1838. var l11 = this.m[10];
  1839. var l12 = this.m[11];
  1840. var l13 = this.m[12];
  1841. var l14 = this.m[13];
  1842. var l15 = this.m[14];
  1843. var l16 = this.m[15];
  1844. var l17 = (l11 * l16) - (l12 * l15);
  1845. var l18 = (l10 * l16) - (l12 * l14);
  1846. var l19 = (l10 * l15) - (l11 * l14);
  1847. var l20 = (l9 * l16) - (l12 * l13);
  1848. var l21 = (l9 * l15) - (l11 * l13);
  1849. var l22 = (l9 * l14) - (l10 * l13);
  1850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1855. var l28 = (l7 * l16) - (l8 * l15);
  1856. var l29 = (l6 * l16) - (l8 * l14);
  1857. var l30 = (l6 * l15) - (l7 * l14);
  1858. var l31 = (l5 * l16) - (l8 * l13);
  1859. var l32 = (l5 * l15) - (l7 * l13);
  1860. var l33 = (l5 * l14) - (l6 * l13);
  1861. var l34 = (l7 * l12) - (l8 * l11);
  1862. var l35 = (l6 * l12) - (l8 * l10);
  1863. var l36 = (l6 * l11) - (l7 * l10);
  1864. var l37 = (l5 * l12) - (l8 * l9);
  1865. var l38 = (l5 * l11) - (l7 * l9);
  1866. var l39 = (l5 * l10) - (l6 * l9);
  1867. other.m[0] = l23 * l27;
  1868. other.m[4] = l24 * l27;
  1869. other.m[8] = l25 * l27;
  1870. other.m[12] = l26 * l27;
  1871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1883. return this;
  1884. };
  1885. Matrix.prototype.setTranslation = function (vector3) {
  1886. this.m[12] = vector3.x;
  1887. this.m[13] = vector3.y;
  1888. this.m[14] = vector3.z;
  1889. return this;
  1890. };
  1891. Matrix.prototype.getTranslation = function () {
  1892. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1893. };
  1894. Matrix.prototype.multiply = function (other) {
  1895. var result = new Matrix();
  1896. this.multiplyToRef(other, result);
  1897. return result;
  1898. };
  1899. Matrix.prototype.copyFrom = function (other) {
  1900. for (var index = 0; index < 16; index++) {
  1901. this.m[index] = other.m[index];
  1902. }
  1903. return this;
  1904. };
  1905. Matrix.prototype.copyToArray = function (array, offset) {
  1906. if (offset === void 0) { offset = 0; }
  1907. for (var index = 0; index < 16; index++) {
  1908. array[offset + index] = this.m[index];
  1909. }
  1910. return this;
  1911. };
  1912. Matrix.prototype.multiplyToRef = function (other, result) {
  1913. this.multiplyToArray(other, result.m, 0);
  1914. return this;
  1915. };
  1916. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1917. var tm0 = this.m[0];
  1918. var tm1 = this.m[1];
  1919. var tm2 = this.m[2];
  1920. var tm3 = this.m[3];
  1921. var tm4 = this.m[4];
  1922. var tm5 = this.m[5];
  1923. var tm6 = this.m[6];
  1924. var tm7 = this.m[7];
  1925. var tm8 = this.m[8];
  1926. var tm9 = this.m[9];
  1927. var tm10 = this.m[10];
  1928. var tm11 = this.m[11];
  1929. var tm12 = this.m[12];
  1930. var tm13 = this.m[13];
  1931. var tm14 = this.m[14];
  1932. var tm15 = this.m[15];
  1933. var om0 = other.m[0];
  1934. var om1 = other.m[1];
  1935. var om2 = other.m[2];
  1936. var om3 = other.m[3];
  1937. var om4 = other.m[4];
  1938. var om5 = other.m[5];
  1939. var om6 = other.m[6];
  1940. var om7 = other.m[7];
  1941. var om8 = other.m[8];
  1942. var om9 = other.m[9];
  1943. var om10 = other.m[10];
  1944. var om11 = other.m[11];
  1945. var om12 = other.m[12];
  1946. var om13 = other.m[13];
  1947. var om14 = other.m[14];
  1948. var om15 = other.m[15];
  1949. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1950. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1951. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1952. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1953. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1954. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1955. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1956. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1957. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1958. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1959. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1960. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1961. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1962. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1963. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1964. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1965. return this;
  1966. };
  1967. Matrix.prototype.equals = function (value) {
  1968. return value &&
  1969. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1970. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1971. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1972. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1973. };
  1974. Matrix.prototype.clone = function () {
  1975. 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]);
  1976. };
  1977. Matrix.prototype.getClassName = function () {
  1978. return "Matrix";
  1979. };
  1980. Matrix.prototype.getHashCode = function () {
  1981. var hash = this.m[0] || 0;
  1982. for (var i = 1; i < 16; i++) {
  1983. hash = (hash * 397) ^ (this.m[i] || 0);
  1984. }
  1985. return hash;
  1986. };
  1987. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1988. translation.x = this.m[12];
  1989. translation.y = this.m[13];
  1990. translation.z = this.m[14];
  1991. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1992. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1993. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1994. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1995. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1996. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1997. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1998. rotation.x = 0;
  1999. rotation.y = 0;
  2000. rotation.z = 0;
  2001. rotation.w = 1;
  2002. return false;
  2003. }
  2004. 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]);
  2005. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2006. return true;
  2007. };
  2008. Matrix.prototype.getRotationMatrix = function () {
  2009. var result = Matrix.Identity();
  2010. this.getRotationMatrixToRef(result);
  2011. return result;
  2012. };
  2013. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2014. var m = this.m;
  2015. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2016. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2017. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2018. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2019. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2020. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2021. 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);
  2022. };
  2023. // Statics
  2024. Matrix.FromArray = function (array, offset) {
  2025. var result = new Matrix();
  2026. if (!offset) {
  2027. offset = 0;
  2028. }
  2029. Matrix.FromArrayToRef(array, offset, result);
  2030. return result;
  2031. };
  2032. Matrix.FromArrayToRef = function (array, offset, result) {
  2033. for (var index = 0; index < 16; index++) {
  2034. result.m[index] = array[index + offset];
  2035. }
  2036. };
  2037. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2038. for (var index = 0; index < 16; index++) {
  2039. result.m[index] = array[index + offset] * scale;
  2040. }
  2041. };
  2042. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2043. result.m[0] = initialM11;
  2044. result.m[1] = initialM12;
  2045. result.m[2] = initialM13;
  2046. result.m[3] = initialM14;
  2047. result.m[4] = initialM21;
  2048. result.m[5] = initialM22;
  2049. result.m[6] = initialM23;
  2050. result.m[7] = initialM24;
  2051. result.m[8] = initialM31;
  2052. result.m[9] = initialM32;
  2053. result.m[10] = initialM33;
  2054. result.m[11] = initialM34;
  2055. result.m[12] = initialM41;
  2056. result.m[13] = initialM42;
  2057. result.m[14] = initialM43;
  2058. result.m[15] = initialM44;
  2059. };
  2060. Matrix.prototype.getRow = function (index) {
  2061. if (index < 0 || index > 3) {
  2062. return null;
  2063. }
  2064. var i = index * 4;
  2065. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2066. };
  2067. Matrix.prototype.setRow = function (index, row) {
  2068. if (index < 0 || index > 3) {
  2069. return this;
  2070. }
  2071. var i = index * 4;
  2072. this.m[i + 0] = row.x;
  2073. this.m[i + 1] = row.y;
  2074. this.m[i + 2] = row.z;
  2075. this.m[i + 3] = row.w;
  2076. return this;
  2077. };
  2078. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2079. var result = new Matrix();
  2080. result.m[0] = initialM11;
  2081. result.m[1] = initialM12;
  2082. result.m[2] = initialM13;
  2083. result.m[3] = initialM14;
  2084. result.m[4] = initialM21;
  2085. result.m[5] = initialM22;
  2086. result.m[6] = initialM23;
  2087. result.m[7] = initialM24;
  2088. result.m[8] = initialM31;
  2089. result.m[9] = initialM32;
  2090. result.m[10] = initialM33;
  2091. result.m[11] = initialM34;
  2092. result.m[12] = initialM41;
  2093. result.m[13] = initialM42;
  2094. result.m[14] = initialM43;
  2095. result.m[15] = initialM44;
  2096. return result;
  2097. };
  2098. Matrix.Compose = function (scale, rotation, translation) {
  2099. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2100. var rotationMatrix = Matrix.Identity();
  2101. rotation.toRotationMatrix(rotationMatrix);
  2102. result = result.multiply(rotationMatrix);
  2103. result.setTranslation(translation);
  2104. return result;
  2105. };
  2106. Matrix.Identity = function () {
  2107. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2108. };
  2109. Matrix.IdentityToRef = function (result) {
  2110. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2111. };
  2112. Matrix.Zero = function () {
  2113. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2114. };
  2115. Matrix.RotationX = function (angle) {
  2116. var result = new Matrix();
  2117. Matrix.RotationXToRef(angle, result);
  2118. return result;
  2119. };
  2120. Matrix.Invert = function (source) {
  2121. var result = new Matrix();
  2122. source.invertToRef(result);
  2123. return result;
  2124. };
  2125. Matrix.RotationXToRef = function (angle, result) {
  2126. var s = Math.sin(angle);
  2127. var c = Math.cos(angle);
  2128. result.m[0] = 1.0;
  2129. result.m[15] = 1.0;
  2130. result.m[5] = c;
  2131. result.m[10] = c;
  2132. result.m[9] = -s;
  2133. result.m[6] = s;
  2134. result.m[1] = 0;
  2135. result.m[2] = 0;
  2136. result.m[3] = 0;
  2137. result.m[4] = 0;
  2138. result.m[7] = 0;
  2139. result.m[8] = 0;
  2140. result.m[11] = 0;
  2141. result.m[12] = 0;
  2142. result.m[13] = 0;
  2143. result.m[14] = 0;
  2144. };
  2145. Matrix.RotationY = function (angle) {
  2146. var result = new Matrix();
  2147. Matrix.RotationYToRef(angle, result);
  2148. return result;
  2149. };
  2150. Matrix.RotationYToRef = function (angle, result) {
  2151. var s = Math.sin(angle);
  2152. var c = Math.cos(angle);
  2153. result.m[5] = 1.0;
  2154. result.m[15] = 1.0;
  2155. result.m[0] = c;
  2156. result.m[2] = -s;
  2157. result.m[8] = s;
  2158. result.m[10] = c;
  2159. result.m[1] = 0;
  2160. result.m[3] = 0;
  2161. result.m[4] = 0;
  2162. result.m[6] = 0;
  2163. result.m[7] = 0;
  2164. result.m[9] = 0;
  2165. result.m[11] = 0;
  2166. result.m[12] = 0;
  2167. result.m[13] = 0;
  2168. result.m[14] = 0;
  2169. };
  2170. Matrix.RotationZ = function (angle) {
  2171. var result = new Matrix();
  2172. Matrix.RotationZToRef(angle, result);
  2173. return result;
  2174. };
  2175. Matrix.RotationZToRef = function (angle, result) {
  2176. var s = Math.sin(angle);
  2177. var c = Math.cos(angle);
  2178. result.m[10] = 1.0;
  2179. result.m[15] = 1.0;
  2180. result.m[0] = c;
  2181. result.m[1] = s;
  2182. result.m[4] = -s;
  2183. result.m[5] = c;
  2184. result.m[2] = 0;
  2185. result.m[3] = 0;
  2186. result.m[6] = 0;
  2187. result.m[7] = 0;
  2188. result.m[8] = 0;
  2189. result.m[9] = 0;
  2190. result.m[11] = 0;
  2191. result.m[12] = 0;
  2192. result.m[13] = 0;
  2193. result.m[14] = 0;
  2194. };
  2195. Matrix.RotationAxis = function (axis, angle) {
  2196. var result = Matrix.Zero();
  2197. Matrix.RotationAxisToRef(axis, angle, result);
  2198. return result;
  2199. };
  2200. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2201. var s = Math.sin(-angle);
  2202. var c = Math.cos(-angle);
  2203. var c1 = 1 - c;
  2204. axis.normalize();
  2205. result.m[0] = (axis.x * axis.x) * c1 + c;
  2206. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2207. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2208. result.m[3] = 0.0;
  2209. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2210. result.m[5] = (axis.y * axis.y) * c1 + c;
  2211. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2212. result.m[7] = 0.0;
  2213. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2214. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2215. result.m[10] = (axis.z * axis.z) * c1 + c;
  2216. result.m[11] = 0.0;
  2217. result.m[15] = 1.0;
  2218. };
  2219. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2220. var result = new Matrix();
  2221. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2222. return result;
  2223. };
  2224. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2225. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2226. this._tempQuaternion.toRotationMatrix(result);
  2227. };
  2228. Matrix.Scaling = function (x, y, z) {
  2229. var result = Matrix.Zero();
  2230. Matrix.ScalingToRef(x, y, z, result);
  2231. return result;
  2232. };
  2233. Matrix.ScalingToRef = function (x, y, z, result) {
  2234. result.m[0] = x;
  2235. result.m[1] = 0;
  2236. result.m[2] = 0;
  2237. result.m[3] = 0;
  2238. result.m[4] = 0;
  2239. result.m[5] = y;
  2240. result.m[6] = 0;
  2241. result.m[7] = 0;
  2242. result.m[8] = 0;
  2243. result.m[9] = 0;
  2244. result.m[10] = z;
  2245. result.m[11] = 0;
  2246. result.m[12] = 0;
  2247. result.m[13] = 0;
  2248. result.m[14] = 0;
  2249. result.m[15] = 1.0;
  2250. };
  2251. Matrix.Translation = function (x, y, z) {
  2252. var result = Matrix.Identity();
  2253. Matrix.TranslationToRef(x, y, z, result);
  2254. return result;
  2255. };
  2256. Matrix.TranslationToRef = function (x, y, z, result) {
  2257. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2258. };
  2259. Matrix.Lerp = function (startValue, endValue, gradient) {
  2260. var result = Matrix.Zero();
  2261. for (var index = 0; index < 16; index++) {
  2262. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2263. }
  2264. return result;
  2265. };
  2266. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2267. var startScale = new Vector3(0, 0, 0);
  2268. var startRotation = new Quaternion();
  2269. var startTranslation = new Vector3(0, 0, 0);
  2270. startValue.decompose(startScale, startRotation, startTranslation);
  2271. var endScale = new Vector3(0, 0, 0);
  2272. var endRotation = new Quaternion();
  2273. var endTranslation = new Vector3(0, 0, 0);
  2274. endValue.decompose(endScale, endRotation, endTranslation);
  2275. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2276. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2277. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2278. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2279. };
  2280. Matrix.LookAtLH = function (eye, target, up) {
  2281. var result = Matrix.Zero();
  2282. Matrix.LookAtLHToRef(eye, target, up, result);
  2283. return result;
  2284. };
  2285. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2286. // Z axis
  2287. target.subtractToRef(eye, this._zAxis);
  2288. this._zAxis.normalize();
  2289. // X axis
  2290. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2291. if (this._xAxis.lengthSquared() === 0) {
  2292. this._xAxis.x = 1.0;
  2293. }
  2294. else {
  2295. this._xAxis.normalize();
  2296. }
  2297. // Y axis
  2298. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2299. this._yAxis.normalize();
  2300. // Eye angles
  2301. var ex = -Vector3.Dot(this._xAxis, eye);
  2302. var ey = -Vector3.Dot(this._yAxis, eye);
  2303. var ez = -Vector3.Dot(this._zAxis, eye);
  2304. 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);
  2305. };
  2306. Matrix.LookAtRH = function (eye, target, up) {
  2307. var result = Matrix.Zero();
  2308. Matrix.LookAtRHToRef(eye, target, up, result);
  2309. return result;
  2310. };
  2311. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2312. // Z axis
  2313. eye.subtractToRef(target, this._zAxis);
  2314. this._zAxis.normalize();
  2315. // X axis
  2316. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2317. if (this._xAxis.lengthSquared() === 0) {
  2318. this._xAxis.x = 1.0;
  2319. }
  2320. else {
  2321. this._xAxis.normalize();
  2322. }
  2323. // Y axis
  2324. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2325. this._yAxis.normalize();
  2326. // Eye angles
  2327. var ex = -Vector3.Dot(this._xAxis, eye);
  2328. var ey = -Vector3.Dot(this._yAxis, eye);
  2329. var ez = -Vector3.Dot(this._zAxis, eye);
  2330. 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);
  2331. };
  2332. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2333. var matrix = Matrix.Zero();
  2334. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2335. return matrix;
  2336. };
  2337. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2338. var hw = 2.0 / width;
  2339. var hh = 2.0 / height;
  2340. var id = 1.0 / (zfar - znear);
  2341. var nid = znear / (znear - zfar);
  2342. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2343. };
  2344. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2345. var matrix = Matrix.Zero();
  2346. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2347. return matrix;
  2348. };
  2349. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2350. result.m[0] = 2.0 / (right - left);
  2351. result.m[1] = result.m[2] = result.m[3] = 0;
  2352. result.m[5] = 2.0 / (top - bottom);
  2353. result.m[4] = result.m[6] = result.m[7] = 0;
  2354. result.m[10] = 1.0 / (zfar - znear);
  2355. result.m[8] = result.m[9] = result.m[11] = 0;
  2356. result.m[12] = (left + right) / (left - right);
  2357. result.m[13] = (top + bottom) / (bottom - top);
  2358. result.m[14] = -znear / (zfar - znear);
  2359. result.m[15] = 1.0;
  2360. };
  2361. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2362. var matrix = Matrix.Zero();
  2363. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2364. return matrix;
  2365. };
  2366. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2367. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2368. result.m[10] *= -1.0;
  2369. };
  2370. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2371. var matrix = Matrix.Zero();
  2372. matrix.m[0] = (2.0 * znear) / width;
  2373. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2374. matrix.m[5] = (2.0 * znear) / height;
  2375. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2376. matrix.m[10] = -zfar / (znear - zfar);
  2377. matrix.m[8] = matrix.m[9] = 0.0;
  2378. matrix.m[11] = 1.0;
  2379. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2380. matrix.m[14] = (znear * zfar) / (znear - zfar);
  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 tan = 1.0 / (Math.tan(fov * 0.5));
  2391. if (isVerticalFovFixed) {
  2392. result.m[0] = tan / aspect;
  2393. }
  2394. else {
  2395. result.m[0] = tan;
  2396. }
  2397. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2398. if (isVerticalFovFixed) {
  2399. result.m[5] = tan;
  2400. }
  2401. else {
  2402. result.m[5] = tan * aspect;
  2403. }
  2404. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2405. result.m[8] = result.m[9] = 0.0;
  2406. result.m[10] = zfar / (zfar - znear);
  2407. result.m[11] = 1.0;
  2408. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2409. result.m[14] = -(znear * zfar) / (zfar - znear);
  2410. };
  2411. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2412. var matrix = Matrix.Zero();
  2413. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2414. return matrix;
  2415. };
  2416. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2417. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2418. var tan = 1.0 / (Math.tan(fov * 0.5));
  2419. if (isVerticalFovFixed) {
  2420. result.m[0] = tan / aspect;
  2421. }
  2422. else {
  2423. result.m[0] = tan;
  2424. }
  2425. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2426. if (isVerticalFovFixed) {
  2427. result.m[5] = tan;
  2428. }
  2429. else {
  2430. result.m[5] = tan * aspect;
  2431. }
  2432. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2433. result.m[8] = result.m[9] = 0.0;
  2434. result.m[10] = zfar / (znear - zfar);
  2435. result.m[11] = -1.0;
  2436. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2437. result.m[14] = (znear * zfar) / (znear - zfar);
  2438. };
  2439. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2440. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2441. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2442. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2443. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2444. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2445. var xScale = 2.0 / (leftTan + rightTan);
  2446. var yScale = 2.0 / (upTan + downTan);
  2447. result.m[0] = xScale;
  2448. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2449. result.m[5] = yScale;
  2450. result.m[6] = result.m[7] = 0.0;
  2451. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2452. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2453. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2454. result.m[10] = -zfar / (znear - zfar);
  2455. result.m[11] = 1.0;
  2456. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2457. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2458. result.m[14] = (znear * zfar) / (znear - zfar);
  2459. };
  2460. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2461. var cw = viewport.width;
  2462. var ch = viewport.height;
  2463. var cx = viewport.x;
  2464. var cy = viewport.y;
  2465. 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);
  2466. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2467. };
  2468. Matrix.GetAsMatrix2x2 = function (matrix) {
  2469. return new Float32Array([
  2470. matrix.m[0], matrix.m[1],
  2471. matrix.m[4], matrix.m[5]
  2472. ]);
  2473. };
  2474. Matrix.GetAsMatrix3x3 = function (matrix) {
  2475. return new Float32Array([
  2476. matrix.m[0], matrix.m[1], matrix.m[2],
  2477. matrix.m[4], matrix.m[5], matrix.m[6],
  2478. matrix.m[8], matrix.m[9], matrix.m[10]
  2479. ]);
  2480. };
  2481. Matrix.Transpose = function (matrix) {
  2482. var result = new Matrix();
  2483. result.m[0] = matrix.m[0];
  2484. result.m[1] = matrix.m[4];
  2485. result.m[2] = matrix.m[8];
  2486. result.m[3] = matrix.m[12];
  2487. result.m[4] = matrix.m[1];
  2488. result.m[5] = matrix.m[5];
  2489. result.m[6] = matrix.m[9];
  2490. result.m[7] = matrix.m[13];
  2491. result.m[8] = matrix.m[2];
  2492. result.m[9] = matrix.m[6];
  2493. result.m[10] = matrix.m[10];
  2494. result.m[11] = matrix.m[14];
  2495. result.m[12] = matrix.m[3];
  2496. result.m[13] = matrix.m[7];
  2497. result.m[14] = matrix.m[11];
  2498. result.m[15] = matrix.m[15];
  2499. return result;
  2500. };
  2501. Matrix.Reflection = function (plane) {
  2502. var matrix = new Matrix();
  2503. Matrix.ReflectionToRef(plane, matrix);
  2504. return matrix;
  2505. };
  2506. Matrix.ReflectionToRef = function (plane, result) {
  2507. plane.normalize();
  2508. var x = plane.normal.x;
  2509. var y = plane.normal.y;
  2510. var z = plane.normal.z;
  2511. var temp = -2 * x;
  2512. var temp2 = -2 * y;
  2513. var temp3 = -2 * z;
  2514. result.m[0] = (temp * x) + 1;
  2515. result.m[1] = temp2 * x;
  2516. result.m[2] = temp3 * x;
  2517. result.m[3] = 0.0;
  2518. result.m[4] = temp * y;
  2519. result.m[5] = (temp2 * y) + 1;
  2520. result.m[6] = temp3 * y;
  2521. result.m[7] = 0.0;
  2522. result.m[8] = temp * z;
  2523. result.m[9] = temp2 * z;
  2524. result.m[10] = (temp3 * z) + 1;
  2525. result.m[11] = 0.0;
  2526. result.m[12] = temp * plane.d;
  2527. result.m[13] = temp2 * plane.d;
  2528. result.m[14] = temp3 * plane.d;
  2529. result.m[15] = 1.0;
  2530. };
  2531. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2532. mat.m[0] = xaxis.x;
  2533. mat.m[1] = xaxis.y;
  2534. mat.m[2] = xaxis.z;
  2535. mat.m[3] = 0;
  2536. mat.m[4] = yaxis.x;
  2537. mat.m[5] = yaxis.y;
  2538. mat.m[6] = yaxis.z;
  2539. mat.m[7] = 0;
  2540. mat.m[8] = zaxis.x;
  2541. mat.m[9] = zaxis.y;
  2542. mat.m[10] = zaxis.z;
  2543. mat.m[11] = 0;
  2544. mat.m[12] = 0;
  2545. mat.m[13] = 0;
  2546. mat.m[14] = 0;
  2547. mat.m[15] = 1;
  2548. };
  2549. Matrix.FromQuaternionToRef = function (quat, result) {
  2550. var xx = quat.x * quat.x;
  2551. var yy = quat.y * quat.y;
  2552. var zz = quat.z * quat.z;
  2553. var xy = quat.x * quat.y;
  2554. var zw = quat.z * quat.w;
  2555. var zx = quat.z * quat.x;
  2556. var yw = quat.y * quat.w;
  2557. var yz = quat.y * quat.z;
  2558. var xw = quat.x * quat.w;
  2559. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2560. result.m[1] = 2.0 * (xy + zw);
  2561. result.m[2] = 2.0 * (zx - yw);
  2562. result.m[3] = 0;
  2563. result.m[4] = 2.0 * (xy - zw);
  2564. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2565. result.m[6] = 2.0 * (yz + xw);
  2566. result.m[7] = 0;
  2567. result.m[8] = 2.0 * (zx + yw);
  2568. result.m[9] = 2.0 * (yz - xw);
  2569. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2570. result.m[11] = 0;
  2571. result.m[12] = 0;
  2572. result.m[13] = 0;
  2573. result.m[14] = 0;
  2574. result.m[15] = 1.0;
  2575. };
  2576. return Matrix;
  2577. }());
  2578. Matrix._tempQuaternion = new Quaternion();
  2579. Matrix._xAxis = Vector3.Zero();
  2580. Matrix._yAxis = Vector3.Zero();
  2581. Matrix._zAxis = Vector3.Zero();
  2582. BABYLON.Matrix = Matrix;
  2583. var Plane = (function () {
  2584. function Plane(a, b, c, d) {
  2585. this.normal = new Vector3(a, b, c);
  2586. this.d = d;
  2587. }
  2588. Plane.prototype.asArray = function () {
  2589. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2590. };
  2591. // Methods
  2592. Plane.prototype.clone = function () {
  2593. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2594. };
  2595. Plane.prototype.getClassName = function () {
  2596. return "Plane";
  2597. };
  2598. Plane.prototype.getHashCode = function () {
  2599. var hash = this.normal.getHashCode();
  2600. hash = (hash * 397) ^ (this.d || 0);
  2601. return hash;
  2602. };
  2603. Plane.prototype.normalize = function () {
  2604. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2605. var magnitude = 0;
  2606. if (norm !== 0) {
  2607. magnitude = 1.0 / norm;
  2608. }
  2609. this.normal.x *= magnitude;
  2610. this.normal.y *= magnitude;
  2611. this.normal.z *= magnitude;
  2612. this.d *= magnitude;
  2613. return this;
  2614. };
  2615. Plane.prototype.transform = function (transformation) {
  2616. var transposedMatrix = Matrix.Transpose(transformation);
  2617. var x = this.normal.x;
  2618. var y = this.normal.y;
  2619. var z = this.normal.z;
  2620. var d = this.d;
  2621. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2622. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2623. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2624. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2625. return new Plane(normalX, normalY, normalZ, finalD);
  2626. };
  2627. Plane.prototype.dotCoordinate = function (point) {
  2628. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2629. };
  2630. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2631. var x1 = point2.x - point1.x;
  2632. var y1 = point2.y - point1.y;
  2633. var z1 = point2.z - point1.z;
  2634. var x2 = point3.x - point1.x;
  2635. var y2 = point3.y - point1.y;
  2636. var z2 = point3.z - point1.z;
  2637. var yz = (y1 * z2) - (z1 * y2);
  2638. var xz = (z1 * x2) - (x1 * z2);
  2639. var xy = (x1 * y2) - (y1 * x2);
  2640. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2641. var invPyth;
  2642. if (pyth !== 0) {
  2643. invPyth = 1.0 / pyth;
  2644. }
  2645. else {
  2646. invPyth = 0;
  2647. }
  2648. this.normal.x = yz * invPyth;
  2649. this.normal.y = xz * invPyth;
  2650. this.normal.z = xy * invPyth;
  2651. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2652. return this;
  2653. };
  2654. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2655. var dot = Vector3.Dot(this.normal, direction);
  2656. return (dot <= epsilon);
  2657. };
  2658. Plane.prototype.signedDistanceTo = function (point) {
  2659. return Vector3.Dot(point, this.normal) + this.d;
  2660. };
  2661. // Statics
  2662. Plane.FromArray = function (array) {
  2663. return new Plane(array[0], array[1], array[2], array[3]);
  2664. };
  2665. Plane.FromPoints = function (point1, point2, point3) {
  2666. var result = new Plane(0, 0, 0, 0);
  2667. result.copyFromPoints(point1, point2, point3);
  2668. return result;
  2669. };
  2670. Plane.FromPositionAndNormal = function (origin, normal) {
  2671. var result = new Plane(0, 0, 0, 0);
  2672. normal.normalize();
  2673. result.normal = normal;
  2674. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2675. return result;
  2676. };
  2677. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2678. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2679. return Vector3.Dot(point, normal) + d;
  2680. };
  2681. return Plane;
  2682. }());
  2683. BABYLON.Plane = Plane;
  2684. var Viewport = (function () {
  2685. function Viewport(x, y, width, height) {
  2686. this.x = x;
  2687. this.y = y;
  2688. this.width = width;
  2689. this.height = height;
  2690. }
  2691. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2692. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2693. };
  2694. return Viewport;
  2695. }());
  2696. BABYLON.Viewport = Viewport;
  2697. var Frustum = (function () {
  2698. function Frustum() {
  2699. }
  2700. Frustum.GetPlanes = function (transform) {
  2701. var frustumPlanes = [];
  2702. for (var index = 0; index < 6; index++) {
  2703. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2704. }
  2705. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2706. return frustumPlanes;
  2707. };
  2708. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2709. // Near
  2710. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2711. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2712. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2713. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2714. frustumPlanes[0].normalize();
  2715. // Far
  2716. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2717. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2718. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2719. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2720. frustumPlanes[1].normalize();
  2721. // Left
  2722. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2723. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2724. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2725. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2726. frustumPlanes[2].normalize();
  2727. // Right
  2728. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2729. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2730. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2731. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2732. frustumPlanes[3].normalize();
  2733. // Top
  2734. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2735. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2736. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2737. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2738. frustumPlanes[4].normalize();
  2739. // Bottom
  2740. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2741. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2742. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2743. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2744. frustumPlanes[5].normalize();
  2745. };
  2746. return Frustum;
  2747. }());
  2748. BABYLON.Frustum = Frustum;
  2749. var Space;
  2750. (function (Space) {
  2751. Space[Space["LOCAL"] = 0] = "LOCAL";
  2752. Space[Space["WORLD"] = 1] = "WORLD";
  2753. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2754. var Axis = (function () {
  2755. function Axis() {
  2756. }
  2757. return Axis;
  2758. }());
  2759. Axis.X = new Vector3(1, 0, 0);
  2760. Axis.Y = new Vector3(0, 1, 0);
  2761. Axis.Z = new Vector3(0, 0, 1);
  2762. BABYLON.Axis = Axis;
  2763. ;
  2764. var BezierCurve = (function () {
  2765. function BezierCurve() {
  2766. }
  2767. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2768. // Extract X (which is equal to time here)
  2769. var f0 = 1 - 3 * x2 + 3 * x1;
  2770. var f1 = 3 * x2 - 6 * x1;
  2771. var f2 = 3 * x1;
  2772. var refinedT = t;
  2773. for (var i = 0; i < 5; i++) {
  2774. var refinedT2 = refinedT * refinedT;
  2775. var refinedT3 = refinedT2 * refinedT;
  2776. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2777. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2778. refinedT -= (x - t) * slope;
  2779. refinedT = Math.min(1, Math.max(0, refinedT));
  2780. }
  2781. // Resolve cubic bezier for the given x
  2782. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2783. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2784. Math.pow(refinedT, 3);
  2785. };
  2786. return BezierCurve;
  2787. }());
  2788. BABYLON.BezierCurve = BezierCurve;
  2789. var Orientation;
  2790. (function (Orientation) {
  2791. Orientation[Orientation["CW"] = 0] = "CW";
  2792. Orientation[Orientation["CCW"] = 1] = "CCW";
  2793. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2794. var Angle = (function () {
  2795. function Angle(radians) {
  2796. var _this = this;
  2797. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2798. this.radians = function () { return _this._radians; };
  2799. this._radians = radians;
  2800. if (this._radians < 0)
  2801. this._radians += (2 * Math.PI);
  2802. }
  2803. Angle.BetweenTwoPoints = function (a, b) {
  2804. var delta = b.subtract(a);
  2805. var theta = Math.atan2(delta.y, delta.x);
  2806. return new Angle(theta);
  2807. };
  2808. Angle.FromRadians = function (radians) {
  2809. return new Angle(radians);
  2810. };
  2811. Angle.FromDegrees = function (degrees) {
  2812. return new Angle(degrees * Math.PI / 180);
  2813. };
  2814. return Angle;
  2815. }());
  2816. BABYLON.Angle = Angle;
  2817. var Arc2 = (function () {
  2818. function Arc2(startPoint, midPoint, endPoint) {
  2819. this.startPoint = startPoint;
  2820. this.midPoint = midPoint;
  2821. this.endPoint = endPoint;
  2822. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2823. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2824. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2825. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2826. 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);
  2827. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2828. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2829. var a1 = this.startAngle.degrees();
  2830. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2831. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2832. // angles correction
  2833. if (a2 - a1 > +180.0)
  2834. a2 -= 360.0;
  2835. if (a2 - a1 < -180.0)
  2836. a2 += 360.0;
  2837. if (a3 - a2 > +180.0)
  2838. a3 -= 360.0;
  2839. if (a3 - a2 < -180.0)
  2840. a3 += 360.0;
  2841. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2842. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2843. }
  2844. return Arc2;
  2845. }());
  2846. BABYLON.Arc2 = Arc2;
  2847. var Path2 = (function () {
  2848. function Path2(x, y) {
  2849. this._points = new Array();
  2850. this._length = 0;
  2851. this.closed = false;
  2852. this._points.push(new Vector2(x, y));
  2853. }
  2854. Path2.prototype.addLineTo = function (x, y) {
  2855. if (closed) {
  2856. //Tools.Error("cannot add lines to closed paths");
  2857. return this;
  2858. }
  2859. var newPoint = new Vector2(x, y);
  2860. var previousPoint = this._points[this._points.length - 1];
  2861. this._points.push(newPoint);
  2862. this._length += newPoint.subtract(previousPoint).length();
  2863. return this;
  2864. };
  2865. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2866. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2867. if (closed) {
  2868. //Tools.Error("cannot add arcs to closed paths");
  2869. return this;
  2870. }
  2871. var startPoint = this._points[this._points.length - 1];
  2872. var midPoint = new Vector2(midX, midY);
  2873. var endPoint = new Vector2(endX, endY);
  2874. var arc = new Arc2(startPoint, midPoint, endPoint);
  2875. var increment = arc.angle.radians() / numberOfSegments;
  2876. if (arc.orientation === Orientation.CW)
  2877. increment *= -1;
  2878. var currentAngle = arc.startAngle.radians() + increment;
  2879. for (var i = 0; i < numberOfSegments; i++) {
  2880. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2881. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2882. this.addLineTo(x, y);
  2883. currentAngle += increment;
  2884. }
  2885. return this;
  2886. };
  2887. Path2.prototype.close = function () {
  2888. this.closed = true;
  2889. return this;
  2890. };
  2891. Path2.prototype.length = function () {
  2892. var result = this._length;
  2893. if (!this.closed) {
  2894. var lastPoint = this._points[this._points.length - 1];
  2895. var firstPoint = this._points[0];
  2896. result += (firstPoint.subtract(lastPoint).length());
  2897. }
  2898. return result;
  2899. };
  2900. Path2.prototype.getPoints = function () {
  2901. return this._points;
  2902. };
  2903. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2904. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2905. //Tools.Error("normalized length position should be between 0 and 1.");
  2906. return Vector2.Zero();
  2907. }
  2908. var lengthPosition = normalizedLengthPosition * this.length();
  2909. var previousOffset = 0;
  2910. for (var i = 0; i < this._points.length; i++) {
  2911. var j = (i + 1) % this._points.length;
  2912. var a = this._points[i];
  2913. var b = this._points[j];
  2914. var bToA = b.subtract(a);
  2915. var nextOffset = (bToA.length() + previousOffset);
  2916. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2917. var dir = bToA.normalize();
  2918. var localOffset = lengthPosition - previousOffset;
  2919. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2920. }
  2921. previousOffset = nextOffset;
  2922. }
  2923. //Tools.Error("internal error");
  2924. return Vector2.Zero();
  2925. };
  2926. Path2.StartingAt = function (x, y) {
  2927. return new Path2(x, y);
  2928. };
  2929. return Path2;
  2930. }());
  2931. BABYLON.Path2 = Path2;
  2932. var Path3D = (function () {
  2933. /**
  2934. * new Path3D(path, normal, raw)
  2935. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2936. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2937. * path : an array of Vector3, the curve axis of the Path3D
  2938. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2939. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2940. */
  2941. function Path3D(path, firstNormal, raw) {
  2942. this.path = path;
  2943. this._curve = new Array();
  2944. this._distances = new Array();
  2945. this._tangents = new Array();
  2946. this._normals = new Array();
  2947. this._binormals = new Array();
  2948. for (var p = 0; p < path.length; p++) {
  2949. this._curve[p] = path[p].clone(); // hard copy
  2950. }
  2951. this._raw = raw || false;
  2952. this._compute(firstNormal);
  2953. }
  2954. /**
  2955. * Returns the Path3D array of successive Vector3 designing its curve.
  2956. */
  2957. Path3D.prototype.getCurve = function () {
  2958. return this._curve;
  2959. };
  2960. /**
  2961. * Returns an array populated with tangent vectors on each Path3D curve point.
  2962. */
  2963. Path3D.prototype.getTangents = function () {
  2964. return this._tangents;
  2965. };
  2966. /**
  2967. * Returns an array populated with normal vectors on each Path3D curve point.
  2968. */
  2969. Path3D.prototype.getNormals = function () {
  2970. return this._normals;
  2971. };
  2972. /**
  2973. * Returns an array populated with binormal vectors on each Path3D curve point.
  2974. */
  2975. Path3D.prototype.getBinormals = function () {
  2976. return this._binormals;
  2977. };
  2978. /**
  2979. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2980. */
  2981. Path3D.prototype.getDistances = function () {
  2982. return this._distances;
  2983. };
  2984. /**
  2985. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2986. * Returns the same object updated.
  2987. */
  2988. Path3D.prototype.update = function (path, firstNormal) {
  2989. for (var p = 0; p < path.length; p++) {
  2990. this._curve[p].x = path[p].x;
  2991. this._curve[p].y = path[p].y;
  2992. this._curve[p].z = path[p].z;
  2993. }
  2994. this._compute(firstNormal);
  2995. return this;
  2996. };
  2997. // private function compute() : computes tangents, normals and binormals
  2998. Path3D.prototype._compute = function (firstNormal) {
  2999. var l = this._curve.length;
  3000. // first and last tangents
  3001. this._tangents[0] = this._getFirstNonNullVector(0);
  3002. if (!this._raw) {
  3003. this._tangents[0].normalize();
  3004. }
  3005. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  3006. if (!this._raw) {
  3007. this._tangents[l - 1].normalize();
  3008. }
  3009. // normals and binormals at first point : arbitrary vector with _normalVector()
  3010. var tg0 = this._tangents[0];
  3011. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  3012. this._normals[0] = pp0;
  3013. if (!this._raw) {
  3014. this._normals[0].normalize();
  3015. }
  3016. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  3017. if (!this._raw) {
  3018. this._binormals[0].normalize();
  3019. }
  3020. this._distances[0] = 0.0;
  3021. // normals and binormals : next points
  3022. var prev; // previous vector (segment)
  3023. var cur; // current vector (segment)
  3024. var curTang; // current tangent
  3025. // previous normal
  3026. var prevBinor; // previous binormal
  3027. for (var i = 1; i < l; i++) {
  3028. // tangents
  3029. prev = this._getLastNonNullVector(i);
  3030. if (i < l - 1) {
  3031. cur = this._getFirstNonNullVector(i);
  3032. this._tangents[i] = prev.add(cur);
  3033. this._tangents[i].normalize();
  3034. }
  3035. this._distances[i] = this._distances[i - 1] + prev.length();
  3036. // normals and binormals
  3037. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3038. curTang = this._tangents[i];
  3039. prevBinor = this._binormals[i - 1];
  3040. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3041. if (!this._raw) {
  3042. this._normals[i].normalize();
  3043. }
  3044. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3045. if (!this._raw) {
  3046. this._binormals[i].normalize();
  3047. }
  3048. }
  3049. };
  3050. // private function getFirstNonNullVector(index)
  3051. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3052. Path3D.prototype._getFirstNonNullVector = function (index) {
  3053. var i = 1;
  3054. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3055. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3056. i++;
  3057. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3058. }
  3059. return nNVector;
  3060. };
  3061. // private function getLastNonNullVector(index)
  3062. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3063. Path3D.prototype._getLastNonNullVector = function (index) {
  3064. var i = 1;
  3065. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3066. while (nLVector.length() === 0 && index > i + 1) {
  3067. i++;
  3068. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3069. }
  3070. return nLVector;
  3071. };
  3072. // private function normalVector(v0, vt, va) :
  3073. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3074. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3075. Path3D.prototype._normalVector = function (v0, vt, va) {
  3076. var normal0;
  3077. var tgl = vt.length();
  3078. if (tgl === 0.0) {
  3079. tgl = 1.0;
  3080. }
  3081. if (va === undefined || va === null) {
  3082. var point;
  3083. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3084. point = new Vector3(0.0, -1.0, 0.0);
  3085. }
  3086. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3087. point = new Vector3(1.0, 0.0, 0.0);
  3088. }
  3089. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3090. point = new Vector3(0.0, 0.0, 1.0);
  3091. }
  3092. normal0 = Vector3.Cross(vt, point);
  3093. }
  3094. else {
  3095. normal0 = Vector3.Cross(vt, va);
  3096. Vector3.CrossToRef(normal0, vt, normal0);
  3097. }
  3098. normal0.normalize();
  3099. return normal0;
  3100. };
  3101. return Path3D;
  3102. }());
  3103. BABYLON.Path3D = Path3D;
  3104. var Curve3 = (function () {
  3105. /**
  3106. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3107. * A Curve3 is designed from a series of successive Vector3.
  3108. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3109. */
  3110. function Curve3(points) {
  3111. this._length = 0.0;
  3112. this._points = points;
  3113. this._length = this._computeLength(points);
  3114. }
  3115. /**
  3116. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3118. * @param v1 (Vector3) the control point
  3119. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3120. * @param nbPoints (integer) the wanted number of points in the curve
  3121. */
  3122. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3123. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3124. var bez = new Array();
  3125. var equation = function (t, val0, val1, val2) {
  3126. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3127. return res;
  3128. };
  3129. for (var i = 0; i <= nbPoints; i++) {
  3130. 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)));
  3131. }
  3132. return new Curve3(bez);
  3133. };
  3134. /**
  3135. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3136. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3137. * @param v1 (Vector3) the first control point
  3138. * @param v2 (Vector3) the second control point
  3139. * @param v3 (Vector3) the end point of the Cubic Bezier
  3140. * @param nbPoints (integer) the wanted number of points in the curve
  3141. */
  3142. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3143. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3144. var bez = new Array();
  3145. var equation = function (t, val0, val1, val2, val3) {
  3146. 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;
  3147. return res;
  3148. };
  3149. for (var i = 0; i <= nbPoints; i++) {
  3150. 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)));
  3151. }
  3152. return new Curve3(bez);
  3153. };
  3154. /**
  3155. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3156. * @param p1 (Vector3) the origin point of the Hermite Spline
  3157. * @param t1 (Vector3) the tangent vector at the origin point
  3158. * @param p2 (Vector3) the end point of the Hermite Spline
  3159. * @param t2 (Vector3) the tangent vector at the end point
  3160. * @param nbPoints (integer) the wanted number of points in the curve
  3161. */
  3162. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3163. var hermite = new Array();
  3164. var step = 1.0 / nbPoints;
  3165. for (var i = 0; i <= nbPoints; i++) {
  3166. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3167. }
  3168. return new Curve3(hermite);
  3169. };
  3170. /**
  3171. * Returns the Curve3 stored array of successive Vector3
  3172. */
  3173. Curve3.prototype.getPoints = function () {
  3174. return this._points;
  3175. };
  3176. /**
  3177. * Returns the computed length (float) of the curve.
  3178. */
  3179. Curve3.prototype.length = function () {
  3180. return this._length;
  3181. };
  3182. /**
  3183. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3184. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3185. * curveA and curveB keep unchanged.
  3186. */
  3187. Curve3.prototype.continue = function (curve) {
  3188. var lastPoint = this._points[this._points.length - 1];
  3189. var continuedPoints = this._points.slice();
  3190. var curvePoints = curve.getPoints();
  3191. for (var i = 1; i < curvePoints.length; i++) {
  3192. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3193. }
  3194. var continuedCurve = new Curve3(continuedPoints);
  3195. return continuedCurve;
  3196. };
  3197. Curve3.prototype._computeLength = function (path) {
  3198. var l = 0;
  3199. for (var i = 1; i < path.length; i++) {
  3200. l += (path[i].subtract(path[i - 1])).length();
  3201. }
  3202. return l;
  3203. };
  3204. return Curve3;
  3205. }());
  3206. BABYLON.Curve3 = Curve3;
  3207. // SphericalHarmonics
  3208. var SphericalHarmonics = (function () {
  3209. function SphericalHarmonics() {
  3210. this.L00 = Vector3.Zero();
  3211. this.L1_1 = Vector3.Zero();
  3212. this.L10 = Vector3.Zero();
  3213. this.L11 = Vector3.Zero();
  3214. this.L2_2 = Vector3.Zero();
  3215. this.L2_1 = Vector3.Zero();
  3216. this.L20 = Vector3.Zero();
  3217. this.L21 = Vector3.Zero();
  3218. this.L22 = Vector3.Zero();
  3219. }
  3220. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3221. var colorVector = new Vector3(color.r, color.g, color.b);
  3222. var c = colorVector.scale(deltaSolidAngle);
  3223. this.L00 = this.L00.add(c.scale(0.282095));
  3224. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3225. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3226. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3227. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3228. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3229. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3230. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3231. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3232. };
  3233. SphericalHarmonics.prototype.scale = function (scale) {
  3234. this.L00 = this.L00.scale(scale);
  3235. this.L1_1 = this.L1_1.scale(scale);
  3236. this.L10 = this.L10.scale(scale);
  3237. this.L11 = this.L11.scale(scale);
  3238. this.L2_2 = this.L2_2.scale(scale);
  3239. this.L2_1 = this.L2_1.scale(scale);
  3240. this.L20 = this.L20.scale(scale);
  3241. this.L21 = this.L21.scale(scale);
  3242. this.L22 = this.L22.scale(scale);
  3243. };
  3244. return SphericalHarmonics;
  3245. }());
  3246. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3247. // SphericalPolynomial
  3248. var SphericalPolynomial = (function () {
  3249. function SphericalPolynomial() {
  3250. this.x = Vector3.Zero();
  3251. this.y = Vector3.Zero();
  3252. this.z = Vector3.Zero();
  3253. this.xx = Vector3.Zero();
  3254. this.yy = Vector3.Zero();
  3255. this.zz = Vector3.Zero();
  3256. this.xy = Vector3.Zero();
  3257. this.yz = Vector3.Zero();
  3258. this.zx = Vector3.Zero();
  3259. }
  3260. SphericalPolynomial.prototype.addAmbient = function (color) {
  3261. var colorVector = new Vector3(color.r, color.g, color.b);
  3262. this.xx = this.xx.add(colorVector);
  3263. this.yy = this.yy.add(colorVector);
  3264. this.zz = this.zz.add(colorVector);
  3265. };
  3266. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3267. var result = new SphericalPolynomial();
  3268. result.x = harmonics.L11.scale(1.02333);
  3269. result.y = harmonics.L1_1.scale(1.02333);
  3270. result.z = harmonics.L10.scale(1.02333);
  3271. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3272. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3273. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3274. result.yz = harmonics.L2_1.scale(0.858086);
  3275. result.zx = harmonics.L21.scale(0.858086);
  3276. result.xy = harmonics.L2_2.scale(0.858086);
  3277. return result;
  3278. };
  3279. return SphericalPolynomial;
  3280. }());
  3281. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3282. // Vertex formats
  3283. var PositionNormalVertex = (function () {
  3284. function PositionNormalVertex(position, normal) {
  3285. if (position === void 0) { position = Vector3.Zero(); }
  3286. if (normal === void 0) { normal = Vector3.Up(); }
  3287. this.position = position;
  3288. this.normal = normal;
  3289. }
  3290. PositionNormalVertex.prototype.clone = function () {
  3291. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3292. };
  3293. return PositionNormalVertex;
  3294. }());
  3295. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3296. var PositionNormalTextureVertex = (function () {
  3297. function PositionNormalTextureVertex(position, normal, uv) {
  3298. if (position === void 0) { position = Vector3.Zero(); }
  3299. if (normal === void 0) { normal = Vector3.Up(); }
  3300. if (uv === void 0) { uv = Vector2.Zero(); }
  3301. this.position = position;
  3302. this.normal = normal;
  3303. this.uv = uv;
  3304. }
  3305. PositionNormalTextureVertex.prototype.clone = function () {
  3306. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3307. };
  3308. return PositionNormalTextureVertex;
  3309. }());
  3310. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3311. // Temporary pre-allocated objects for engine internal use
  3312. // usage in any internal function :
  3313. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3314. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3315. var Tmp = (function () {
  3316. function Tmp() {
  3317. }
  3318. return Tmp;
  3319. }());
  3320. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3321. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3322. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3323. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3324. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3325. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3326. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3327. Matrix.Zero(), Matrix.Zero(),
  3328. Matrix.Zero(), Matrix.Zero(),
  3329. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3330. BABYLON.Tmp = Tmp;
  3331. })(BABYLON || (BABYLON = {}));
  3332. //# sourceMappingURL=babylon.math.js.map
  3333. //# sourceMappingURL=babylon.mixins.js.map
  3334. var BABYLON;
  3335. (function (BABYLON) {
  3336. function generateSerializableMember(type, sourceName) {
  3337. return function (target, propertyKey) {
  3338. if (!target.__serializableMembers) {
  3339. target.__serializableMembers = {};
  3340. }
  3341. if (!target.__serializableMembers[propertyKey]) {
  3342. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3343. }
  3344. };
  3345. }
  3346. function serialize(sourceName) {
  3347. return generateSerializableMember(0, sourceName); // value member
  3348. }
  3349. BABYLON.serialize = serialize;
  3350. function serializeAsTexture(sourceName) {
  3351. return generateSerializableMember(1, sourceName); // texture member
  3352. }
  3353. BABYLON.serializeAsTexture = serializeAsTexture;
  3354. function serializeAsColor3(sourceName) {
  3355. return generateSerializableMember(2, sourceName); // color3 member
  3356. }
  3357. BABYLON.serializeAsColor3 = serializeAsColor3;
  3358. function serializeAsFresnelParameters(sourceName) {
  3359. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3360. }
  3361. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3362. function serializeAsVector2(sourceName) {
  3363. return generateSerializableMember(4, sourceName); // vector2 member
  3364. }
  3365. BABYLON.serializeAsVector2 = serializeAsVector2;
  3366. function serializeAsVector3(sourceName) {
  3367. return generateSerializableMember(5, sourceName); // vector3 member
  3368. }
  3369. BABYLON.serializeAsVector3 = serializeAsVector3;
  3370. function serializeAsMeshReference(sourceName) {
  3371. return generateSerializableMember(6, sourceName); // mesh reference member
  3372. }
  3373. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3374. function serializeAsColorCurves(sourceName) {
  3375. return generateSerializableMember(7, sourceName); // color curves
  3376. }
  3377. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3378. var SerializationHelper = (function () {
  3379. function SerializationHelper() {
  3380. }
  3381. SerializationHelper.Serialize = function (entity, serializationObject) {
  3382. if (!serializationObject) {
  3383. serializationObject = {};
  3384. }
  3385. // Tags
  3386. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3387. // Properties
  3388. for (var property in entity.__serializableMembers) {
  3389. var propertyDescriptor = entity.__serializableMembers[property];
  3390. var targetPropertyName = propertyDescriptor.sourceName || property;
  3391. var propertyType = propertyDescriptor.type;
  3392. var sourceProperty = entity[property];
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0:
  3396. serializationObject[targetPropertyName] = sourceProperty;
  3397. break;
  3398. case 1:
  3399. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3400. break;
  3401. case 2:
  3402. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3403. break;
  3404. case 3:
  3405. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3406. break;
  3407. case 4:
  3408. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3409. break;
  3410. case 5:
  3411. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3412. break;
  3413. case 6:
  3414. serializationObject[targetPropertyName] = sourceProperty.id;
  3415. break;
  3416. case 7:
  3417. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3418. break;
  3419. }
  3420. }
  3421. }
  3422. return serializationObject;
  3423. };
  3424. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3425. var destination = creationFunction();
  3426. // Tags
  3427. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3428. // Properties
  3429. for (var property in destination.__serializableMembers) {
  3430. var propertyDescriptor = destination.__serializableMembers[property];
  3431. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3432. var propertyType = propertyDescriptor.type;
  3433. if (sourceProperty !== undefined && sourceProperty !== null) {
  3434. switch (propertyType) {
  3435. case 0:
  3436. destination[property] = sourceProperty;
  3437. break;
  3438. case 1:
  3439. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3440. break;
  3441. case 2:
  3442. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3443. break;
  3444. case 3:
  3445. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3446. break;
  3447. case 4:
  3448. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3449. break;
  3450. case 5:
  3451. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3452. break;
  3453. case 6:
  3454. destination[property] = scene.getLastMeshByID(sourceProperty);
  3455. break;
  3456. case 7:
  3457. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3458. break;
  3459. }
  3460. }
  3461. }
  3462. return destination;
  3463. };
  3464. SerializationHelper.Clone = function (creationFunction, source) {
  3465. var destination = creationFunction();
  3466. // Tags
  3467. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3468. // Properties
  3469. for (var property in destination.__serializableMembers) {
  3470. var propertyDescriptor = destination.__serializableMembers[property];
  3471. var sourceProperty = source[property];
  3472. var propertyType = propertyDescriptor.type;
  3473. if (sourceProperty !== undefined && sourceProperty !== null) {
  3474. switch (propertyType) {
  3475. case 0: // Value
  3476. case 6:
  3477. destination[property] = sourceProperty;
  3478. break;
  3479. case 1: // Texture
  3480. case 2: // Color3
  3481. case 3: // FresnelParameters
  3482. case 4: // Vector2
  3483. case 5: // Vector3
  3484. case 7:
  3485. destination[property] = sourceProperty.clone();
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. return destination;
  3491. };
  3492. return SerializationHelper;
  3493. }());
  3494. BABYLON.SerializationHelper = SerializationHelper;
  3495. })(BABYLON || (BABYLON = {}));
  3496. //# sourceMappingURL=babylon.decorators.js.map
  3497. var BABYLON;
  3498. (function (BABYLON) {
  3499. /**
  3500. * A class serves as a medium between the observable and its observers
  3501. */
  3502. var EventState = (function () {
  3503. /**
  3504. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3505. */
  3506. function EventState(mask, skipNextObservers) {
  3507. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3508. this.initalize(mask, skipNextObservers);
  3509. }
  3510. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3511. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3512. this.mask = mask;
  3513. this.skipNextObservers = skipNextObservers;
  3514. return this;
  3515. };
  3516. return EventState;
  3517. }());
  3518. BABYLON.EventState = EventState;
  3519. /**
  3520. * Represent an Observer registered to a given Observable object.
  3521. */
  3522. var Observer = (function () {
  3523. function Observer(callback, mask) {
  3524. this.callback = callback;
  3525. this.mask = mask;
  3526. }
  3527. return Observer;
  3528. }());
  3529. BABYLON.Observer = Observer;
  3530. /**
  3531. * The Observable class is a simple implementation of the Observable pattern.
  3532. * 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.
  3533. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3534. * 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).
  3535. * 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.
  3536. */
  3537. var Observable = (function () {
  3538. function Observable() {
  3539. this._observers = new Array();
  3540. this._eventState = new EventState(0);
  3541. }
  3542. /**
  3543. * Create a new Observer with the specified callback
  3544. * @param callback the callback that will be executed for that Observer
  3545. * @param mask the mask used to filter observers
  3546. * @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.
  3547. */
  3548. Observable.prototype.add = function (callback, mask, insertFirst) {
  3549. if (mask === void 0) { mask = -1; }
  3550. if (insertFirst === void 0) { insertFirst = false; }
  3551. if (!callback) {
  3552. return null;
  3553. }
  3554. var observer = new Observer(callback, mask);
  3555. if (insertFirst) {
  3556. this._observers.unshift(observer);
  3557. }
  3558. else {
  3559. this._observers.push(observer);
  3560. }
  3561. return observer;
  3562. };
  3563. /**
  3564. * Remove an Observer from the Observable object
  3565. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3566. */
  3567. Observable.prototype.remove = function (observer) {
  3568. var index = this._observers.indexOf(observer);
  3569. if (index !== -1) {
  3570. this._observers.splice(index, 1);
  3571. return true;
  3572. }
  3573. return false;
  3574. };
  3575. /**
  3576. * Remove a callback from the Observable object
  3577. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3578. */
  3579. Observable.prototype.removeCallback = function (callback) {
  3580. for (var index = 0; index < this._observers.length; index++) {
  3581. if (this._observers[index].callback === callback) {
  3582. this._observers.splice(index, 1);
  3583. return true;
  3584. }
  3585. }
  3586. return false;
  3587. };
  3588. /**
  3589. * Notify all Observers by calling their respective callback with the given data
  3590. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3591. * @param eventData
  3592. * @param mask
  3593. */
  3594. Observable.prototype.notifyObservers = function (eventData, mask) {
  3595. if (mask === void 0) { mask = -1; }
  3596. var state = this._eventState;
  3597. state.mask = mask;
  3598. state.skipNextObservers = false;
  3599. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3600. var obs = _a[_i];
  3601. if (obs.mask & mask) {
  3602. obs.callback(eventData, state);
  3603. }
  3604. if (state.skipNextObservers) {
  3605. return false;
  3606. }
  3607. }
  3608. return true;
  3609. };
  3610. /**
  3611. * return true is the Observable has at least one Observer registered
  3612. */
  3613. Observable.prototype.hasObservers = function () {
  3614. return this._observers.length > 0;
  3615. };
  3616. /**
  3617. * Clear the list of observers
  3618. */
  3619. Observable.prototype.clear = function () {
  3620. this._observers = new Array();
  3621. };
  3622. /**
  3623. * Clone the current observable
  3624. */
  3625. Observable.prototype.clone = function () {
  3626. var result = new Observable();
  3627. result._observers = this._observers.slice(0);
  3628. return result;
  3629. };
  3630. return Observable;
  3631. }());
  3632. BABYLON.Observable = Observable;
  3633. })(BABYLON || (BABYLON = {}));
  3634. //# sourceMappingURL=babylon.observable.js.map
  3635. var BABYLON;
  3636. (function (BABYLON) {
  3637. var Database = (function () {
  3638. function Database(urlToScene, callbackManifestChecked) {
  3639. // Handling various flavors of prefixed version of IndexedDB
  3640. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3641. this.callbackManifestChecked = callbackManifestChecked;
  3642. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3643. this.db = null;
  3644. this.enableSceneOffline = false;
  3645. this.enableTexturesOffline = false;
  3646. this.manifestVersionFound = 0;
  3647. this.mustUpdateRessources = false;
  3648. this.hasReachedQuota = false;
  3649. if (!Database.IDBStorageEnabled) {
  3650. this.callbackManifestChecked(true);
  3651. }
  3652. else {
  3653. this.checkManifestFile();
  3654. }
  3655. }
  3656. Database.prototype.checkManifestFile = function () {
  3657. var _this = this;
  3658. function noManifestFile() {
  3659. that.enableSceneOffline = false;
  3660. that.enableTexturesOffline = false;
  3661. that.callbackManifestChecked(false);
  3662. }
  3663. var that = this;
  3664. var timeStampUsed = false;
  3665. var manifestURL = this.currentSceneUrl + ".manifest";
  3666. var xhr = new XMLHttpRequest();
  3667. if (navigator.onLine) {
  3668. // Adding a timestamp to by-pass browsers' cache
  3669. timeStampUsed = true;
  3670. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3671. }
  3672. xhr.open("GET", manifestURL, true);
  3673. xhr.addEventListener("load", function () {
  3674. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3675. try {
  3676. var manifestFile = JSON.parse(xhr.response);
  3677. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3678. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3679. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3680. _this.manifestVersionFound = manifestFile.version;
  3681. }
  3682. if (_this.callbackManifestChecked) {
  3683. _this.callbackManifestChecked(true);
  3684. }
  3685. }
  3686. catch (ex) {
  3687. noManifestFile();
  3688. }
  3689. }
  3690. else {
  3691. noManifestFile();
  3692. }
  3693. }, false);
  3694. xhr.addEventListener("error", function (event) {
  3695. if (timeStampUsed) {
  3696. timeStampUsed = false;
  3697. // Let's retry without the timeStamp
  3698. // It could fail when coupled with HTML5 Offline API
  3699. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3700. xhr.open("GET", retryManifestURL, true);
  3701. xhr.send();
  3702. }
  3703. else {
  3704. noManifestFile();
  3705. }
  3706. }, false);
  3707. try {
  3708. xhr.send();
  3709. }
  3710. catch (ex) {
  3711. BABYLON.Tools.Error("Error on XHR send request.");
  3712. that.callbackManifestChecked(false);
  3713. }
  3714. };
  3715. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3716. var _this = this;
  3717. function handleError() {
  3718. that.isSupported = false;
  3719. if (errorCallback)
  3720. errorCallback();
  3721. }
  3722. var that = this;
  3723. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3724. // Your browser doesn't support IndexedDB
  3725. this.isSupported = false;
  3726. if (errorCallback)
  3727. errorCallback();
  3728. }
  3729. else {
  3730. // If the DB hasn't been opened or created yet
  3731. if (!this.db) {
  3732. this.hasReachedQuota = false;
  3733. this.isSupported = true;
  3734. var request = this.idbFactory.open("babylonjs", 1);
  3735. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3736. request.onerror = function (event) {
  3737. handleError();
  3738. };
  3739. // executes when a version change transaction cannot complete due to other active transactions
  3740. request.onblocked = function (event) {
  3741. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3742. handleError();
  3743. };
  3744. // DB has been opened successfully
  3745. request.onsuccess = function (event) {
  3746. _this.db = request.result;
  3747. successCallback();
  3748. };
  3749. // Initialization of the DB. Creating Scenes & Textures stores
  3750. request.onupgradeneeded = function (event) {
  3751. _this.db = (event.target).result;
  3752. try {
  3753. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3754. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3755. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3756. }
  3757. catch (ex) {
  3758. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3759. handleError();
  3760. }
  3761. };
  3762. }
  3763. else {
  3764. if (successCallback)
  3765. successCallback();
  3766. }
  3767. }
  3768. };
  3769. Database.prototype.loadImageFromDB = function (url, image) {
  3770. var _this = this;
  3771. var completeURL = Database.ReturnFullUrlLocation(url);
  3772. var saveAndLoadImage = function () {
  3773. if (!_this.hasReachedQuota && _this.db !== null) {
  3774. // the texture is not yet in the DB, let's try to save it
  3775. _this._saveImageIntoDBAsync(completeURL, image);
  3776. }
  3777. else {
  3778. image.src = url;
  3779. }
  3780. };
  3781. if (!this.mustUpdateRessources) {
  3782. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3783. }
  3784. else {
  3785. saveAndLoadImage();
  3786. }
  3787. };
  3788. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3789. if (this.isSupported && this.db !== null) {
  3790. var texture;
  3791. var transaction = this.db.transaction(["textures"]);
  3792. transaction.onabort = function (event) {
  3793. image.src = url;
  3794. };
  3795. transaction.oncomplete = function (event) {
  3796. var blobTextureURL;
  3797. if (texture) {
  3798. var URL = window.URL || window.webkitURL;
  3799. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3800. image.onerror = function () {
  3801. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3802. image.src = url;
  3803. };
  3804. image.src = blobTextureURL;
  3805. }
  3806. else {
  3807. notInDBCallback();
  3808. }
  3809. };
  3810. var getRequest = transaction.objectStore("textures").get(url);
  3811. getRequest.onsuccess = function (event) {
  3812. texture = (event.target).result;
  3813. };
  3814. getRequest.onerror = function (event) {
  3815. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3816. image.src = url;
  3817. };
  3818. }
  3819. else {
  3820. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3821. image.src = url;
  3822. }
  3823. };
  3824. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3825. var _this = this;
  3826. if (this.isSupported) {
  3827. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3828. var generateBlobUrl = function () {
  3829. var blobTextureURL;
  3830. if (blob) {
  3831. var URL = window.URL || window.webkitURL;
  3832. try {
  3833. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3834. }
  3835. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3836. catch (ex) {
  3837. blobTextureURL = URL.createObjectURL(blob);
  3838. }
  3839. }
  3840. image.src = blobTextureURL;
  3841. };
  3842. if (Database.IsUASupportingBlobStorage) {
  3843. var xhr = new XMLHttpRequest(), blob;
  3844. xhr.open("GET", url, true);
  3845. xhr.responseType = "blob";
  3846. xhr.addEventListener("load", function () {
  3847. if (xhr.status === 200) {
  3848. // Blob as response (XHR2)
  3849. blob = xhr.response;
  3850. var transaction = _this.db.transaction(["textures"], "readwrite");
  3851. // the transaction could abort because of a QuotaExceededError error
  3852. transaction.onabort = function (event) {
  3853. try {
  3854. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3855. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3856. _this.hasReachedQuota = true;
  3857. }
  3858. }
  3859. catch (ex) { }
  3860. generateBlobUrl();
  3861. };
  3862. transaction.oncomplete = function (event) {
  3863. generateBlobUrl();
  3864. };
  3865. var newTexture = { textureUrl: url, data: blob };
  3866. try {
  3867. // Put the blob into the dabase
  3868. var addRequest = transaction.objectStore("textures").put(newTexture);
  3869. addRequest.onsuccess = function (event) {
  3870. };
  3871. addRequest.onerror = function (event) {
  3872. generateBlobUrl();
  3873. };
  3874. }
  3875. catch (ex) {
  3876. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3877. if (ex.code === 25) {
  3878. Database.IsUASupportingBlobStorage = false;
  3879. }
  3880. image.src = url;
  3881. }
  3882. }
  3883. else {
  3884. image.src = url;
  3885. }
  3886. }, false);
  3887. xhr.addEventListener("error", function (event) {
  3888. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3889. image.src = url;
  3890. }, false);
  3891. xhr.send();
  3892. }
  3893. else {
  3894. image.src = url;
  3895. }
  3896. }
  3897. else {
  3898. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3899. image.src = url;
  3900. }
  3901. };
  3902. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3903. var _this = this;
  3904. var updateVersion = function (event) {
  3905. // the version is not yet in the DB or we need to update it
  3906. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3907. };
  3908. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3909. };
  3910. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3911. var _this = this;
  3912. if (this.isSupported) {
  3913. var version;
  3914. try {
  3915. var transaction = this.db.transaction(["versions"]);
  3916. transaction.oncomplete = function (event) {
  3917. if (version) {
  3918. // If the version in the JSON file is > than the version in DB
  3919. if (_this.manifestVersionFound > version.data) {
  3920. _this.mustUpdateRessources = true;
  3921. updateInDBCallback();
  3922. }
  3923. else {
  3924. callback(version.data);
  3925. }
  3926. }
  3927. else {
  3928. _this.mustUpdateRessources = true;
  3929. updateInDBCallback();
  3930. }
  3931. };
  3932. transaction.onabort = function (event) {
  3933. callback(-1);
  3934. };
  3935. var getRequest = transaction.objectStore("versions").get(url);
  3936. getRequest.onsuccess = function (event) {
  3937. version = (event.target).result;
  3938. };
  3939. getRequest.onerror = function (event) {
  3940. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3941. callback(-1);
  3942. };
  3943. }
  3944. catch (ex) {
  3945. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3946. callback(-1);
  3947. }
  3948. }
  3949. else {
  3950. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3951. callback(-1);
  3952. }
  3953. };
  3954. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3955. var _this = this;
  3956. if (this.isSupported && !this.hasReachedQuota) {
  3957. try {
  3958. // Open a transaction to the database
  3959. var transaction = this.db.transaction(["versions"], "readwrite");
  3960. // the transaction could abort because of a QuotaExceededError error
  3961. transaction.onabort = function (event) {
  3962. try {
  3963. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3964. _this.hasReachedQuota = true;
  3965. }
  3966. }
  3967. catch (ex) { }
  3968. callback(-1);
  3969. };
  3970. transaction.oncomplete = function (event) {
  3971. callback(_this.manifestVersionFound);
  3972. };
  3973. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3974. // Put the scene into the database
  3975. var addRequest = transaction.objectStore("versions").put(newVersion);
  3976. addRequest.onsuccess = function (event) {
  3977. };
  3978. addRequest.onerror = function (event) {
  3979. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3980. };
  3981. }
  3982. catch (ex) {
  3983. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3984. callback(-1);
  3985. }
  3986. }
  3987. else {
  3988. callback(-1);
  3989. }
  3990. };
  3991. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3992. var _this = this;
  3993. var completeUrl = Database.ReturnFullUrlLocation(url);
  3994. var saveAndLoadFile = function (event) {
  3995. // the scene is not yet in the DB, let's try to save it
  3996. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3997. };
  3998. this._checkVersionFromDB(completeUrl, function (version) {
  3999. if (version !== -1) {
  4000. if (!_this.mustUpdateRessources) {
  4001. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  4002. }
  4003. else {
  4004. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  4005. }
  4006. }
  4007. else {
  4008. errorCallback();
  4009. }
  4010. });
  4011. };
  4012. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  4013. if (this.isSupported) {
  4014. var targetStore;
  4015. if (url.indexOf(".babylon") !== -1) {
  4016. targetStore = "scenes";
  4017. }
  4018. else {
  4019. targetStore = "textures";
  4020. }
  4021. var file;
  4022. var transaction = this.db.transaction([targetStore]);
  4023. transaction.oncomplete = function (event) {
  4024. if (file) {
  4025. callback(file.data);
  4026. }
  4027. else {
  4028. notInDBCallback();
  4029. }
  4030. };
  4031. transaction.onabort = function (event) {
  4032. notInDBCallback();
  4033. };
  4034. var getRequest = transaction.objectStore(targetStore).get(url);
  4035. getRequest.onsuccess = function (event) {
  4036. file = (event.target).result;
  4037. };
  4038. getRequest.onerror = function (event) {
  4039. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4040. notInDBCallback();
  4041. };
  4042. }
  4043. else {
  4044. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4045. callback();
  4046. }
  4047. };
  4048. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4049. var _this = this;
  4050. if (this.isSupported) {
  4051. var targetStore;
  4052. if (url.indexOf(".babylon") !== -1) {
  4053. targetStore = "scenes";
  4054. }
  4055. else {
  4056. targetStore = "textures";
  4057. }
  4058. // Create XHR
  4059. var xhr = new XMLHttpRequest(), fileData;
  4060. xhr.open("GET", url, true);
  4061. if (useArrayBuffer) {
  4062. xhr.responseType = "arraybuffer";
  4063. }
  4064. xhr.onprogress = progressCallback;
  4065. xhr.addEventListener("load", function () {
  4066. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4067. // Blob as response (XHR2)
  4068. //fileData = xhr.responseText;
  4069. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4070. if (!_this.hasReachedQuota) {
  4071. // Open a transaction to the database
  4072. var transaction = _this.db.transaction([targetStore], "readwrite");
  4073. // the transaction could abort because of a QuotaExceededError error
  4074. transaction.onabort = function (event) {
  4075. try {
  4076. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4077. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4078. _this.hasReachedQuota = true;
  4079. }
  4080. }
  4081. catch (ex) { }
  4082. callback(fileData);
  4083. };
  4084. transaction.oncomplete = function (event) {
  4085. callback(fileData);
  4086. };
  4087. var newFile;
  4088. if (targetStore === "scenes") {
  4089. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4090. }
  4091. else {
  4092. newFile = { textureUrl: url, data: fileData };
  4093. }
  4094. try {
  4095. // Put the scene into the database
  4096. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4097. addRequest.onsuccess = function (event) {
  4098. };
  4099. addRequest.onerror = function (event) {
  4100. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4101. };
  4102. }
  4103. catch (ex) {
  4104. callback(fileData);
  4105. }
  4106. }
  4107. else {
  4108. callback(fileData);
  4109. }
  4110. }
  4111. else {
  4112. callback();
  4113. }
  4114. }, false);
  4115. xhr.addEventListener("error", function (event) {
  4116. BABYLON.Tools.Error("error on XHR request.");
  4117. callback();
  4118. }, false);
  4119. xhr.send();
  4120. }
  4121. else {
  4122. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4123. callback();
  4124. }
  4125. };
  4126. return Database;
  4127. }());
  4128. Database.IsUASupportingBlobStorage = true;
  4129. Database.IDBStorageEnabled = true;
  4130. Database.parseURL = function (url) {
  4131. var a = document.createElement('a');
  4132. a.href = url;
  4133. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4134. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4135. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4136. return absLocation;
  4137. };
  4138. Database.ReturnFullUrlLocation = function (url) {
  4139. if (url.indexOf("http:/") === -1) {
  4140. return (Database.parseURL(window.location.href) + url);
  4141. }
  4142. else {
  4143. return url;
  4144. }
  4145. };
  4146. BABYLON.Database = Database;
  4147. })(BABYLON || (BABYLON = {}));
  4148. //# sourceMappingURL=babylon.database.js.map
  4149. var BABYLON;
  4150. (function (BABYLON) {
  4151. var Internals;
  4152. (function (Internals) {
  4153. /*
  4154. * Based on jsTGALoader - Javascript loader for TGA file
  4155. * By Vincent Thibault
  4156. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4157. */
  4158. var TGATools = (function () {
  4159. function TGATools() {
  4160. }
  4161. TGATools.GetTGAHeader = function (data) {
  4162. var offset = 0;
  4163. var header = {
  4164. id_length: data[offset++],
  4165. colormap_type: data[offset++],
  4166. image_type: data[offset++],
  4167. colormap_index: data[offset++] | data[offset++] << 8,
  4168. colormap_length: data[offset++] | data[offset++] << 8,
  4169. colormap_size: data[offset++],
  4170. origin: [
  4171. data[offset++] | data[offset++] << 8,
  4172. data[offset++] | data[offset++] << 8
  4173. ],
  4174. width: data[offset++] | data[offset++] << 8,
  4175. height: data[offset++] | data[offset++] << 8,
  4176. pixel_size: data[offset++],
  4177. flags: data[offset++]
  4178. };
  4179. return header;
  4180. };
  4181. TGATools.UploadContent = function (gl, data) {
  4182. // Not enough data to contain header ?
  4183. if (data.length < 19) {
  4184. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4185. return;
  4186. }
  4187. // Read Header
  4188. var offset = 18;
  4189. var header = TGATools.GetTGAHeader(data);
  4190. // Assume it's a valid Targa file.
  4191. if (header.id_length + offset > data.length) {
  4192. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4193. return;
  4194. }
  4195. // Skip not needed data
  4196. offset += header.id_length;
  4197. var use_rle = false;
  4198. var use_pal = false;
  4199. var use_rgb = false;
  4200. var use_grey = false;
  4201. // Get some informations.
  4202. switch (header.image_type) {
  4203. case TGATools._TYPE_RLE_INDEXED:
  4204. use_rle = true;
  4205. case TGATools._TYPE_INDEXED:
  4206. use_pal = true;
  4207. break;
  4208. case TGATools._TYPE_RLE_RGB:
  4209. use_rle = true;
  4210. case TGATools._TYPE_RGB:
  4211. use_rgb = true;
  4212. break;
  4213. case TGATools._TYPE_RLE_GREY:
  4214. use_rle = true;
  4215. case TGATools._TYPE_GREY:
  4216. use_grey = true;
  4217. break;
  4218. }
  4219. var pixel_data;
  4220. var numAlphaBits = header.flags & 0xf;
  4221. var pixel_size = header.pixel_size >> 3;
  4222. var pixel_total = header.width * header.height * pixel_size;
  4223. // Read palettes
  4224. var palettes;
  4225. if (use_pal) {
  4226. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4227. }
  4228. // Read LRE
  4229. if (use_rle) {
  4230. pixel_data = new Uint8Array(pixel_total);
  4231. var c, count, i;
  4232. var localOffset = 0;
  4233. var pixels = new Uint8Array(pixel_size);
  4234. while (offset < pixel_total && localOffset < pixel_total) {
  4235. c = data[offset++];
  4236. count = (c & 0x7f) + 1;
  4237. // RLE pixels
  4238. if (c & 0x80) {
  4239. // Bind pixel tmp array
  4240. for (i = 0; i < pixel_size; ++i) {
  4241. pixels[i] = data[offset++];
  4242. }
  4243. // Copy pixel array
  4244. for (i = 0; i < count; ++i) {
  4245. pixel_data.set(pixels, localOffset + i * pixel_size);
  4246. }
  4247. localOffset += pixel_size * count;
  4248. }
  4249. else {
  4250. count *= pixel_size;
  4251. for (i = 0; i < count; ++i) {
  4252. pixel_data[localOffset + i] = data[offset++];
  4253. }
  4254. localOffset += count;
  4255. }
  4256. }
  4257. }
  4258. else {
  4259. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4260. }
  4261. // Load to texture
  4262. var x_start, y_start, x_step, y_step, y_end, x_end;
  4263. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4264. default:
  4265. case TGATools._ORIGIN_UL:
  4266. x_start = 0;
  4267. x_step = 1;
  4268. x_end = header.width;
  4269. y_start = 0;
  4270. y_step = 1;
  4271. y_end = header.height;
  4272. break;
  4273. case TGATools._ORIGIN_BL:
  4274. x_start = 0;
  4275. x_step = 1;
  4276. x_end = header.width;
  4277. y_start = header.height - 1;
  4278. y_step = -1;
  4279. y_end = -1;
  4280. break;
  4281. case TGATools._ORIGIN_UR:
  4282. x_start = header.width - 1;
  4283. x_step = -1;
  4284. x_end = -1;
  4285. y_start = 0;
  4286. y_step = 1;
  4287. y_end = header.height;
  4288. break;
  4289. case TGATools._ORIGIN_BR:
  4290. x_start = header.width - 1;
  4291. x_step = -1;
  4292. x_end = -1;
  4293. y_start = header.height - 1;
  4294. y_step = -1;
  4295. y_end = -1;
  4296. break;
  4297. }
  4298. // Load the specify method
  4299. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4300. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4301. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4302. };
  4303. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4304. var image = pixel_data, colormap = palettes;
  4305. var width = header.width, height = header.height;
  4306. var color, i = 0, x, y;
  4307. var imageData = new Uint8Array(width * height * 4);
  4308. for (y = y_start; y !== y_end; y += y_step) {
  4309. for (x = x_start; x !== x_end; x += x_step, i++) {
  4310. color = image[i];
  4311. imageData[(x + width * y) * 4 + 3] = 255;
  4312. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4313. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4314. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4315. }
  4316. }
  4317. return imageData;
  4318. };
  4319. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4320. var image = pixel_data;
  4321. var width = header.width, height = header.height;
  4322. var color, i = 0, x, y;
  4323. var imageData = new Uint8Array(width * height * 4);
  4324. for (y = y_start; y !== y_end; y += y_step) {
  4325. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4326. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4327. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4328. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4329. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4330. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4331. }
  4332. }
  4333. return imageData;
  4334. };
  4335. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4336. var image = pixel_data;
  4337. var width = header.width, height = header.height;
  4338. var i = 0, x, y;
  4339. var imageData = new Uint8Array(width * height * 4);
  4340. for (y = y_start; y !== y_end; y += y_step) {
  4341. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4342. imageData[(x + width * y) * 4 + 3] = 255;
  4343. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4344. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4345. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4346. }
  4347. }
  4348. return imageData;
  4349. };
  4350. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4351. var image = pixel_data;
  4352. var width = header.width, height = header.height;
  4353. var i = 0, x, y;
  4354. var imageData = new Uint8Array(width * height * 4);
  4355. for (y = y_start; y !== y_end; y += y_step) {
  4356. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4357. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4358. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4359. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4360. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4361. }
  4362. }
  4363. return imageData;
  4364. };
  4365. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4366. var image = pixel_data;
  4367. var width = header.width, height = header.height;
  4368. var color, i = 0, x, y;
  4369. var imageData = new Uint8Array(width * height * 4);
  4370. for (y = y_start; y !== y_end; y += y_step) {
  4371. for (x = x_start; x !== x_end; x += x_step, i++) {
  4372. color = image[i];
  4373. imageData[(x + width * y) * 4 + 0] = color;
  4374. imageData[(x + width * y) * 4 + 1] = color;
  4375. imageData[(x + width * y) * 4 + 2] = color;
  4376. imageData[(x + width * y) * 4 + 3] = 255;
  4377. }
  4378. }
  4379. return imageData;
  4380. };
  4381. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4382. var image = pixel_data;
  4383. var width = header.width, height = header.height;
  4384. var i = 0, x, y;
  4385. var imageData = new Uint8Array(width * height * 4);
  4386. for (y = y_start; y !== y_end; y += y_step) {
  4387. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4388. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4389. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4390. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4391. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4392. }
  4393. }
  4394. return imageData;
  4395. };
  4396. return TGATools;
  4397. }());
  4398. TGATools._TYPE_NO_DATA = 0;
  4399. TGATools._TYPE_INDEXED = 1;
  4400. TGATools._TYPE_RGB = 2;
  4401. TGATools._TYPE_GREY = 3;
  4402. TGATools._TYPE_RLE_INDEXED = 9;
  4403. TGATools._TYPE_RLE_RGB = 10;
  4404. TGATools._TYPE_RLE_GREY = 11;
  4405. TGATools._ORIGIN_MASK = 0x30;
  4406. TGATools._ORIGIN_SHIFT = 0x04;
  4407. TGATools._ORIGIN_BL = 0x00;
  4408. TGATools._ORIGIN_BR = 0x01;
  4409. TGATools._ORIGIN_UL = 0x02;
  4410. TGATools._ORIGIN_UR = 0x03;
  4411. Internals.TGATools = TGATools;
  4412. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4413. })(BABYLON || (BABYLON = {}));
  4414. //# sourceMappingURL=babylon.tools.tga.js.map
  4415. var BABYLON;
  4416. (function (BABYLON) {
  4417. var SmartArray = (function () {
  4418. function SmartArray(capacity) {
  4419. this.length = 0;
  4420. this._duplicateId = 0;
  4421. this.data = new Array(capacity);
  4422. this._id = SmartArray._GlobalId++;
  4423. }
  4424. SmartArray.prototype.push = function (value) {
  4425. this.data[this.length++] = value;
  4426. if (this.length > this.data.length) {
  4427. this.data.length *= 2;
  4428. }
  4429. if (!value.__smartArrayFlags) {
  4430. value.__smartArrayFlags = {};
  4431. }
  4432. value.__smartArrayFlags[this._id] = this._duplicateId;
  4433. };
  4434. SmartArray.prototype.pushNoDuplicate = function (value) {
  4435. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4436. return false;
  4437. }
  4438. this.push(value);
  4439. return true;
  4440. };
  4441. SmartArray.prototype.sort = function (compareFn) {
  4442. this.data.sort(compareFn);
  4443. };
  4444. SmartArray.prototype.reset = function () {
  4445. this.length = 0;
  4446. this._duplicateId++;
  4447. };
  4448. SmartArray.prototype.concat = function (array) {
  4449. if (array.length === 0) {
  4450. return;
  4451. }
  4452. if (this.length + array.length > this.data.length) {
  4453. this.data.length = (this.length + array.length) * 2;
  4454. }
  4455. for (var index = 0; index < array.length; index++) {
  4456. this.data[this.length++] = (array.data || array)[index];
  4457. }
  4458. };
  4459. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4460. if (array.length === 0) {
  4461. return;
  4462. }
  4463. if (this.length + array.length > this.data.length) {
  4464. this.data.length = (this.length + array.length) * 2;
  4465. }
  4466. for (var index = 0; index < array.length; index++) {
  4467. var item = (array.data || array)[index];
  4468. this.pushNoDuplicate(item);
  4469. }
  4470. };
  4471. SmartArray.prototype.indexOf = function (value) {
  4472. var position = this.data.indexOf(value);
  4473. if (position >= this.length) {
  4474. return -1;
  4475. }
  4476. return position;
  4477. };
  4478. return SmartArray;
  4479. }());
  4480. // Statics
  4481. SmartArray._GlobalId = 0;
  4482. BABYLON.SmartArray = SmartArray;
  4483. })(BABYLON || (BABYLON = {}));
  4484. //# sourceMappingURL=babylon.smartArray.js.map
  4485. var BABYLON;
  4486. (function (BABYLON) {
  4487. /**
  4488. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4489. * The underlying implementation relies on an associative array to ensure the best performances.
  4490. * The value can be anything including 'null' but except 'undefined'
  4491. */
  4492. var StringDictionary = (function () {
  4493. function StringDictionary() {
  4494. this._count = 0;
  4495. this._data = {};
  4496. }
  4497. /**
  4498. * This will clear this dictionary and copy the content from the 'source' one.
  4499. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4500. * @param source the dictionary to take the content from and copy to this dictionary
  4501. */
  4502. StringDictionary.prototype.copyFrom = function (source) {
  4503. var _this = this;
  4504. this.clear();
  4505. source.forEach(function (t, v) { return _this.add(t, v); });
  4506. };
  4507. /**
  4508. * Get a value based from its key
  4509. * @param key the given key to get the matching value from
  4510. * @return the value if found, otherwise undefined is returned
  4511. */
  4512. StringDictionary.prototype.get = function (key) {
  4513. var val = this._data[key];
  4514. if (val !== undefined) {
  4515. return val;
  4516. }
  4517. return undefined;
  4518. };
  4519. /**
  4520. * Get a value from its key or add it if it doesn't exist.
  4521. * This method will ensure you that a given key/data will be present in the dictionary.
  4522. * @param key the given key to get the matching value from
  4523. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4524. * The factory will only be invoked if there's no data for the given key.
  4525. * @return the value corresponding to the key.
  4526. */
  4527. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4528. var val = this.get(key);
  4529. if (val !== undefined) {
  4530. return val;
  4531. }
  4532. val = factory(key);
  4533. if (val) {
  4534. this.add(key, val);
  4535. }
  4536. return val;
  4537. };
  4538. /**
  4539. * Get a value from its key if present in the dictionary otherwise add it
  4540. * @param key the key to get the value from
  4541. * @param val if there's no such key/value pair in the dictionary add it with this value
  4542. * @return the value corresponding to the key
  4543. */
  4544. StringDictionary.prototype.getOrAdd = function (key, val) {
  4545. var curVal = this.get(key);
  4546. if (curVal !== undefined) {
  4547. return curVal;
  4548. }
  4549. this.add(key, val);
  4550. return val;
  4551. };
  4552. /**
  4553. * Check if there's a given key in the dictionary
  4554. * @param key the key to check for
  4555. * @return true if the key is present, false otherwise
  4556. */
  4557. StringDictionary.prototype.contains = function (key) {
  4558. return this._data[key] !== undefined;
  4559. };
  4560. /**
  4561. * Add a new key and its corresponding value
  4562. * @param key the key to add
  4563. * @param value the value corresponding to the key
  4564. * @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
  4565. */
  4566. StringDictionary.prototype.add = function (key, value) {
  4567. if (this._data[key] !== undefined) {
  4568. return false;
  4569. }
  4570. this._data[key] = value;
  4571. ++this._count;
  4572. return true;
  4573. };
  4574. StringDictionary.prototype.set = function (key, value) {
  4575. if (this._data[key] === undefined) {
  4576. return false;
  4577. }
  4578. this._data[key] = value;
  4579. return true;
  4580. };
  4581. /**
  4582. * Get the element of the given key and remove it from the dictionary
  4583. * @param key
  4584. */
  4585. StringDictionary.prototype.getAndRemove = function (key) {
  4586. var val = this.get(key);
  4587. if (val !== undefined) {
  4588. delete this._data[key];
  4589. --this._count;
  4590. return val;
  4591. }
  4592. return null;
  4593. };
  4594. /**
  4595. * Remove a key/value from the dictionary.
  4596. * @param key the key to remove
  4597. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4598. */
  4599. StringDictionary.prototype.remove = function (key) {
  4600. if (this.contains(key)) {
  4601. delete this._data[key];
  4602. --this._count;
  4603. return true;
  4604. }
  4605. return false;
  4606. };
  4607. /**
  4608. * Clear the whole content of the dictionary
  4609. */
  4610. StringDictionary.prototype.clear = function () {
  4611. this._data = {};
  4612. this._count = 0;
  4613. };
  4614. Object.defineProperty(StringDictionary.prototype, "count", {
  4615. get: function () {
  4616. return this._count;
  4617. },
  4618. enumerable: true,
  4619. configurable: true
  4620. });
  4621. /**
  4622. * Execute a callback on each key/val of the dictionary.
  4623. * Note that you can remove any element in this dictionary in the callback implementation
  4624. * @param callback the callback to execute on a given key/value pair
  4625. */
  4626. StringDictionary.prototype.forEach = function (callback) {
  4627. for (var cur in this._data) {
  4628. var val = this._data[cur];
  4629. callback(cur, val);
  4630. }
  4631. };
  4632. /**
  4633. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4634. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4635. * Note that you can remove any element in this dictionary in the callback implementation
  4636. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4637. */
  4638. StringDictionary.prototype.first = function (callback) {
  4639. for (var cur in this._data) {
  4640. var val = this._data[cur];
  4641. var res = callback(cur, val);
  4642. if (res) {
  4643. return res;
  4644. }
  4645. }
  4646. return null;
  4647. };
  4648. return StringDictionary;
  4649. }());
  4650. BABYLON.StringDictionary = StringDictionary;
  4651. })(BABYLON || (BABYLON = {}));
  4652. //# sourceMappingURL=babylon.stringDictionary.js.map
  4653. var BABYLON;
  4654. (function (BABYLON) {
  4655. // Screenshots
  4656. var screenshotCanvas;
  4657. var cloneValue = function (source, destinationObject) {
  4658. if (!source)
  4659. return null;
  4660. if (source instanceof BABYLON.Mesh) {
  4661. return null;
  4662. }
  4663. if (source instanceof BABYLON.SubMesh) {
  4664. return source.clone(destinationObject);
  4665. }
  4666. else if (source.clone) {
  4667. return source.clone();
  4668. }
  4669. return null;
  4670. };
  4671. var Tools = (function () {
  4672. function Tools() {
  4673. }
  4674. Tools.Instantiate = function (className) {
  4675. var arr = className.split(".");
  4676. var fn = (window || this);
  4677. for (var i = 0, len = arr.length; i < len; i++) {
  4678. fn = fn[arr[i]];
  4679. }
  4680. if (typeof fn !== "function") {
  4681. return null;
  4682. }
  4683. return fn;
  4684. };
  4685. Tools.SetImmediate = function (action) {
  4686. if (window.setImmediate) {
  4687. window.setImmediate(action);
  4688. }
  4689. else {
  4690. setTimeout(action, 1);
  4691. }
  4692. };
  4693. Tools.IsExponentOfTwo = function (value) {
  4694. var count = 1;
  4695. do {
  4696. count *= 2;
  4697. } while (count < value);
  4698. return count === value;
  4699. };
  4700. Tools.GetExponentOfTwo = function (value, max) {
  4701. var count = 1;
  4702. do {
  4703. count *= 2;
  4704. } while (count < value);
  4705. if (count > max)
  4706. count = max;
  4707. return count;
  4708. };
  4709. Tools.GetFilename = function (path) {
  4710. var index = path.lastIndexOf("/");
  4711. if (index < 0)
  4712. return path;
  4713. return path.substring(index + 1);
  4714. };
  4715. Tools.GetDOMTextContent = function (element) {
  4716. var result = "";
  4717. var child = element.firstChild;
  4718. while (child) {
  4719. if (child.nodeType === 3) {
  4720. result += child.textContent;
  4721. }
  4722. child = child.nextSibling;
  4723. }
  4724. return result;
  4725. };
  4726. Tools.ToDegrees = function (angle) {
  4727. return angle * 180 / Math.PI;
  4728. };
  4729. Tools.ToRadians = function (angle) {
  4730. return angle * Math.PI / 180;
  4731. };
  4732. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4733. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4734. var output = "";
  4735. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4736. var i = 0;
  4737. var bytes = new Uint8Array(buffer);
  4738. while (i < bytes.length) {
  4739. chr1 = bytes[i++];
  4740. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4741. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4742. enc1 = chr1 >> 2;
  4743. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4744. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4745. enc4 = chr3 & 63;
  4746. if (isNaN(chr2)) {
  4747. enc3 = enc4 = 64;
  4748. }
  4749. else if (isNaN(chr3)) {
  4750. enc4 = 64;
  4751. }
  4752. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4753. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4754. }
  4755. return "data:image/png;base64," + output;
  4756. };
  4757. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4758. if (bias === void 0) { bias = null; }
  4759. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4760. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4761. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4762. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4763. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4764. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4765. }
  4766. if (bias) {
  4767. minimum.x -= minimum.x * bias.x + bias.y;
  4768. minimum.y -= minimum.y * bias.x + bias.y;
  4769. minimum.z -= minimum.z * bias.x + bias.y;
  4770. maximum.x += maximum.x * bias.x + bias.y;
  4771. maximum.y += maximum.y * bias.x + bias.y;
  4772. maximum.z += maximum.z * bias.x + bias.y;
  4773. }
  4774. return {
  4775. minimum: minimum,
  4776. maximum: maximum
  4777. };
  4778. };
  4779. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4780. if (bias === void 0) { bias = null; }
  4781. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4782. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4783. if (!stride) {
  4784. stride = 3;
  4785. }
  4786. for (var index = start; index < start + count; index++) {
  4787. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4788. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4789. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4790. }
  4791. if (bias) {
  4792. minimum.x -= minimum.x * bias.x + bias.y;
  4793. minimum.y -= minimum.y * bias.x + bias.y;
  4794. minimum.z -= minimum.z * bias.x + bias.y;
  4795. maximum.x += maximum.x * bias.x + bias.y;
  4796. maximum.y += maximum.y * bias.x + bias.y;
  4797. maximum.z += maximum.z * bias.x + bias.y;
  4798. }
  4799. return {
  4800. minimum: minimum,
  4801. maximum: maximum
  4802. };
  4803. };
  4804. Tools.Vector2ArrayFeeder = function (array) {
  4805. return function (index) {
  4806. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4807. var length = isFloatArray ? array.length / 2 : array.length;
  4808. if (index >= length) {
  4809. return null;
  4810. }
  4811. if (isFloatArray) {
  4812. var fa = array;
  4813. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4814. }
  4815. var a = array;
  4816. return a[index];
  4817. };
  4818. };
  4819. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4820. if (bias === void 0) { bias = null; }
  4821. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4822. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4823. var i = 0;
  4824. var cur = feeder(i++);
  4825. while (cur) {
  4826. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4827. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4828. cur = feeder(i++);
  4829. }
  4830. if (bias) {
  4831. minimum.x -= minimum.x * bias.x + bias.y;
  4832. minimum.y -= minimum.y * bias.x + bias.y;
  4833. maximum.x += maximum.x * bias.x + bias.y;
  4834. maximum.y += maximum.y * bias.x + bias.y;
  4835. }
  4836. return {
  4837. minimum: minimum,
  4838. maximum: maximum
  4839. };
  4840. };
  4841. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4842. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4843. return undefined;
  4844. return Array.isArray(obj) ? obj : [obj];
  4845. };
  4846. // Misc.
  4847. Tools.GetPointerPrefix = function () {
  4848. var eventPrefix = "pointer";
  4849. // Check if pointer events are supported
  4850. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4851. eventPrefix = "mouse";
  4852. }
  4853. return eventPrefix;
  4854. };
  4855. /**
  4856. * @param func - the function to be called
  4857. * @param requester - the object that will request the next frame. Falls back to window.
  4858. */
  4859. Tools.QueueNewFrame = function (func, requester) {
  4860. if (requester === void 0) { requester = window; }
  4861. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4862. /*if(requester.isPresenting) {
  4863. return;
  4864. } else*/ if (requester.requestAnimationFrame)
  4865. requester.requestAnimationFrame(func);
  4866. else if (requester.msRequestAnimationFrame)
  4867. requester.msRequestAnimationFrame(func);
  4868. else if (requester.webkitRequestAnimationFrame)
  4869. requester.webkitRequestAnimationFrame(func);
  4870. else if (requester.mozRequestAnimationFrame)
  4871. requester.mozRequestAnimationFrame(func);
  4872. else if (requester.oRequestAnimationFrame)
  4873. requester.oRequestAnimationFrame(func);
  4874. else {
  4875. window.setTimeout(func, 16);
  4876. }
  4877. };
  4878. Tools.RequestFullscreen = function (element) {
  4879. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4880. if (!requestFunction)
  4881. return;
  4882. requestFunction.call(element);
  4883. };
  4884. Tools.ExitFullscreen = function () {
  4885. if (document.exitFullscreen) {
  4886. document.exitFullscreen();
  4887. }
  4888. else if (document.mozCancelFullScreen) {
  4889. document.mozCancelFullScreen();
  4890. }
  4891. else if (document.webkitCancelFullScreen) {
  4892. document.webkitCancelFullScreen();
  4893. }
  4894. else if (document.msCancelFullScreen) {
  4895. document.msCancelFullScreen();
  4896. }
  4897. };
  4898. Tools.SetCorsBehavior = function (url, img) {
  4899. if (Tools.CorsBehavior) {
  4900. switch (typeof (Tools.CorsBehavior)) {
  4901. case "function":
  4902. var result = Tools.CorsBehavior(url);
  4903. if (result) {
  4904. return result;
  4905. }
  4906. break;
  4907. case "string":
  4908. default:
  4909. img.crossOrigin = Tools.CorsBehavior;
  4910. break;
  4911. }
  4912. }
  4913. };
  4914. // External files
  4915. Tools.CleanUrl = function (url) {
  4916. url = url.replace(/#/mg, "%23");
  4917. return url;
  4918. };
  4919. Tools.LoadImage = function (url, onload, onerror, database) {
  4920. if (url instanceof ArrayBuffer) {
  4921. url = Tools.EncodeArrayBufferTobase64(url);
  4922. }
  4923. url = Tools.CleanUrl(url);
  4924. var img = new Image();
  4925. if (url.substr(0, 5) !== "data:") {
  4926. Tools.SetCorsBehavior(url, img);
  4927. }
  4928. img.onload = function () {
  4929. onload(img);
  4930. };
  4931. img.onerror = function (err) {
  4932. Tools.Error("Error while trying to load texture: " + url);
  4933. if (Tools.UseFallbackTexture) {
  4934. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4935. onload(img);
  4936. }
  4937. else {
  4938. onerror();
  4939. }
  4940. };
  4941. var noIndexedDB = function () {
  4942. img.src = url;
  4943. };
  4944. var loadFromIndexedDB = function () {
  4945. database.loadImageFromDB(url, img);
  4946. };
  4947. //ANY database to do!
  4948. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4949. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4950. }
  4951. else {
  4952. if (url.indexOf("file:") === -1) {
  4953. noIndexedDB();
  4954. }
  4955. else {
  4956. try {
  4957. var textureName = url.substring(5).toLowerCase();
  4958. var blobURL;
  4959. try {
  4960. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4961. }
  4962. catch (ex) {
  4963. // Chrome doesn't support oneTimeOnly parameter
  4964. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4965. }
  4966. img.src = blobURL;
  4967. }
  4968. catch (e) {
  4969. img.src = null;
  4970. }
  4971. }
  4972. }
  4973. return img;
  4974. };
  4975. //ANY
  4976. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4977. url = Tools.CleanUrl(url);
  4978. var noIndexedDB = function () {
  4979. var request = new XMLHttpRequest();
  4980. var loadUrl = Tools.BaseUrl + url;
  4981. request.open('GET', loadUrl, true);
  4982. if (useArrayBuffer) {
  4983. request.responseType = "arraybuffer";
  4984. }
  4985. request.onprogress = progressCallBack;
  4986. request.onreadystatechange = function () {
  4987. if (request.readyState === 4) {
  4988. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4989. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4990. callback(!useArrayBuffer ? request.responseText : request.response);
  4991. }
  4992. else {
  4993. if (onError) {
  4994. onError();
  4995. }
  4996. else {
  4997. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4998. }
  4999. }
  5000. }
  5001. };
  5002. request.send(null);
  5003. };
  5004. var loadFromIndexedDB = function () {
  5005. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5006. };
  5007. if (url.indexOf("file:") !== -1) {
  5008. var fileName = url.substring(5).toLowerCase();
  5009. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5010. }
  5011. else {
  5012. // Caching all files
  5013. if (database && database.enableSceneOffline) {
  5014. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5015. }
  5016. else {
  5017. noIndexedDB();
  5018. }
  5019. }
  5020. };
  5021. /**
  5022. * Load a script (identified by an url). When the url returns, the
  5023. * content of this file is added into a new script element, attached to the DOM (body element)
  5024. */
  5025. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5026. var head = document.getElementsByTagName('head')[0];
  5027. var script = document.createElement('script');
  5028. script.type = 'text/javascript';
  5029. script.src = scriptUrl;
  5030. var self = this;
  5031. script.onload = function () {
  5032. if (onSuccess) {
  5033. onSuccess();
  5034. }
  5035. };
  5036. script.onerror = function () {
  5037. if (onError) {
  5038. onError();
  5039. }
  5040. };
  5041. head.appendChild(script);
  5042. };
  5043. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5044. var reader = new FileReader();
  5045. reader.onload = function (e) {
  5046. //target doesn't have result from ts 1.3
  5047. callback(e.target['result']);
  5048. };
  5049. reader.onprogress = progressCallback;
  5050. reader.readAsDataURL(fileToLoad);
  5051. };
  5052. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5053. var reader = new FileReader();
  5054. reader.onerror = function (e) {
  5055. Tools.Log("Error while reading file: " + fileToLoad.name);
  5056. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5057. };
  5058. reader.onload = function (e) {
  5059. //target doesn't have result from ts 1.3
  5060. callback(e.target['result']);
  5061. };
  5062. reader.onprogress = progressCallBack;
  5063. if (!useArrayBuffer) {
  5064. // Asynchronous read
  5065. reader.readAsText(fileToLoad);
  5066. }
  5067. else {
  5068. reader.readAsArrayBuffer(fileToLoad);
  5069. }
  5070. };
  5071. //returns a downloadable url to a file content.
  5072. Tools.FileAsURL = function (content) {
  5073. var fileBlob = new Blob([content]);
  5074. var url = window.URL || window.webkitURL;
  5075. var link = url.createObjectURL(fileBlob);
  5076. return link;
  5077. };
  5078. // Misc.
  5079. Tools.Format = function (value, decimals) {
  5080. if (decimals === void 0) { decimals = 2; }
  5081. return value.toFixed(decimals);
  5082. };
  5083. Tools.CheckExtends = function (v, min, max) {
  5084. if (v.x < min.x)
  5085. min.x = v.x;
  5086. if (v.y < min.y)
  5087. min.y = v.y;
  5088. if (v.z < min.z)
  5089. min.z = v.z;
  5090. if (v.x > max.x)
  5091. max.x = v.x;
  5092. if (v.y > max.y)
  5093. max.y = v.y;
  5094. if (v.z > max.z)
  5095. max.z = v.z;
  5096. };
  5097. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5098. for (var prop in source) {
  5099. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5100. continue;
  5101. }
  5102. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5103. continue;
  5104. }
  5105. var sourceValue = source[prop];
  5106. var typeOfSourceValue = typeof sourceValue;
  5107. if (typeOfSourceValue === "function") {
  5108. continue;
  5109. }
  5110. if (typeOfSourceValue === "object") {
  5111. if (sourceValue instanceof Array) {
  5112. destination[prop] = [];
  5113. if (sourceValue.length > 0) {
  5114. if (typeof sourceValue[0] == "object") {
  5115. for (var index = 0; index < sourceValue.length; index++) {
  5116. var clonedValue = cloneValue(sourceValue[index], destination);
  5117. if (destination[prop].indexOf(clonedValue) === -1) {
  5118. destination[prop].push(clonedValue);
  5119. }
  5120. }
  5121. }
  5122. else {
  5123. destination[prop] = sourceValue.slice(0);
  5124. }
  5125. }
  5126. }
  5127. else {
  5128. destination[prop] = cloneValue(sourceValue, destination);
  5129. }
  5130. }
  5131. else {
  5132. destination[prop] = sourceValue;
  5133. }
  5134. }
  5135. };
  5136. Tools.IsEmpty = function (obj) {
  5137. for (var i in obj) {
  5138. return false;
  5139. }
  5140. return true;
  5141. };
  5142. Tools.RegisterTopRootEvents = function (events) {
  5143. for (var index = 0; index < events.length; index++) {
  5144. var event = events[index];
  5145. window.addEventListener(event.name, event.handler, false);
  5146. try {
  5147. if (window.parent) {
  5148. window.parent.addEventListener(event.name, event.handler, false);
  5149. }
  5150. }
  5151. catch (e) {
  5152. }
  5153. }
  5154. };
  5155. Tools.UnregisterTopRootEvents = function (events) {
  5156. for (var index = 0; index < events.length; index++) {
  5157. var event = events[index];
  5158. window.removeEventListener(event.name, event.handler);
  5159. try {
  5160. if (window.parent) {
  5161. window.parent.removeEventListener(event.name, event.handler);
  5162. }
  5163. }
  5164. catch (e) {
  5165. }
  5166. }
  5167. };
  5168. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5169. if (mimeType === void 0) { mimeType = "image/png"; }
  5170. // Read the contents of the framebuffer
  5171. var numberOfChannelsByLine = width * 4;
  5172. var halfHeight = height / 2;
  5173. //Reading datas from WebGL
  5174. var data = engine.readPixels(0, 0, width, height);
  5175. //To flip image on Y axis.
  5176. for (var i = 0; i < halfHeight; i++) {
  5177. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5178. var currentCell = j + i * numberOfChannelsByLine;
  5179. var targetLine = height - i - 1;
  5180. var targetCell = j + targetLine * numberOfChannelsByLine;
  5181. var temp = data[currentCell];
  5182. data[currentCell] = data[targetCell];
  5183. data[targetCell] = temp;
  5184. }
  5185. }
  5186. // Create a 2D canvas to store the result
  5187. if (!screenshotCanvas) {
  5188. screenshotCanvas = document.createElement('canvas');
  5189. }
  5190. screenshotCanvas.width = width;
  5191. screenshotCanvas.height = height;
  5192. var context = screenshotCanvas.getContext('2d');
  5193. // Copy the pixels to a 2D canvas
  5194. var imageData = context.createImageData(width, height);
  5195. var castData = (imageData.data);
  5196. castData.set(data);
  5197. context.putImageData(imageData, 0, 0);
  5198. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5199. };
  5200. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5201. if (mimeType === void 0) { mimeType = "image/png"; }
  5202. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5203. if (successCallback) {
  5204. successCallback(base64Image);
  5205. }
  5206. else {
  5207. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5208. if (("download" in document.createElement("a"))) {
  5209. var a = window.document.createElement("a");
  5210. a.href = base64Image;
  5211. var date = new Date();
  5212. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5213. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5214. window.document.body.appendChild(a);
  5215. a.addEventListener("click", function () {
  5216. a.parentElement.removeChild(a);
  5217. });
  5218. a.click();
  5219. }
  5220. else {
  5221. var newWindow = window.open("");
  5222. var img = newWindow.document.createElement("img");
  5223. img.src = base64Image;
  5224. newWindow.document.body.appendChild(img);
  5225. }
  5226. }
  5227. };
  5228. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5229. if (mimeType === void 0) { mimeType = "image/png"; }
  5230. var width;
  5231. var height;
  5232. // If a precision value is specified
  5233. if (size.precision) {
  5234. width = Math.round(engine.getRenderWidth() * size.precision);
  5235. height = Math.round(width / engine.getAspectRatio(camera));
  5236. }
  5237. else if (size.width && size.height) {
  5238. width = size.width;
  5239. height = size.height;
  5240. }
  5241. else if (size.width && !size.height) {
  5242. width = size.width;
  5243. height = Math.round(width / engine.getAspectRatio(camera));
  5244. }
  5245. else if (size.height && !size.width) {
  5246. height = size.height;
  5247. width = Math.round(height * engine.getAspectRatio(camera));
  5248. }
  5249. else if (!isNaN(size)) {
  5250. height = size;
  5251. width = size;
  5252. }
  5253. else {
  5254. Tools.Error("Invalid 'size' parameter !");
  5255. return;
  5256. }
  5257. if (!screenshotCanvas) {
  5258. screenshotCanvas = document.createElement('canvas');
  5259. }
  5260. screenshotCanvas.width = width;
  5261. screenshotCanvas.height = height;
  5262. var renderContext = screenshotCanvas.getContext("2d");
  5263. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5264. var newWidth = width;
  5265. var newHeight = newWidth / ratio;
  5266. if (newHeight > height) {
  5267. newHeight = height;
  5268. newWidth = newHeight * ratio;
  5269. }
  5270. var offsetX = Math.max(0, width - newWidth) / 2;
  5271. var offsetY = Math.max(0, height - newHeight) / 2;
  5272. renderContext.fillStyle = camera.getScene().clearColor.toHexString();
  5273. renderContext.fillRect(0, 0, width, height);
  5274. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5275. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5276. };
  5277. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5278. if (mimeType === void 0) { mimeType = "image/png"; }
  5279. var width;
  5280. var height;
  5281. //If a precision value is specified
  5282. if (size.precision) {
  5283. width = Math.round(engine.getRenderWidth() * size.precision);
  5284. height = Math.round(width / engine.getAspectRatio(camera));
  5285. size = { width: width, height: height };
  5286. }
  5287. else if (size.width && size.height) {
  5288. width = size.width;
  5289. height = size.height;
  5290. }
  5291. else if (size.width && !size.height) {
  5292. width = size.width;
  5293. height = Math.round(width / engine.getAspectRatio(camera));
  5294. size = { width: width, height: height };
  5295. }
  5296. else if (size.height && !size.width) {
  5297. height = size.height;
  5298. width = Math.round(height * engine.getAspectRatio(camera));
  5299. size = { width: width, height: height };
  5300. }
  5301. else if (!isNaN(size)) {
  5302. height = size;
  5303. width = size;
  5304. }
  5305. else {
  5306. Tools.Error("Invalid 'size' parameter !");
  5307. return;
  5308. }
  5309. var scene = camera.getScene();
  5310. var previousCamera = null;
  5311. if (scene.activeCamera !== camera) {
  5312. previousCamera = scene.activeCamera;
  5313. scene.activeCamera = camera;
  5314. }
  5315. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5316. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5317. texture.renderList = scene.meshes;
  5318. texture.onAfterRenderObservable.add(function () {
  5319. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5320. });
  5321. scene.incrementRenderId();
  5322. scene.resetCachedMaterial();
  5323. texture.render(true);
  5324. texture.dispose();
  5325. if (previousCamera) {
  5326. scene.activeCamera = previousCamera;
  5327. }
  5328. camera.getProjectionMatrix(true); // Force cache refresh;
  5329. };
  5330. // XHR response validator for local file scenario
  5331. Tools.ValidateXHRData = function (xhr, dataType) {
  5332. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5333. if (dataType === void 0) { dataType = 7; }
  5334. try {
  5335. if (dataType & 1) {
  5336. if (xhr.responseText && xhr.responseText.length > 0) {
  5337. return true;
  5338. }
  5339. else if (dataType === 1) {
  5340. return false;
  5341. }
  5342. }
  5343. if (dataType & 2) {
  5344. // Check header width and height since there is no "TGA" magic number
  5345. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5346. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5347. return true;
  5348. }
  5349. else if (dataType === 2) {
  5350. return false;
  5351. }
  5352. }
  5353. if (dataType & 4) {
  5354. // Check for the "DDS" magic number
  5355. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5356. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5357. return true;
  5358. }
  5359. else {
  5360. return false;
  5361. }
  5362. }
  5363. }
  5364. catch (e) {
  5365. }
  5366. return false;
  5367. };
  5368. /**
  5369. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5370. * Be aware Math.random() could cause collisions, but:
  5371. * "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"
  5372. */
  5373. Tools.RandomId = function () {
  5374. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5375. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5376. return v.toString(16);
  5377. });
  5378. };
  5379. Object.defineProperty(Tools, "NoneLogLevel", {
  5380. get: function () {
  5381. return Tools._NoneLogLevel;
  5382. },
  5383. enumerable: true,
  5384. configurable: true
  5385. });
  5386. Object.defineProperty(Tools, "MessageLogLevel", {
  5387. get: function () {
  5388. return Tools._MessageLogLevel;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(Tools, "WarningLogLevel", {
  5394. get: function () {
  5395. return Tools._WarningLogLevel;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Object.defineProperty(Tools, "ErrorLogLevel", {
  5401. get: function () {
  5402. return Tools._ErrorLogLevel;
  5403. },
  5404. enumerable: true,
  5405. configurable: true
  5406. });
  5407. Object.defineProperty(Tools, "AllLogLevel", {
  5408. get: function () {
  5409. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5410. },
  5411. enumerable: true,
  5412. configurable: true
  5413. });
  5414. Tools._AddLogEntry = function (entry) {
  5415. Tools._LogCache = entry + Tools._LogCache;
  5416. if (Tools.OnNewCacheEntry) {
  5417. Tools.OnNewCacheEntry(entry);
  5418. }
  5419. };
  5420. Tools._FormatMessage = function (message) {
  5421. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5422. var date = new Date();
  5423. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5424. };
  5425. Tools._LogDisabled = function (message) {
  5426. // nothing to do
  5427. };
  5428. Tools._LogEnabled = function (message) {
  5429. var formattedMessage = Tools._FormatMessage(message);
  5430. console.log("BJS - " + formattedMessage);
  5431. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5432. Tools._AddLogEntry(entry);
  5433. };
  5434. Tools._WarnDisabled = function (message) {
  5435. // nothing to do
  5436. };
  5437. Tools._WarnEnabled = function (message) {
  5438. var formattedMessage = Tools._FormatMessage(message);
  5439. console.warn("BJS - " + formattedMessage);
  5440. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5441. Tools._AddLogEntry(entry);
  5442. };
  5443. Tools._ErrorDisabled = function (message) {
  5444. // nothing to do
  5445. };
  5446. Tools._ErrorEnabled = function (message) {
  5447. Tools.errorsCount++;
  5448. var formattedMessage = Tools._FormatMessage(message);
  5449. console.error("BJS - " + formattedMessage);
  5450. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5451. Tools._AddLogEntry(entry);
  5452. };
  5453. Object.defineProperty(Tools, "LogCache", {
  5454. get: function () {
  5455. return Tools._LogCache;
  5456. },
  5457. enumerable: true,
  5458. configurable: true
  5459. });
  5460. Tools.ClearLogCache = function () {
  5461. Tools._LogCache = "";
  5462. Tools.errorsCount = 0;
  5463. };
  5464. Object.defineProperty(Tools, "LogLevels", {
  5465. set: function (level) {
  5466. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5467. Tools.Log = Tools._LogEnabled;
  5468. }
  5469. else {
  5470. Tools.Log = Tools._LogDisabled;
  5471. }
  5472. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5473. Tools.Warn = Tools._WarnEnabled;
  5474. }
  5475. else {
  5476. Tools.Warn = Tools._WarnDisabled;
  5477. }
  5478. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5479. Tools.Error = Tools._ErrorEnabled;
  5480. }
  5481. else {
  5482. Tools.Error = Tools._ErrorDisabled;
  5483. }
  5484. },
  5485. enumerable: true,
  5486. configurable: true
  5487. });
  5488. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5489. get: function () {
  5490. return Tools._PerformanceNoneLogLevel;
  5491. },
  5492. enumerable: true,
  5493. configurable: true
  5494. });
  5495. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5496. get: function () {
  5497. return Tools._PerformanceUserMarkLogLevel;
  5498. },
  5499. enumerable: true,
  5500. configurable: true
  5501. });
  5502. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5503. get: function () {
  5504. return Tools._PerformanceConsoleLogLevel;
  5505. },
  5506. enumerable: true,
  5507. configurable: true
  5508. });
  5509. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5510. set: function (level) {
  5511. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5512. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5513. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5514. return;
  5515. }
  5516. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5517. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5518. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5519. return;
  5520. }
  5521. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5522. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5523. },
  5524. enumerable: true,
  5525. configurable: true
  5526. });
  5527. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5528. };
  5529. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5530. };
  5531. Tools._StartUserMark = function (counterName, condition) {
  5532. if (condition === void 0) { condition = true; }
  5533. if (!condition || !Tools._performance.mark) {
  5534. return;
  5535. }
  5536. Tools._performance.mark(counterName + "-Begin");
  5537. };
  5538. Tools._EndUserMark = function (counterName, condition) {
  5539. if (condition === void 0) { condition = true; }
  5540. if (!condition || !Tools._performance.mark) {
  5541. return;
  5542. }
  5543. Tools._performance.mark(counterName + "-End");
  5544. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5545. };
  5546. Tools._StartPerformanceConsole = function (counterName, condition) {
  5547. if (condition === void 0) { condition = true; }
  5548. if (!condition) {
  5549. return;
  5550. }
  5551. Tools._StartUserMark(counterName, condition);
  5552. if (console.time) {
  5553. console.time(counterName);
  5554. }
  5555. };
  5556. Tools._EndPerformanceConsole = function (counterName, condition) {
  5557. if (condition === void 0) { condition = true; }
  5558. if (!condition) {
  5559. return;
  5560. }
  5561. Tools._EndUserMark(counterName, condition);
  5562. if (console.time) {
  5563. console.timeEnd(counterName);
  5564. }
  5565. };
  5566. Object.defineProperty(Tools, "Now", {
  5567. get: function () {
  5568. if (window.performance && window.performance.now) {
  5569. return window.performance.now();
  5570. }
  5571. return new Date().getTime();
  5572. },
  5573. enumerable: true,
  5574. configurable: true
  5575. });
  5576. /**
  5577. * This method will return the name of the class used to create the instance of the given object.
  5578. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5579. * @param object the object to get the class name from
  5580. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5581. */
  5582. Tools.getClassName = function (object, isType) {
  5583. if (isType === void 0) { isType = false; }
  5584. var name = null;
  5585. if (!isType && object.getClassName) {
  5586. name = object.getClassName();
  5587. }
  5588. else {
  5589. if (object instanceof Object) {
  5590. var classObj = isType ? object : Object.getPrototypeOf(object);
  5591. name = classObj.constructor["__bjsclassName__"];
  5592. }
  5593. if (!name) {
  5594. name = typeof object;
  5595. }
  5596. }
  5597. return name;
  5598. };
  5599. Tools.first = function (array, predicate) {
  5600. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5601. var el = array_1[_i];
  5602. if (predicate(el)) {
  5603. return el;
  5604. }
  5605. }
  5606. };
  5607. /**
  5608. * This method will return the name of the full name of the class, including its owning module (if any).
  5609. * 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).
  5610. * @param object the object to get the class name from
  5611. * @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.
  5612. */
  5613. Tools.getFullClassName = function (object, isType) {
  5614. if (isType === void 0) { isType = false; }
  5615. var className = null;
  5616. var moduleName = null;
  5617. if (!isType && object.getClassName) {
  5618. className = object.getClassName();
  5619. }
  5620. else {
  5621. if (object instanceof Object) {
  5622. var classObj = isType ? object : Object.getPrototypeOf(object);
  5623. className = classObj.constructor["__bjsclassName__"];
  5624. moduleName = classObj.constructor["__bjsmoduleName__"];
  5625. }
  5626. if (!className) {
  5627. className = typeof object;
  5628. }
  5629. }
  5630. if (!className) {
  5631. return null;
  5632. }
  5633. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5634. };
  5635. /**
  5636. * 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.
  5637. * @param array
  5638. */
  5639. Tools.arrayOrStringFeeder = function (array) {
  5640. return function (index) {
  5641. if (index >= array.length) {
  5642. return null;
  5643. }
  5644. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5645. if (val && val.getHashCode) {
  5646. val = val.getHashCode();
  5647. }
  5648. if (typeof val === "string") {
  5649. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5650. }
  5651. return val;
  5652. };
  5653. };
  5654. /**
  5655. * Compute the hashCode of a stream of number
  5656. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5657. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5658. * @return the hash code computed
  5659. */
  5660. Tools.hashCodeFromStream = function (feeder) {
  5661. // Based from here: http://stackoverflow.com/a/7616484/802124
  5662. var hash = 0;
  5663. var index = 0;
  5664. var chr = feeder(index++);
  5665. while (chr != null) {
  5666. hash = ((hash << 5) - hash) + chr;
  5667. hash |= 0; // Convert to 32bit integer
  5668. chr = feeder(index++);
  5669. }
  5670. return hash;
  5671. };
  5672. return Tools;
  5673. }());
  5674. Tools.BaseUrl = "";
  5675. Tools.CorsBehavior = "anonymous";
  5676. Tools.UseFallbackTexture = true;
  5677. // Logs
  5678. Tools._NoneLogLevel = 0;
  5679. Tools._MessageLogLevel = 1;
  5680. Tools._WarningLogLevel = 2;
  5681. Tools._ErrorLogLevel = 4;
  5682. Tools._LogCache = "";
  5683. Tools.errorsCount = 0;
  5684. Tools.Log = Tools._LogEnabled;
  5685. Tools.Warn = Tools._WarnEnabled;
  5686. Tools.Error = Tools._ErrorEnabled;
  5687. // Performances
  5688. Tools._PerformanceNoneLogLevel = 0;
  5689. Tools._PerformanceUserMarkLogLevel = 1;
  5690. Tools._PerformanceConsoleLogLevel = 2;
  5691. Tools._performance = window.performance;
  5692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5694. BABYLON.Tools = Tools;
  5695. /**
  5696. * This class is used to track a performance counter which is number based.
  5697. * The user has access to many properties which give statistics of different nature
  5698. *
  5699. * The implementer can track two kinds of Performance Counter: time and count
  5700. * 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.
  5701. * 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.
  5702. */
  5703. var PerfCounter = (function () {
  5704. function PerfCounter() {
  5705. this._startMonitoringTime = 0;
  5706. this._min = 0;
  5707. this._max = 0;
  5708. this._average = 0;
  5709. this._lastSecAverage = 0;
  5710. this._current = 0;
  5711. this._totalValueCount = 0;
  5712. this._totalAccumulated = 0;
  5713. this._lastSecAccumulated = 0;
  5714. this._lastSecTime = 0;
  5715. this._lastSecValueCount = 0;
  5716. }
  5717. Object.defineProperty(PerfCounter.prototype, "min", {
  5718. /**
  5719. * Returns the smallest value ever
  5720. */
  5721. get: function () {
  5722. return this._min;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. Object.defineProperty(PerfCounter.prototype, "max", {
  5728. /**
  5729. * Returns the biggest value ever
  5730. */
  5731. get: function () {
  5732. return this._max;
  5733. },
  5734. enumerable: true,
  5735. configurable: true
  5736. });
  5737. Object.defineProperty(PerfCounter.prototype, "average", {
  5738. /**
  5739. * Returns the average value since the performance counter is running
  5740. */
  5741. get: function () {
  5742. return this._average;
  5743. },
  5744. enumerable: true,
  5745. configurable: true
  5746. });
  5747. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5748. /**
  5749. * Returns the average value of the last second the counter was monitored
  5750. */
  5751. get: function () {
  5752. return this._lastSecAverage;
  5753. },
  5754. enumerable: true,
  5755. configurable: true
  5756. });
  5757. Object.defineProperty(PerfCounter.prototype, "current", {
  5758. /**
  5759. * Returns the current value
  5760. */
  5761. get: function () {
  5762. return this._current;
  5763. },
  5764. enumerable: true,
  5765. configurable: true
  5766. });
  5767. Object.defineProperty(PerfCounter.prototype, "total", {
  5768. get: function () {
  5769. return this._totalAccumulated;
  5770. },
  5771. enumerable: true,
  5772. configurable: true
  5773. });
  5774. /**
  5775. * Call this method to start monitoring a new frame.
  5776. * 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.
  5777. */
  5778. PerfCounter.prototype.fetchNewFrame = function () {
  5779. this._totalValueCount++;
  5780. this._current = 0;
  5781. this._lastSecValueCount++;
  5782. };
  5783. /**
  5784. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5785. * @param newCount the count value to add to the monitored count
  5786. * @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.
  5787. */
  5788. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5789. this._current += newCount;
  5790. if (fetchResult) {
  5791. this._fetchResult();
  5792. }
  5793. };
  5794. /**
  5795. * Start monitoring this performance counter
  5796. */
  5797. PerfCounter.prototype.beginMonitoring = function () {
  5798. this._startMonitoringTime = Tools.Now;
  5799. };
  5800. /**
  5801. * Compute the time lapsed since the previous beginMonitoring() call.
  5802. * @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
  5803. */
  5804. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5805. if (newFrame === void 0) { newFrame = true; }
  5806. if (newFrame) {
  5807. this.fetchNewFrame();
  5808. }
  5809. var currentTime = Tools.Now;
  5810. this._current = currentTime - this._startMonitoringTime;
  5811. if (newFrame) {
  5812. this._fetchResult();
  5813. }
  5814. };
  5815. PerfCounter.prototype._fetchResult = function () {
  5816. this._totalAccumulated += this._current;
  5817. this._lastSecAccumulated += this._current;
  5818. // Min/Max update
  5819. this._min = Math.min(this._min, this._current);
  5820. this._max = Math.max(this._max, this._current);
  5821. this._average = this._totalAccumulated / this._totalValueCount;
  5822. // Reset last sec?
  5823. var now = Tools.Now;
  5824. if ((now - this._lastSecTime) > 1000) {
  5825. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5826. this._lastSecTime = now;
  5827. this._lastSecAccumulated = 0;
  5828. this._lastSecValueCount = 0;
  5829. }
  5830. };
  5831. return PerfCounter;
  5832. }());
  5833. BABYLON.PerfCounter = PerfCounter;
  5834. /**
  5835. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5836. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5837. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5838. * @param name The name of the class, case should be preserved
  5839. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5840. */
  5841. function className(name, module) {
  5842. return function (target) {
  5843. target["__bjsclassName__"] = name;
  5844. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5845. };
  5846. }
  5847. BABYLON.className = className;
  5848. /**
  5849. * An implementation of a loop for asynchronous functions.
  5850. */
  5851. var AsyncLoop = (function () {
  5852. /**
  5853. * Constroctor.
  5854. * @param iterations the number of iterations.
  5855. * @param _fn the function to run each iteration
  5856. * @param _successCallback the callback that will be called upon succesful execution
  5857. * @param offset starting offset.
  5858. */
  5859. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5860. if (offset === void 0) { offset = 0; }
  5861. this.iterations = iterations;
  5862. this._fn = _fn;
  5863. this._successCallback = _successCallback;
  5864. this.index = offset - 1;
  5865. this._done = false;
  5866. }
  5867. /**
  5868. * Execute the next iteration. Must be called after the last iteration was finished.
  5869. */
  5870. AsyncLoop.prototype.executeNext = function () {
  5871. if (!this._done) {
  5872. if (this.index + 1 < this.iterations) {
  5873. ++this.index;
  5874. this._fn(this);
  5875. }
  5876. else {
  5877. this.breakLoop();
  5878. }
  5879. }
  5880. };
  5881. /**
  5882. * Break the loop and run the success callback.
  5883. */
  5884. AsyncLoop.prototype.breakLoop = function () {
  5885. this._done = true;
  5886. this._successCallback();
  5887. };
  5888. /**
  5889. * Helper function
  5890. */
  5891. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5892. if (offset === void 0) { offset = 0; }
  5893. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5894. loop.executeNext();
  5895. return loop;
  5896. };
  5897. /**
  5898. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5899. * @param iterations total number of iterations
  5900. * @param syncedIterations number of synchronous iterations in each async iteration.
  5901. * @param fn the function to call each iteration.
  5902. * @param callback a success call back that will be called when iterating stops.
  5903. * @param breakFunction a break condition (optional)
  5904. * @param timeout timeout settings for the setTimeout function. default - 0.
  5905. * @constructor
  5906. */
  5907. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5908. if (timeout === void 0) { timeout = 0; }
  5909. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5910. if (breakFunction && breakFunction())
  5911. loop.breakLoop();
  5912. else {
  5913. setTimeout(function () {
  5914. for (var i = 0; i < syncedIterations; ++i) {
  5915. var iteration = (loop.index * syncedIterations) + i;
  5916. if (iteration >= iterations)
  5917. break;
  5918. fn(iteration);
  5919. if (breakFunction && breakFunction()) {
  5920. loop.breakLoop();
  5921. break;
  5922. }
  5923. }
  5924. loop.executeNext();
  5925. }, timeout);
  5926. }
  5927. }, callback);
  5928. };
  5929. return AsyncLoop;
  5930. }());
  5931. BABYLON.AsyncLoop = AsyncLoop;
  5932. })(BABYLON || (BABYLON = {}));
  5933. //# sourceMappingURL=babylon.tools.js.map
  5934. var BABYLON;
  5935. (function (BABYLON) {
  5936. var Internals;
  5937. (function (Internals) {
  5938. var _AlphaState = (function () {
  5939. /**
  5940. * Initializes the state.
  5941. */
  5942. function _AlphaState() {
  5943. this._isAlphaBlendDirty = false;
  5944. this._isBlendFunctionParametersDirty = false;
  5945. this._alphaBlend = false;
  5946. this._blendFunctionParameters = new Array(4);
  5947. this.reset();
  5948. }
  5949. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5950. get: function () {
  5951. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5952. },
  5953. enumerable: true,
  5954. configurable: true
  5955. });
  5956. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5957. get: function () {
  5958. return this._alphaBlend;
  5959. },
  5960. set: function (value) {
  5961. if (this._alphaBlend === value) {
  5962. return;
  5963. }
  5964. this._alphaBlend = value;
  5965. this._isAlphaBlendDirty = true;
  5966. },
  5967. enumerable: true,
  5968. configurable: true
  5969. });
  5970. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5971. if (this._blendFunctionParameters[0] === value0 &&
  5972. this._blendFunctionParameters[1] === value1 &&
  5973. this._blendFunctionParameters[2] === value2 &&
  5974. this._blendFunctionParameters[3] === value3) {
  5975. return;
  5976. }
  5977. this._blendFunctionParameters[0] = value0;
  5978. this._blendFunctionParameters[1] = value1;
  5979. this._blendFunctionParameters[2] = value2;
  5980. this._blendFunctionParameters[3] = value3;
  5981. this._isBlendFunctionParametersDirty = true;
  5982. };
  5983. _AlphaState.prototype.reset = function () {
  5984. this._alphaBlend = false;
  5985. this._blendFunctionParameters[0] = null;
  5986. this._blendFunctionParameters[1] = null;
  5987. this._blendFunctionParameters[2] = null;
  5988. this._blendFunctionParameters[3] = null;
  5989. this._isAlphaBlendDirty = true;
  5990. this._isBlendFunctionParametersDirty = false;
  5991. };
  5992. _AlphaState.prototype.apply = function (gl) {
  5993. if (!this.isDirty) {
  5994. return;
  5995. }
  5996. // Alpha blend
  5997. if (this._isAlphaBlendDirty) {
  5998. if (this._alphaBlend) {
  5999. gl.enable(gl.BLEND);
  6000. }
  6001. else {
  6002. gl.disable(gl.BLEND);
  6003. }
  6004. this._isAlphaBlendDirty = false;
  6005. }
  6006. // Alpha function
  6007. if (this._isBlendFunctionParametersDirty) {
  6008. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6009. this._isBlendFunctionParametersDirty = false;
  6010. }
  6011. };
  6012. return _AlphaState;
  6013. }());
  6014. Internals._AlphaState = _AlphaState;
  6015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6016. })(BABYLON || (BABYLON = {}));
  6017. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6018. var BABYLON;
  6019. (function (BABYLON) {
  6020. var Internals;
  6021. (function (Internals) {
  6022. var _DepthCullingState = (function () {
  6023. /**
  6024. * Initializes the state.
  6025. */
  6026. function _DepthCullingState() {
  6027. this._isDepthTestDirty = false;
  6028. this._isDepthMaskDirty = false;
  6029. this._isDepthFuncDirty = false;
  6030. this._isCullFaceDirty = false;
  6031. this._isCullDirty = false;
  6032. this._isZOffsetDirty = false;
  6033. this.reset();
  6034. }
  6035. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6036. get: function () {
  6037. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6038. },
  6039. enumerable: true,
  6040. configurable: true
  6041. });
  6042. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6043. get: function () {
  6044. return this._zOffset;
  6045. },
  6046. set: function (value) {
  6047. if (this._zOffset === value) {
  6048. return;
  6049. }
  6050. this._zOffset = value;
  6051. this._isZOffsetDirty = true;
  6052. },
  6053. enumerable: true,
  6054. configurable: true
  6055. });
  6056. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6057. get: function () {
  6058. return this._cullFace;
  6059. },
  6060. set: function (value) {
  6061. if (this._cullFace === value) {
  6062. return;
  6063. }
  6064. this._cullFace = value;
  6065. this._isCullFaceDirty = true;
  6066. },
  6067. enumerable: true,
  6068. configurable: true
  6069. });
  6070. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6071. get: function () {
  6072. return this._cull;
  6073. },
  6074. set: function (value) {
  6075. if (this._cull === value) {
  6076. return;
  6077. }
  6078. this._cull = value;
  6079. this._isCullDirty = true;
  6080. },
  6081. enumerable: true,
  6082. configurable: true
  6083. });
  6084. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6085. get: function () {
  6086. return this._depthFunc;
  6087. },
  6088. set: function (value) {
  6089. if (this._depthFunc === value) {
  6090. return;
  6091. }
  6092. this._depthFunc = value;
  6093. this._isDepthFuncDirty = true;
  6094. },
  6095. enumerable: true,
  6096. configurable: true
  6097. });
  6098. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6099. get: function () {
  6100. return this._depthMask;
  6101. },
  6102. set: function (value) {
  6103. if (this._depthMask === value) {
  6104. return;
  6105. }
  6106. this._depthMask = value;
  6107. this._isDepthMaskDirty = true;
  6108. },
  6109. enumerable: true,
  6110. configurable: true
  6111. });
  6112. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6113. get: function () {
  6114. return this._depthTest;
  6115. },
  6116. set: function (value) {
  6117. if (this._depthTest === value) {
  6118. return;
  6119. }
  6120. this._depthTest = value;
  6121. this._isDepthTestDirty = true;
  6122. },
  6123. enumerable: true,
  6124. configurable: true
  6125. });
  6126. _DepthCullingState.prototype.reset = function () {
  6127. this._depthMask = true;
  6128. this._depthTest = true;
  6129. this._depthFunc = null;
  6130. this._cullFace = null;
  6131. this._cull = null;
  6132. this._zOffset = 0;
  6133. this._isDepthTestDirty = true;
  6134. this._isDepthMaskDirty = true;
  6135. this._isDepthFuncDirty = false;
  6136. this._isCullFaceDirty = false;
  6137. this._isCullDirty = false;
  6138. this._isZOffsetDirty = false;
  6139. };
  6140. _DepthCullingState.prototype.apply = function (gl) {
  6141. if (!this.isDirty) {
  6142. return;
  6143. }
  6144. // Cull
  6145. if (this._isCullDirty) {
  6146. if (this.cull) {
  6147. gl.enable(gl.CULL_FACE);
  6148. }
  6149. else {
  6150. gl.disable(gl.CULL_FACE);
  6151. }
  6152. this._isCullDirty = false;
  6153. }
  6154. // Cull face
  6155. if (this._isCullFaceDirty) {
  6156. gl.cullFace(this.cullFace);
  6157. this._isCullFaceDirty = false;
  6158. }
  6159. // Depth mask
  6160. if (this._isDepthMaskDirty) {
  6161. gl.depthMask(this.depthMask);
  6162. this._isDepthMaskDirty = false;
  6163. }
  6164. // Depth test
  6165. if (this._isDepthTestDirty) {
  6166. if (this.depthTest) {
  6167. gl.enable(gl.DEPTH_TEST);
  6168. }
  6169. else {
  6170. gl.disable(gl.DEPTH_TEST);
  6171. }
  6172. this._isDepthTestDirty = false;
  6173. }
  6174. // Depth func
  6175. if (this._isDepthFuncDirty) {
  6176. gl.depthFunc(this.depthFunc);
  6177. this._isDepthFuncDirty = false;
  6178. }
  6179. // zOffset
  6180. if (this._isZOffsetDirty) {
  6181. if (this.zOffset) {
  6182. gl.enable(gl.POLYGON_OFFSET_FILL);
  6183. gl.polygonOffset(this.zOffset, 0);
  6184. }
  6185. else {
  6186. gl.disable(gl.POLYGON_OFFSET_FILL);
  6187. }
  6188. this._isZOffsetDirty = false;
  6189. }
  6190. };
  6191. return _DepthCullingState;
  6192. }());
  6193. Internals._DepthCullingState = _DepthCullingState;
  6194. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6195. })(BABYLON || (BABYLON = {}));
  6196. //# sourceMappingURL=babylon.depthCullingState.js.map
  6197. var BABYLON;
  6198. (function (BABYLON) {
  6199. var Internals;
  6200. (function (Internals) {
  6201. var _StencilState = (function () {
  6202. function _StencilState() {
  6203. this._isStencilTestDirty = false;
  6204. this._isStencilMaskDirty = false;
  6205. this._isStencilFuncDirty = false;
  6206. this._isStencilOpDirty = false;
  6207. this.reset();
  6208. }
  6209. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6210. get: function () {
  6211. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6217. get: function () {
  6218. return this._stencilFunc;
  6219. },
  6220. set: function (value) {
  6221. if (this._stencilFunc === value) {
  6222. return;
  6223. }
  6224. this._stencilFunc = value;
  6225. this._isStencilFuncDirty = true;
  6226. },
  6227. enumerable: true,
  6228. configurable: true
  6229. });
  6230. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6231. get: function () {
  6232. return this._stencilFuncRef;
  6233. },
  6234. set: function (value) {
  6235. if (this._stencilFuncRef === value) {
  6236. return;
  6237. }
  6238. this._stencilFuncRef = value;
  6239. this._isStencilFuncDirty = true;
  6240. },
  6241. enumerable: true,
  6242. configurable: true
  6243. });
  6244. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6245. get: function () {
  6246. return this._stencilFuncMask;
  6247. },
  6248. set: function (value) {
  6249. if (this._stencilFuncMask === value) {
  6250. return;
  6251. }
  6252. this._stencilFuncMask = value;
  6253. this._isStencilFuncDirty = true;
  6254. },
  6255. enumerable: true,
  6256. configurable: true
  6257. });
  6258. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6259. get: function () {
  6260. return this._stencilOpStencilFail;
  6261. },
  6262. set: function (value) {
  6263. if (this._stencilOpStencilFail === value) {
  6264. return;
  6265. }
  6266. this._stencilOpStencilFail = value;
  6267. this._isStencilOpDirty = true;
  6268. },
  6269. enumerable: true,
  6270. configurable: true
  6271. });
  6272. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6273. get: function () {
  6274. return this._stencilOpDepthFail;
  6275. },
  6276. set: function (value) {
  6277. if (this._stencilOpDepthFail === value) {
  6278. return;
  6279. }
  6280. this._stencilOpDepthFail = value;
  6281. this._isStencilOpDirty = true;
  6282. },
  6283. enumerable: true,
  6284. configurable: true
  6285. });
  6286. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6287. get: function () {
  6288. return this._stencilOpStencilDepthPass;
  6289. },
  6290. set: function (value) {
  6291. if (this._stencilOpStencilDepthPass === value) {
  6292. return;
  6293. }
  6294. this._stencilOpStencilDepthPass = value;
  6295. this._isStencilOpDirty = true;
  6296. },
  6297. enumerable: true,
  6298. configurable: true
  6299. });
  6300. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6301. get: function () {
  6302. return this._stencilMask;
  6303. },
  6304. set: function (value) {
  6305. if (this._stencilMask === value) {
  6306. return;
  6307. }
  6308. this._stencilMask = value;
  6309. this._isStencilMaskDirty = true;
  6310. },
  6311. enumerable: true,
  6312. configurable: true
  6313. });
  6314. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6315. get: function () {
  6316. return this._stencilTest;
  6317. },
  6318. set: function (value) {
  6319. if (this._stencilTest === value) {
  6320. return;
  6321. }
  6322. this._stencilTest = value;
  6323. this._isStencilTestDirty = true;
  6324. },
  6325. enumerable: true,
  6326. configurable: true
  6327. });
  6328. _StencilState.prototype.reset = function () {
  6329. this._stencilTest = false;
  6330. this._stencilMask = 0xFF;
  6331. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6332. this._stencilFuncRef = 1;
  6333. this._stencilFuncMask = 0xFF;
  6334. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6335. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6336. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6337. this._isStencilTestDirty = true;
  6338. this._isStencilMaskDirty = true;
  6339. this._isStencilFuncDirty = true;
  6340. this._isStencilOpDirty = true;
  6341. };
  6342. _StencilState.prototype.apply = function (gl) {
  6343. if (!this.isDirty) {
  6344. return;
  6345. }
  6346. // Stencil test
  6347. if (this._isStencilTestDirty) {
  6348. if (this.stencilTest) {
  6349. gl.enable(gl.STENCIL_TEST);
  6350. }
  6351. else {
  6352. gl.disable(gl.STENCIL_TEST);
  6353. }
  6354. this._isStencilTestDirty = false;
  6355. }
  6356. // Stencil mask
  6357. if (this._isStencilMaskDirty) {
  6358. gl.stencilMask(this.stencilMask);
  6359. this._isStencilMaskDirty = false;
  6360. }
  6361. // Stencil func
  6362. if (this._isStencilFuncDirty) {
  6363. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6364. this._isStencilFuncDirty = false;
  6365. }
  6366. // Stencil op
  6367. if (this._isStencilOpDirty) {
  6368. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6369. this._isStencilOpDirty = false;
  6370. }
  6371. };
  6372. return _StencilState;
  6373. }());
  6374. Internals._StencilState = _StencilState;
  6375. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6376. })(BABYLON || (BABYLON = {}));
  6377. //# sourceMappingURL=babylon.stencilState.js.map
  6378. var BABYLON;
  6379. (function (BABYLON) {
  6380. var compileShader = function (gl, source, type, defines) {
  6381. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6382. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6383. gl.compileShader(shader);
  6384. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6385. throw new Error(gl.getShaderInfoLog(shader));
  6386. }
  6387. return shader;
  6388. };
  6389. var HALF_FLOAT_OES = 0x8D61;
  6390. var getWebGLTextureType = function (gl, type) {
  6391. if (type === Engine.TEXTURETYPE_FLOAT) {
  6392. return gl.FLOAT;
  6393. }
  6394. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6395. // Add Half Float Constant.
  6396. return HALF_FLOAT_OES;
  6397. }
  6398. return gl.UNSIGNED_BYTE;
  6399. };
  6400. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6401. var magFilter = gl.NEAREST;
  6402. var minFilter = gl.NEAREST;
  6403. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6404. magFilter = gl.LINEAR;
  6405. if (generateMipMaps) {
  6406. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6407. }
  6408. else {
  6409. minFilter = gl.LINEAR;
  6410. }
  6411. }
  6412. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6413. magFilter = gl.LINEAR;
  6414. if (generateMipMaps) {
  6415. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6416. }
  6417. else {
  6418. minFilter = gl.LINEAR;
  6419. }
  6420. }
  6421. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6422. magFilter = gl.NEAREST;
  6423. if (generateMipMaps) {
  6424. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6425. }
  6426. else {
  6427. minFilter = gl.NEAREST;
  6428. }
  6429. }
  6430. return {
  6431. min: minFilter,
  6432. mag: magFilter
  6433. };
  6434. };
  6435. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6437. var engine = scene.getEngine();
  6438. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6439. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6440. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6441. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6442. texture._baseWidth = width;
  6443. texture._baseHeight = height;
  6444. texture._width = potWidth;
  6445. texture._height = potHeight;
  6446. texture.isReady = true;
  6447. processFunction(potWidth, potHeight);
  6448. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6451. if (!noMipmap && !isCompressed) {
  6452. gl.generateMipmap(gl.TEXTURE_2D);
  6453. }
  6454. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6455. engine.resetTextureCache();
  6456. scene._removePendingData(texture);
  6457. texture.onLoadedCallbacks.forEach(function (callback) {
  6458. callback();
  6459. });
  6460. texture.onLoadedCallbacks = [];
  6461. };
  6462. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6463. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6464. var img;
  6465. var onload = function () {
  6466. loadedImages[index] = img;
  6467. loadedImages._internalCount++;
  6468. scene._removePendingData(img);
  6469. if (loadedImages._internalCount === 6) {
  6470. onfinish(loadedImages);
  6471. }
  6472. };
  6473. var onerror = function () {
  6474. scene._removePendingData(img);
  6475. if (onErrorCallBack) {
  6476. onErrorCallBack();
  6477. }
  6478. };
  6479. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6480. scene._addPendingData(img);
  6481. };
  6482. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6483. if (onError === void 0) { onError = null; }
  6484. var loadedImages = [];
  6485. loadedImages._internalCount = 0;
  6486. for (var index = 0; index < 6; index++) {
  6487. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6488. }
  6489. };
  6490. var InstancingAttributeInfo = (function () {
  6491. function InstancingAttributeInfo() {
  6492. }
  6493. return InstancingAttributeInfo;
  6494. }());
  6495. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6496. var EngineCapabilities = (function () {
  6497. function EngineCapabilities() {
  6498. }
  6499. return EngineCapabilities;
  6500. }());
  6501. BABYLON.EngineCapabilities = EngineCapabilities;
  6502. /**
  6503. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6504. */
  6505. var Engine = (function () {
  6506. /**
  6507. * @constructor
  6508. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6509. * @param {boolean} [antialias] - enable antialias
  6510. * @param options - further options to be sent to the getContext function
  6511. */
  6512. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6513. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6514. var _this = this;
  6515. // Public members
  6516. this.isFullscreen = false;
  6517. this.isPointerLock = false;
  6518. this.cullBackFaces = true;
  6519. this.renderEvenInBackground = true;
  6520. // To enable/disable IDB support and avoid XHR on .manifest
  6521. this.enableOfflineSupport = true;
  6522. this.scenes = new Array();
  6523. this._windowIsBackground = false;
  6524. this._webGLVersion = "1.0";
  6525. this._badOS = false;
  6526. this._drawCalls = new BABYLON.PerfCounter();
  6527. this._renderingQueueLaunched = false;
  6528. this._activeRenderLoops = [];
  6529. // FPS
  6530. this.fpsRange = 60;
  6531. this.previousFramesDuration = [];
  6532. this.fps = 60;
  6533. this.deltaTime = 0;
  6534. // States
  6535. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6536. this._stencilState = new BABYLON.Internals._StencilState();
  6537. this._alphaState = new BABYLON.Internals._AlphaState();
  6538. this._alphaMode = Engine.ALPHA_DISABLE;
  6539. // Cache
  6540. this._loadedTexturesCache = new Array();
  6541. this._maxTextureChannels = 16;
  6542. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6543. this._compiledEffects = {};
  6544. this._vertexAttribArraysEnabled = [];
  6545. this._uintIndicesCurrentlySet = false;
  6546. this._currentBoundBuffer = new Array();
  6547. this._currentBufferPointers = [];
  6548. this._currentInstanceLocations = new Array();
  6549. this._currentInstanceBuffers = new Array();
  6550. // Hardware supported Compressed Textures
  6551. this._texturesSupported = new Array();
  6552. this._onVRFullScreenTriggered = function () {
  6553. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6554. //get the old size before we change
  6555. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6556. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6557. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6558. //But actually, no browser follow the specs...
  6559. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6560. //get the width and height, change the render size
  6561. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6562. var width, height;
  6563. _this.setHardwareScalingLevel(1);
  6564. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6565. }
  6566. else {
  6567. //When the specs are implemented, need to uncomment this.
  6568. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6569. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6570. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6571. _this._vrDisplayEnabled = undefined;
  6572. }
  6573. };
  6574. this._renderingCanvas = canvas;
  6575. this._externalData = new BABYLON.StringDictionary();
  6576. options = options || {};
  6577. if (antialias != null) {
  6578. options.antialias = antialias;
  6579. }
  6580. if (options.preserveDrawingBuffer === undefined) {
  6581. options.preserveDrawingBuffer = false;
  6582. }
  6583. // Checks if some of the format renders first to allow the use of webgl inspector.
  6584. var renderToFullFloat = this._canRenderToFloatTexture();
  6585. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6586. // GL
  6587. //try {
  6588. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6589. // if (this._gl) {
  6590. // this._webGLVersion = "2.0";
  6591. // }
  6592. //} catch (e) {
  6593. // // Do nothing
  6594. //}
  6595. if (!this._gl) {
  6596. if (!canvas) {
  6597. throw new Error("The provided canvas is null or undefined.");
  6598. }
  6599. try {
  6600. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6601. }
  6602. catch (e) {
  6603. throw new Error("WebGL not supported");
  6604. }
  6605. }
  6606. if (!this._gl) {
  6607. throw new Error("WebGL not supported");
  6608. }
  6609. this._onBlur = function () {
  6610. _this._windowIsBackground = true;
  6611. };
  6612. this._onFocus = function () {
  6613. _this._windowIsBackground = false;
  6614. };
  6615. window.addEventListener("blur", this._onBlur);
  6616. window.addEventListener("focus", this._onFocus);
  6617. // Viewport
  6618. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6619. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6620. this.resize();
  6621. // Caps
  6622. this._isStencilEnable = options.stencil;
  6623. this._caps = new EngineCapabilities();
  6624. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6625. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6626. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6627. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6628. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6629. // Infos
  6630. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6631. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6632. if (rendererInfo != null) {
  6633. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6634. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6635. }
  6636. if (!this._glVendor) {
  6637. this._glVendor = "Unknown vendor";
  6638. }
  6639. if (!this._glRenderer) {
  6640. this._glRenderer = "Unknown renderer";
  6641. }
  6642. // Extensions
  6643. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6644. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc');
  6645. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6646. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); // 2nd is what iOS reports
  6647. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1');
  6648. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // first is the final name, found hardware using 2nd
  6649. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6650. 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');
  6651. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6652. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6653. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6654. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6655. this._caps.highPrecisionShaderSupported = true;
  6656. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6657. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6658. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6659. this._caps.textureFloatRender = renderToFullFloat;
  6660. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6661. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6662. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6663. // Intelligently add supported commpressed formats in order to check for.
  6664. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6665. // Next PVR & S3, which are probably superior to ETC1/2.
  6666. // Likely no hardware which supports both PVR & S3, so order matters little.
  6667. // ETC2 is newer and handles ETC1, so check for first.
  6668. if (this._caps.astc)
  6669. this.texturesSupported.push('.astc');
  6670. if (this._caps.s3tc)
  6671. this.texturesSupported.push('.dds');
  6672. if (this._caps.pvrtc)
  6673. this.texturesSupported.push('.pvr');
  6674. if (this._caps.etc2)
  6675. this.texturesSupported.push('.etc2');
  6676. if (this._caps.etc1)
  6677. this.texturesSupported.push('.etc1');
  6678. if (this._gl.getShaderPrecisionFormat) {
  6679. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6680. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6681. }
  6682. // Depth buffer
  6683. this.setDepthBuffer(true);
  6684. this.setDepthFunctionToLessOrEqual();
  6685. this.setDepthWrite(true);
  6686. // Fullscreen
  6687. this._onFullscreenChange = function () {
  6688. if (document.fullscreen !== undefined) {
  6689. _this.isFullscreen = document.fullscreen;
  6690. }
  6691. else if (document.mozFullScreen !== undefined) {
  6692. _this.isFullscreen = document.mozFullScreen;
  6693. }
  6694. else if (document.webkitIsFullScreen !== undefined) {
  6695. _this.isFullscreen = document.webkitIsFullScreen;
  6696. }
  6697. else if (document.msIsFullScreen !== undefined) {
  6698. _this.isFullscreen = document.msIsFullScreen;
  6699. }
  6700. // Pointer lock
  6701. if (_this.isFullscreen && _this._pointerLockRequested) {
  6702. canvas.requestPointerLock = canvas.requestPointerLock ||
  6703. canvas.msRequestPointerLock ||
  6704. canvas.mozRequestPointerLock ||
  6705. canvas.webkitRequestPointerLock;
  6706. if (canvas.requestPointerLock) {
  6707. canvas.requestPointerLock();
  6708. }
  6709. }
  6710. };
  6711. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6712. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6713. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6714. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6715. // Pointer lock
  6716. this._onPointerLockChange = function () {
  6717. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6718. document.webkitPointerLockElement === canvas ||
  6719. document.msPointerLockElement === canvas ||
  6720. document.pointerLockElement === canvas);
  6721. };
  6722. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6723. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6724. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6725. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6726. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6727. Engine.audioEngine = new BABYLON.AudioEngine();
  6728. }
  6729. //default loading screen
  6730. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6731. //Load WebVR Devices
  6732. if (options.autoEnableWebVR) {
  6733. this.initWebVR();
  6734. }
  6735. //Detect if we are running on a faulty buggy OS.
  6736. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6737. //ua sniffing is the tool of the devil.
  6738. this._badOS = regexp.test(navigator.userAgent);
  6739. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6740. }
  6741. Object.defineProperty(Engine, "NEVER", {
  6742. get: function () {
  6743. return Engine._NEVER;
  6744. },
  6745. enumerable: true,
  6746. configurable: true
  6747. });
  6748. Object.defineProperty(Engine, "ALWAYS", {
  6749. get: function () {
  6750. return Engine._ALWAYS;
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. Object.defineProperty(Engine, "LESS", {
  6756. get: function () {
  6757. return Engine._LESS;
  6758. },
  6759. enumerable: true,
  6760. configurable: true
  6761. });
  6762. Object.defineProperty(Engine, "EQUAL", {
  6763. get: function () {
  6764. return Engine._EQUAL;
  6765. },
  6766. enumerable: true,
  6767. configurable: true
  6768. });
  6769. Object.defineProperty(Engine, "LEQUAL", {
  6770. get: function () {
  6771. return Engine._LEQUAL;
  6772. },
  6773. enumerable: true,
  6774. configurable: true
  6775. });
  6776. Object.defineProperty(Engine, "GREATER", {
  6777. get: function () {
  6778. return Engine._GREATER;
  6779. },
  6780. enumerable: true,
  6781. configurable: true
  6782. });
  6783. Object.defineProperty(Engine, "GEQUAL", {
  6784. get: function () {
  6785. return Engine._GEQUAL;
  6786. },
  6787. enumerable: true,
  6788. configurable: true
  6789. });
  6790. Object.defineProperty(Engine, "NOTEQUAL", {
  6791. get: function () {
  6792. return Engine._NOTEQUAL;
  6793. },
  6794. enumerable: true,
  6795. configurable: true
  6796. });
  6797. Object.defineProperty(Engine, "KEEP", {
  6798. get: function () {
  6799. return Engine._KEEP;
  6800. },
  6801. enumerable: true,
  6802. configurable: true
  6803. });
  6804. Object.defineProperty(Engine, "REPLACE", {
  6805. get: function () {
  6806. return Engine._REPLACE;
  6807. },
  6808. enumerable: true,
  6809. configurable: true
  6810. });
  6811. Object.defineProperty(Engine, "INCR", {
  6812. get: function () {
  6813. return Engine._INCR;
  6814. },
  6815. enumerable: true,
  6816. configurable: true
  6817. });
  6818. Object.defineProperty(Engine, "DECR", {
  6819. get: function () {
  6820. return Engine._DECR;
  6821. },
  6822. enumerable: true,
  6823. configurable: true
  6824. });
  6825. Object.defineProperty(Engine, "INVERT", {
  6826. get: function () {
  6827. return Engine._INVERT;
  6828. },
  6829. enumerable: true,
  6830. configurable: true
  6831. });
  6832. Object.defineProperty(Engine, "INCR_WRAP", {
  6833. get: function () {
  6834. return Engine._INCR_WRAP;
  6835. },
  6836. enumerable: true,
  6837. configurable: true
  6838. });
  6839. Object.defineProperty(Engine, "DECR_WRAP", {
  6840. get: function () {
  6841. return Engine._DECR_WRAP;
  6842. },
  6843. enumerable: true,
  6844. configurable: true
  6845. });
  6846. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6847. get: function () {
  6848. return Engine._ALPHA_DISABLE;
  6849. },
  6850. enumerable: true,
  6851. configurable: true
  6852. });
  6853. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6854. get: function () {
  6855. return Engine._ALPHA_ONEONE;
  6856. },
  6857. enumerable: true,
  6858. configurable: true
  6859. });
  6860. Object.defineProperty(Engine, "ALPHA_ADD", {
  6861. get: function () {
  6862. return Engine._ALPHA_ADD;
  6863. },
  6864. enumerable: true,
  6865. configurable: true
  6866. });
  6867. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6868. get: function () {
  6869. return Engine._ALPHA_COMBINE;
  6870. },
  6871. enumerable: true,
  6872. configurable: true
  6873. });
  6874. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6875. get: function () {
  6876. return Engine._ALPHA_SUBTRACT;
  6877. },
  6878. enumerable: true,
  6879. configurable: true
  6880. });
  6881. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6882. get: function () {
  6883. return Engine._ALPHA_MULTIPLY;
  6884. },
  6885. enumerable: true,
  6886. configurable: true
  6887. });
  6888. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6889. get: function () {
  6890. return Engine._ALPHA_MAXIMIZED;
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6896. get: function () {
  6897. return Engine._DELAYLOADSTATE_NONE;
  6898. },
  6899. enumerable: true,
  6900. configurable: true
  6901. });
  6902. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6903. get: function () {
  6904. return Engine._DELAYLOADSTATE_LOADED;
  6905. },
  6906. enumerable: true,
  6907. configurable: true
  6908. });
  6909. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6910. get: function () {
  6911. return Engine._DELAYLOADSTATE_LOADING;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6917. get: function () {
  6918. return Engine._DELAYLOADSTATE_NOTLOADED;
  6919. },
  6920. enumerable: true,
  6921. configurable: true
  6922. });
  6923. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6924. get: function () {
  6925. return Engine._TEXTUREFORMAT_ALPHA;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6931. get: function () {
  6932. return Engine._TEXTUREFORMAT_LUMINANCE;
  6933. },
  6934. enumerable: true,
  6935. configurable: true
  6936. });
  6937. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6938. get: function () {
  6939. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6940. },
  6941. enumerable: true,
  6942. configurable: true
  6943. });
  6944. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6945. get: function () {
  6946. return Engine._TEXTUREFORMAT_RGB;
  6947. },
  6948. enumerable: true,
  6949. configurable: true
  6950. });
  6951. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6952. get: function () {
  6953. return Engine._TEXTUREFORMAT_RGBA;
  6954. },
  6955. enumerable: true,
  6956. configurable: true
  6957. });
  6958. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6959. get: function () {
  6960. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6961. },
  6962. enumerable: true,
  6963. configurable: true
  6964. });
  6965. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6966. get: function () {
  6967. return Engine._TEXTURETYPE_FLOAT;
  6968. },
  6969. enumerable: true,
  6970. configurable: true
  6971. });
  6972. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6973. get: function () {
  6974. return Engine._TEXTURETYPE_HALF_FLOAT;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. Object.defineProperty(Engine, "Version", {
  6980. get: function () {
  6981. return "2.6-alpha";
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(Engine.prototype, "texturesSupported", {
  6987. get: function () {
  6988. return this._texturesSupported;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  6994. get: function () {
  6995. return this._textureFormatInUse;
  6996. },
  6997. enumerable: true,
  6998. configurable: true
  6999. });
  7000. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7001. get: function () {
  7002. return this._webGLVersion;
  7003. },
  7004. enumerable: true,
  7005. configurable: true
  7006. });
  7007. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7008. /**
  7009. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7010. */
  7011. get: function () {
  7012. return this._isStencilEnable;
  7013. },
  7014. enumerable: true,
  7015. configurable: true
  7016. });
  7017. Engine.prototype._prepareWorkingCanvas = function () {
  7018. if (this._workingCanvas) {
  7019. return;
  7020. }
  7021. this._workingCanvas = document.createElement("canvas");
  7022. this._workingContext = this._workingCanvas.getContext("2d");
  7023. };
  7024. Engine.prototype.resetTextureCache = function () {
  7025. for (var index = 0; index < this._maxTextureChannels; index++) {
  7026. this._activeTexturesCache[index] = null;
  7027. }
  7028. };
  7029. Engine.prototype.getGlInfo = function () {
  7030. return {
  7031. vendor: this._glVendor,
  7032. renderer: this._glRenderer,
  7033. version: this._glVersion
  7034. };
  7035. };
  7036. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7037. if (useScreen === void 0) { useScreen = false; }
  7038. var viewport = camera.viewport;
  7039. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7040. };
  7041. Engine.prototype.getRenderWidth = function (useScreen) {
  7042. if (useScreen === void 0) { useScreen = false; }
  7043. if (!useScreen && this._currentRenderTarget) {
  7044. return this._currentRenderTarget._width;
  7045. }
  7046. return this._renderingCanvas.width;
  7047. };
  7048. Engine.prototype.getRenderHeight = function (useScreen) {
  7049. if (useScreen === void 0) { useScreen = false; }
  7050. if (!useScreen && this._currentRenderTarget) {
  7051. return this._currentRenderTarget._height;
  7052. }
  7053. return this._renderingCanvas.height;
  7054. };
  7055. Engine.prototype.getRenderingCanvas = function () {
  7056. return this._renderingCanvas;
  7057. };
  7058. Engine.prototype.getRenderingCanvasClientRect = function () {
  7059. return this._renderingCanvas.getBoundingClientRect();
  7060. };
  7061. Engine.prototype.setHardwareScalingLevel = function (level) {
  7062. this._hardwareScalingLevel = level;
  7063. this.resize();
  7064. };
  7065. Engine.prototype.getHardwareScalingLevel = function () {
  7066. return this._hardwareScalingLevel;
  7067. };
  7068. Engine.prototype.getLoadedTexturesCache = function () {
  7069. return this._loadedTexturesCache;
  7070. };
  7071. Engine.prototype.getCaps = function () {
  7072. return this._caps;
  7073. };
  7074. Object.defineProperty(Engine.prototype, "drawCalls", {
  7075. get: function () {
  7076. return this._drawCalls.current;
  7077. },
  7078. enumerable: true,
  7079. configurable: true
  7080. });
  7081. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7082. get: function () {
  7083. return this._drawCalls;
  7084. },
  7085. enumerable: true,
  7086. configurable: true
  7087. });
  7088. Engine.prototype.getDepthFunction = function () {
  7089. return this._depthCullingState.depthFunc;
  7090. };
  7091. Engine.prototype.setDepthFunction = function (depthFunc) {
  7092. this._depthCullingState.depthFunc = depthFunc;
  7093. };
  7094. Engine.prototype.setDepthFunctionToGreater = function () {
  7095. this._depthCullingState.depthFunc = this._gl.GREATER;
  7096. };
  7097. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7098. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7099. };
  7100. Engine.prototype.setDepthFunctionToLess = function () {
  7101. this._depthCullingState.depthFunc = this._gl.LESS;
  7102. };
  7103. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7104. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7105. };
  7106. Engine.prototype.getStencilBuffer = function () {
  7107. return this._stencilState.stencilTest;
  7108. };
  7109. Engine.prototype.setStencilBuffer = function (enable) {
  7110. this._stencilState.stencilTest = enable;
  7111. };
  7112. Engine.prototype.getStencilMask = function () {
  7113. return this._stencilState.stencilMask;
  7114. };
  7115. Engine.prototype.setStencilMask = function (mask) {
  7116. this._stencilState.stencilMask = mask;
  7117. };
  7118. Engine.prototype.getStencilFunction = function () {
  7119. return this._stencilState.stencilFunc;
  7120. };
  7121. Engine.prototype.getStencilFunctionReference = function () {
  7122. return this._stencilState.stencilFuncRef;
  7123. };
  7124. Engine.prototype.getStencilFunctionMask = function () {
  7125. return this._stencilState.stencilFuncMask;
  7126. };
  7127. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7128. this._stencilState.stencilFunc = stencilFunc;
  7129. };
  7130. Engine.prototype.setStencilFunctionReference = function (reference) {
  7131. this._stencilState.stencilFuncRef = reference;
  7132. };
  7133. Engine.prototype.setStencilFunctionMask = function (mask) {
  7134. this._stencilState.stencilFuncMask = mask;
  7135. };
  7136. Engine.prototype.getStencilOperationFail = function () {
  7137. return this._stencilState.stencilOpStencilFail;
  7138. };
  7139. Engine.prototype.getStencilOperationDepthFail = function () {
  7140. return this._stencilState.stencilOpDepthFail;
  7141. };
  7142. Engine.prototype.getStencilOperationPass = function () {
  7143. return this._stencilState.stencilOpStencilDepthPass;
  7144. };
  7145. Engine.prototype.setStencilOperationFail = function (operation) {
  7146. this._stencilState.stencilOpStencilFail = operation;
  7147. };
  7148. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7149. this._stencilState.stencilOpDepthFail = operation;
  7150. };
  7151. Engine.prototype.setStencilOperationPass = function (operation) {
  7152. this._stencilState.stencilOpStencilDepthPass = operation;
  7153. };
  7154. /**
  7155. * stop executing a render loop function and remove it from the execution array
  7156. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7157. */
  7158. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7159. if (!renderFunction) {
  7160. this._activeRenderLoops = [];
  7161. return;
  7162. }
  7163. var index = this._activeRenderLoops.indexOf(renderFunction);
  7164. if (index >= 0) {
  7165. this._activeRenderLoops.splice(index, 1);
  7166. }
  7167. };
  7168. Engine.prototype._renderLoop = function () {
  7169. var shouldRender = true;
  7170. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7171. shouldRender = false;
  7172. }
  7173. if (shouldRender) {
  7174. // Start new frame
  7175. this.beginFrame();
  7176. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7177. var renderFunction = this._activeRenderLoops[index];
  7178. renderFunction();
  7179. }
  7180. // Present
  7181. this.endFrame();
  7182. }
  7183. if (this._activeRenderLoops.length > 0) {
  7184. // Register new frame
  7185. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7186. }
  7187. else {
  7188. this._renderingQueueLaunched = false;
  7189. }
  7190. };
  7191. /**
  7192. * Register and execute a render loop. The engine can have more than one render function.
  7193. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7194. * @example
  7195. * engine.runRenderLoop(function () {
  7196. * scene.render()
  7197. * })
  7198. */
  7199. Engine.prototype.runRenderLoop = function (renderFunction) {
  7200. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7201. return;
  7202. }
  7203. this._activeRenderLoops.push(renderFunction);
  7204. if (!this._renderingQueueLaunched) {
  7205. this._renderingQueueLaunched = true;
  7206. this._bindedRenderFunction = this._renderLoop.bind(this);
  7207. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7208. }
  7209. };
  7210. /**
  7211. * Toggle full screen mode.
  7212. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7213. * @param {any} options - an options object to be sent to the requestFullscreen function
  7214. */
  7215. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7216. if (this.isFullscreen) {
  7217. BABYLON.Tools.ExitFullscreen();
  7218. }
  7219. else {
  7220. this._pointerLockRequested = requestPointerLock;
  7221. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7222. }
  7223. };
  7224. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7225. if (stencil === void 0) { stencil = false; }
  7226. this.applyStates();
  7227. var mode = 0;
  7228. if (backBuffer) {
  7229. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7230. mode |= this._gl.COLOR_BUFFER_BIT;
  7231. }
  7232. if (depth) {
  7233. this._gl.clearDepth(1.0);
  7234. mode |= this._gl.DEPTH_BUFFER_BIT;
  7235. }
  7236. if (stencil) {
  7237. this._gl.clearStencil(0);
  7238. mode |= this._gl.STENCIL_BUFFER_BIT;
  7239. }
  7240. this._gl.clear(mode);
  7241. };
  7242. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7243. var gl = this._gl;
  7244. // Save state
  7245. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7246. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7247. // Change state
  7248. gl.enable(gl.SCISSOR_TEST);
  7249. gl.scissor(x, y, width, height);
  7250. // Clear
  7251. this.clear(clearColor, true, true, true);
  7252. // Restore state
  7253. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7254. if (curScissor === true) {
  7255. gl.enable(gl.SCISSOR_TEST);
  7256. }
  7257. else {
  7258. gl.disable(gl.SCISSOR_TEST);
  7259. }
  7260. };
  7261. /**
  7262. * Set the WebGL's viewport
  7263. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7264. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7265. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7266. */
  7267. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7268. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7269. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7270. var x = viewport.x || 0;
  7271. var y = viewport.y || 0;
  7272. this._cachedViewport = viewport;
  7273. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7274. };
  7275. /**
  7276. * Directly set the WebGL Viewport
  7277. * The x, y, width & height are directly passed to the WebGL call
  7278. * @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.
  7279. */
  7280. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7281. var currentViewport = this._cachedViewport;
  7282. this._cachedViewport = null;
  7283. this._gl.viewport(x, y, width, height);
  7284. return currentViewport;
  7285. };
  7286. Engine.prototype.beginFrame = function () {
  7287. this._measureFps();
  7288. };
  7289. Engine.prototype.endFrame = function () {
  7290. //force a flush in case we are using a bad OS.
  7291. if (this._badOS) {
  7292. this.flushFramebuffer();
  7293. }
  7294. //submit frame to the vr device, if enabled
  7295. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7296. this._vrDisplayEnabled.submitFrame();
  7297. }
  7298. };
  7299. /**
  7300. * resize the view according to the canvas' size.
  7301. * @example
  7302. * window.addEventListener("resize", function () {
  7303. * engine.resize();
  7304. * });
  7305. */
  7306. Engine.prototype.resize = function () {
  7307. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7308. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7309. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7310. };
  7311. /**
  7312. * force a specific size of the canvas
  7313. * @param {number} width - the new canvas' width
  7314. * @param {number} height - the new canvas' height
  7315. */
  7316. Engine.prototype.setSize = function (width, height) {
  7317. this._renderingCanvas.width = width;
  7318. this._renderingCanvas.height = height;
  7319. for (var index = 0; index < this.scenes.length; index++) {
  7320. var scene = this.scenes[index];
  7321. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7322. var cam = scene.cameras[camIndex];
  7323. cam._currentRenderId = 0;
  7324. }
  7325. }
  7326. };
  7327. //WebVR functions
  7328. Engine.prototype.initWebVR = function () {
  7329. if (!this.vrDisplaysPromise) {
  7330. this._getVRDisplays();
  7331. }
  7332. };
  7333. Engine.prototype.enableVR = function (vrDevice) {
  7334. this._vrDisplayEnabled = vrDevice;
  7335. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7336. };
  7337. Engine.prototype.disableVR = function () {
  7338. if (this._vrDisplayEnabled) {
  7339. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7340. }
  7341. };
  7342. Engine.prototype._getVRDisplays = function () {
  7343. var _this = this;
  7344. var getWebVRDevices = function (devices) {
  7345. var size = devices.length;
  7346. var i = 0;
  7347. _this._vrDisplays = devices.filter(function (device) {
  7348. return devices[i] instanceof VRDisplay;
  7349. });
  7350. return _this._vrDisplays;
  7351. };
  7352. //using a key due to typescript
  7353. if (navigator.getVRDisplays) {
  7354. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7355. }
  7356. };
  7357. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7358. this._currentRenderTarget = texture;
  7359. this.bindUnboundFramebuffer(texture._framebuffer);
  7360. var gl = this._gl;
  7361. if (texture.isCube) {
  7362. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7363. }
  7364. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7365. this.wipeCaches();
  7366. };
  7367. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7368. if (this._currentFramebuffer !== framebuffer) {
  7369. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7370. this._currentFramebuffer = framebuffer;
  7371. }
  7372. };
  7373. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7374. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7375. this._currentRenderTarget = null;
  7376. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7377. var gl = this._gl;
  7378. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7379. gl.generateMipmap(gl.TEXTURE_2D);
  7380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7381. }
  7382. this.bindUnboundFramebuffer(null);
  7383. };
  7384. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7385. if (texture.generateMipMaps) {
  7386. var gl = this._gl;
  7387. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7388. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7390. }
  7391. };
  7392. Engine.prototype.flushFramebuffer = function () {
  7393. this._gl.flush();
  7394. };
  7395. Engine.prototype.restoreDefaultFramebuffer = function () {
  7396. this._currentRenderTarget = null;
  7397. this.bindUnboundFramebuffer(null);
  7398. this.setViewport(this._cachedViewport);
  7399. this.wipeCaches();
  7400. };
  7401. // VBOs
  7402. Engine.prototype._resetVertexBufferBinding = function () {
  7403. this.bindArrayBuffer(null);
  7404. this._cachedVertexBuffers = null;
  7405. };
  7406. Engine.prototype.createVertexBuffer = function (vertices) {
  7407. var vbo = this._gl.createBuffer();
  7408. this.bindArrayBuffer(vbo);
  7409. if (vertices instanceof Float32Array) {
  7410. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7411. }
  7412. else {
  7413. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7414. }
  7415. this._resetVertexBufferBinding();
  7416. vbo.references = 1;
  7417. return vbo;
  7418. };
  7419. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7420. var vbo = this._gl.createBuffer();
  7421. this.bindArrayBuffer(vbo);
  7422. if (vertices instanceof Float32Array) {
  7423. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7424. }
  7425. else {
  7426. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7427. }
  7428. this._resetVertexBufferBinding();
  7429. vbo.references = 1;
  7430. return vbo;
  7431. };
  7432. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7433. this.bindArrayBuffer(vertexBuffer);
  7434. if (offset === undefined) {
  7435. offset = 0;
  7436. }
  7437. if (count === undefined) {
  7438. if (vertices instanceof Float32Array) {
  7439. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7440. }
  7441. else {
  7442. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7443. }
  7444. }
  7445. else {
  7446. if (vertices instanceof Float32Array) {
  7447. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7448. }
  7449. else {
  7450. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7451. }
  7452. }
  7453. this._resetVertexBufferBinding();
  7454. };
  7455. Engine.prototype._resetIndexBufferBinding = function () {
  7456. this.bindIndexBuffer(null);
  7457. this._cachedIndexBuffer = null;
  7458. };
  7459. Engine.prototype.createIndexBuffer = function (indices) {
  7460. var vbo = this._gl.createBuffer();
  7461. this.bindIndexBuffer(vbo);
  7462. // Check for 32 bits indices
  7463. var arrayBuffer;
  7464. var need32Bits = false;
  7465. if (this._caps.uintIndices) {
  7466. for (var index = 0; index < indices.length; index++) {
  7467. if (indices[index] > 65535) {
  7468. need32Bits = true;
  7469. break;
  7470. }
  7471. }
  7472. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7473. }
  7474. else {
  7475. arrayBuffer = new Uint16Array(indices);
  7476. }
  7477. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7478. this._resetIndexBufferBinding();
  7479. vbo.references = 1;
  7480. vbo.is32Bits = need32Bits;
  7481. return vbo;
  7482. };
  7483. Engine.prototype.bindArrayBuffer = function (buffer) {
  7484. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7485. };
  7486. Engine.prototype.bindIndexBuffer = function (buffer) {
  7487. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7488. };
  7489. Engine.prototype.bindBuffer = function (buffer, target) {
  7490. if (this._currentBoundBuffer[target] !== buffer) {
  7491. this._gl.bindBuffer(target, buffer);
  7492. this._currentBoundBuffer[target] = buffer;
  7493. }
  7494. };
  7495. Engine.prototype.updateArrayBuffer = function (data) {
  7496. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7497. };
  7498. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7499. var pointer = this._currentBufferPointers[indx];
  7500. var changed = false;
  7501. if (!pointer) {
  7502. changed = true;
  7503. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7504. }
  7505. else {
  7506. if (pointer.buffer !== buffer) {
  7507. pointer.buffer = buffer;
  7508. changed = true;
  7509. }
  7510. if (pointer.size !== size) {
  7511. pointer.size = size;
  7512. changed = true;
  7513. }
  7514. if (pointer.type !== type) {
  7515. pointer.type = type;
  7516. changed = true;
  7517. }
  7518. if (pointer.normalized !== normalized) {
  7519. pointer.normalized = normalized;
  7520. changed = true;
  7521. }
  7522. if (pointer.stride !== stride) {
  7523. pointer.stride = stride;
  7524. changed = true;
  7525. }
  7526. if (pointer.offset !== offset) {
  7527. pointer.offset = offset;
  7528. changed = true;
  7529. }
  7530. }
  7531. if (changed) {
  7532. this.bindArrayBuffer(buffer);
  7533. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7534. }
  7535. };
  7536. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7537. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7538. this._cachedVertexBuffers = vertexBuffer;
  7539. this._cachedEffectForVertexBuffers = effect;
  7540. var attributesCount = effect.getAttributesCount();
  7541. this.unbindAllAttributes();
  7542. var offset = 0;
  7543. for (var index = 0; index < attributesCount; index++) {
  7544. if (index < vertexDeclaration.length) {
  7545. var order = effect.getAttributeLocation(index);
  7546. if (order >= 0) {
  7547. this._gl.enableVertexAttribArray(order);
  7548. this._vertexAttribArraysEnabled[order] = true;
  7549. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7550. }
  7551. offset += vertexDeclaration[index] * 4;
  7552. }
  7553. }
  7554. }
  7555. if (this._cachedIndexBuffer !== indexBuffer) {
  7556. this._cachedIndexBuffer = indexBuffer;
  7557. this.bindIndexBuffer(indexBuffer);
  7558. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7559. }
  7560. };
  7561. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7562. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7563. this._cachedVertexBuffers = vertexBuffers;
  7564. this._cachedEffectForVertexBuffers = effect;
  7565. var attributes = effect.getAttributesNames();
  7566. this.unbindAllAttributes();
  7567. for (var index = 0; index < attributes.length; index++) {
  7568. var order = effect.getAttributeLocation(index);
  7569. if (order >= 0) {
  7570. var vertexBuffer = vertexBuffers[attributes[index]];
  7571. if (!vertexBuffer) {
  7572. continue;
  7573. }
  7574. this._gl.enableVertexAttribArray(order);
  7575. this._vertexAttribArraysEnabled[order] = true;
  7576. var buffer = vertexBuffer.getBuffer();
  7577. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7578. if (vertexBuffer.getIsInstanced()) {
  7579. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7580. this._currentInstanceLocations.push(order);
  7581. this._currentInstanceBuffers.push(buffer);
  7582. }
  7583. }
  7584. }
  7585. }
  7586. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7587. this._cachedIndexBuffer = indexBuffer;
  7588. this.bindIndexBuffer(indexBuffer);
  7589. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7590. }
  7591. };
  7592. Engine.prototype.unbindInstanceAttributes = function () {
  7593. var boundBuffer;
  7594. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7595. var instancesBuffer = this._currentInstanceBuffers[i];
  7596. if (boundBuffer != instancesBuffer) {
  7597. boundBuffer = instancesBuffer;
  7598. this.bindArrayBuffer(instancesBuffer);
  7599. }
  7600. var offsetLocation = this._currentInstanceLocations[i];
  7601. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7602. }
  7603. this._currentInstanceBuffers.length = 0;
  7604. this._currentInstanceLocations.length = 0;
  7605. };
  7606. Engine.prototype._releaseBuffer = function (buffer) {
  7607. buffer.references--;
  7608. if (buffer.references === 0) {
  7609. this._gl.deleteBuffer(buffer);
  7610. return true;
  7611. }
  7612. return false;
  7613. };
  7614. Engine.prototype.createInstancesBuffer = function (capacity) {
  7615. var buffer = this._gl.createBuffer();
  7616. buffer.capacity = capacity;
  7617. this.bindArrayBuffer(buffer);
  7618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7619. return buffer;
  7620. };
  7621. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7622. this._gl.deleteBuffer(buffer);
  7623. };
  7624. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7625. this.bindArrayBuffer(instancesBuffer);
  7626. if (data) {
  7627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7628. }
  7629. if (offsetLocations[0].index !== undefined) {
  7630. var stride = 0;
  7631. for (var i = 0; i < offsetLocations.length; i++) {
  7632. var ai = offsetLocations[i];
  7633. stride += ai.attributeSize * 4;
  7634. }
  7635. for (var i = 0; i < offsetLocations.length; i++) {
  7636. var ai = offsetLocations[i];
  7637. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7638. this._gl.enableVertexAttribArray(ai.index);
  7639. this._vertexAttribArraysEnabled[ai.index] = true;
  7640. }
  7641. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7642. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7643. this._currentInstanceLocations.push(ai.index);
  7644. this._currentInstanceBuffers.push(instancesBuffer);
  7645. }
  7646. }
  7647. else {
  7648. for (var index = 0; index < 4; index++) {
  7649. var offsetLocation = offsetLocations[index];
  7650. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7651. this._gl.enableVertexAttribArray(offsetLocation);
  7652. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7653. }
  7654. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7655. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7656. this._currentInstanceLocations.push(offsetLocation);
  7657. this._currentInstanceBuffers.push(instancesBuffer);
  7658. }
  7659. }
  7660. };
  7661. Engine.prototype.applyStates = function () {
  7662. this._depthCullingState.apply(this._gl);
  7663. this._stencilState.apply(this._gl);
  7664. this._alphaState.apply(this._gl);
  7665. };
  7666. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7667. // Apply states
  7668. this.applyStates();
  7669. this._drawCalls.addCount(1, false);
  7670. // Render
  7671. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7672. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7673. if (instancesCount) {
  7674. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7675. return;
  7676. }
  7677. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7678. };
  7679. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7680. // Apply states
  7681. this.applyStates();
  7682. this._drawCalls.addCount(1, false);
  7683. if (instancesCount) {
  7684. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7685. return;
  7686. }
  7687. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7688. };
  7689. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7690. // Apply states
  7691. this.applyStates();
  7692. this._drawCalls.addCount(1, false);
  7693. if (instancesCount) {
  7694. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7695. return;
  7696. }
  7697. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7698. };
  7699. // Shaders
  7700. Engine.prototype._releaseEffect = function (effect) {
  7701. if (this._compiledEffects[effect._key]) {
  7702. delete this._compiledEffects[effect._key];
  7703. if (effect.getProgram()) {
  7704. this._gl.deleteProgram(effect.getProgram());
  7705. }
  7706. }
  7707. };
  7708. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7709. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7710. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7711. var name = vertex + "+" + fragment + "@" + defines;
  7712. if (this._compiledEffects[name]) {
  7713. return this._compiledEffects[name];
  7714. }
  7715. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7716. effect._key = name;
  7717. this._compiledEffects[name] = effect;
  7718. return effect;
  7719. };
  7720. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7721. if (uniformsNames === void 0) { uniformsNames = []; }
  7722. if (samplers === void 0) { samplers = []; }
  7723. if (defines === void 0) { defines = ""; }
  7724. return this.createEffect({
  7725. vertex: "particles",
  7726. fragmentElement: fragmentName
  7727. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7728. };
  7729. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7730. context = context || this._gl;
  7731. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7732. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7733. var shaderProgram = context.createProgram();
  7734. context.attachShader(shaderProgram, vertexShader);
  7735. context.attachShader(shaderProgram, fragmentShader);
  7736. context.linkProgram(shaderProgram);
  7737. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7738. if (!linked) {
  7739. var error = context.getProgramInfoLog(shaderProgram);
  7740. if (error) {
  7741. throw new Error(error);
  7742. }
  7743. }
  7744. context.deleteShader(vertexShader);
  7745. context.deleteShader(fragmentShader);
  7746. return shaderProgram;
  7747. };
  7748. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7749. var results = [];
  7750. for (var index = 0; index < uniformsNames.length; index++) {
  7751. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7752. }
  7753. return results;
  7754. };
  7755. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7756. var results = [];
  7757. for (var index = 0; index < attributesNames.length; index++) {
  7758. try {
  7759. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7760. }
  7761. catch (e) {
  7762. results.push(-1);
  7763. }
  7764. }
  7765. return results;
  7766. };
  7767. Engine.prototype.enableEffect = function (effect) {
  7768. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7769. // if (effect && effect.onBind) {
  7770. // effect.onBind(effect);
  7771. // }
  7772. // return;
  7773. //}
  7774. // Use program
  7775. this.setProgram(effect.getProgram());
  7776. this._currentEffect = effect;
  7777. if (effect.onBind) {
  7778. effect.onBind(effect);
  7779. }
  7780. };
  7781. Engine.prototype.setIntArray = function (uniform, array) {
  7782. if (!uniform)
  7783. return;
  7784. this._gl.uniform1iv(uniform, array);
  7785. };
  7786. Engine.prototype.setIntArray2 = function (uniform, array) {
  7787. if (!uniform || array.length % 2 !== 0)
  7788. return;
  7789. this._gl.uniform2iv(uniform, array);
  7790. };
  7791. Engine.prototype.setIntArray3 = function (uniform, array) {
  7792. if (!uniform || array.length % 3 !== 0)
  7793. return;
  7794. this._gl.uniform3iv(uniform, array);
  7795. };
  7796. Engine.prototype.setIntArray4 = function (uniform, array) {
  7797. if (!uniform || array.length % 4 !== 0)
  7798. return;
  7799. this._gl.uniform4iv(uniform, array);
  7800. };
  7801. Engine.prototype.setFloatArray = function (uniform, array) {
  7802. if (!uniform)
  7803. return;
  7804. this._gl.uniform1fv(uniform, array);
  7805. };
  7806. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7807. if (!uniform || array.length % 2 !== 0)
  7808. return;
  7809. this._gl.uniform2fv(uniform, array);
  7810. };
  7811. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7812. if (!uniform || array.length % 3 !== 0)
  7813. return;
  7814. this._gl.uniform3fv(uniform, array);
  7815. };
  7816. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7817. if (!uniform || array.length % 4 !== 0)
  7818. return;
  7819. this._gl.uniform4fv(uniform, array);
  7820. };
  7821. Engine.prototype.setArray = function (uniform, array) {
  7822. if (!uniform)
  7823. return;
  7824. this._gl.uniform1fv(uniform, array);
  7825. };
  7826. Engine.prototype.setArray2 = function (uniform, array) {
  7827. if (!uniform || array.length % 2 !== 0)
  7828. return;
  7829. this._gl.uniform2fv(uniform, array);
  7830. };
  7831. Engine.prototype.setArray3 = function (uniform, array) {
  7832. if (!uniform || array.length % 3 !== 0)
  7833. return;
  7834. this._gl.uniform3fv(uniform, array);
  7835. };
  7836. Engine.prototype.setArray4 = function (uniform, array) {
  7837. if (!uniform || array.length % 4 !== 0)
  7838. return;
  7839. this._gl.uniform4fv(uniform, array);
  7840. };
  7841. Engine.prototype.setMatrices = function (uniform, matrices) {
  7842. if (!uniform)
  7843. return;
  7844. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7845. };
  7846. Engine.prototype.setMatrix = function (uniform, matrix) {
  7847. if (!uniform)
  7848. return;
  7849. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7850. };
  7851. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7852. if (!uniform)
  7853. return;
  7854. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7855. };
  7856. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7857. if (!uniform)
  7858. return;
  7859. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7860. };
  7861. Engine.prototype.setFloat = function (uniform, value) {
  7862. if (!uniform)
  7863. return;
  7864. this._gl.uniform1f(uniform, value);
  7865. };
  7866. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7867. if (!uniform)
  7868. return;
  7869. this._gl.uniform2f(uniform, x, y);
  7870. };
  7871. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7872. if (!uniform)
  7873. return;
  7874. this._gl.uniform3f(uniform, x, y, z);
  7875. };
  7876. Engine.prototype.setBool = function (uniform, bool) {
  7877. if (!uniform)
  7878. return;
  7879. this._gl.uniform1i(uniform, bool);
  7880. };
  7881. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7882. if (!uniform)
  7883. return;
  7884. this._gl.uniform4f(uniform, x, y, z, w);
  7885. };
  7886. Engine.prototype.setColor3 = function (uniform, color3) {
  7887. if (!uniform)
  7888. return;
  7889. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7890. };
  7891. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7892. if (!uniform)
  7893. return;
  7894. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7895. };
  7896. // States
  7897. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7898. if (zOffset === void 0) { zOffset = 0; }
  7899. if (reverseSide === void 0) { reverseSide = false; }
  7900. // Culling
  7901. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7902. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7903. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7904. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7905. if (culling) {
  7906. this._depthCullingState.cullFace = cullFace;
  7907. this._depthCullingState.cull = true;
  7908. }
  7909. else {
  7910. this._depthCullingState.cull = false;
  7911. }
  7912. }
  7913. // Z offset
  7914. this._depthCullingState.zOffset = zOffset;
  7915. };
  7916. Engine.prototype.setDepthBuffer = function (enable) {
  7917. this._depthCullingState.depthTest = enable;
  7918. };
  7919. Engine.prototype.getDepthWrite = function () {
  7920. return this._depthCullingState.depthMask;
  7921. };
  7922. Engine.prototype.setDepthWrite = function (enable) {
  7923. this._depthCullingState.depthMask = enable;
  7924. };
  7925. Engine.prototype.setColorWrite = function (enable) {
  7926. this._gl.colorMask(enable, enable, enable, enable);
  7927. };
  7928. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7929. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7930. if (this._alphaMode === mode) {
  7931. return;
  7932. }
  7933. switch (mode) {
  7934. case Engine.ALPHA_DISABLE:
  7935. this._alphaState.alphaBlend = false;
  7936. break;
  7937. case Engine.ALPHA_COMBINE:
  7938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7939. this._alphaState.alphaBlend = true;
  7940. break;
  7941. case Engine.ALPHA_ONEONE:
  7942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7943. this._alphaState.alphaBlend = true;
  7944. break;
  7945. case Engine.ALPHA_ADD:
  7946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7947. this._alphaState.alphaBlend = true;
  7948. break;
  7949. case Engine.ALPHA_SUBTRACT:
  7950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7951. this._alphaState.alphaBlend = true;
  7952. break;
  7953. case Engine.ALPHA_MULTIPLY:
  7954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7955. this._alphaState.alphaBlend = true;
  7956. break;
  7957. case Engine.ALPHA_MAXIMIZED:
  7958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7959. this._alphaState.alphaBlend = true;
  7960. break;
  7961. }
  7962. if (!noDepthWriteChange) {
  7963. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7964. }
  7965. this._alphaMode = mode;
  7966. };
  7967. Engine.prototype.getAlphaMode = function () {
  7968. return this._alphaMode;
  7969. };
  7970. Engine.prototype.setAlphaTesting = function (enable) {
  7971. this._alphaTest = enable;
  7972. };
  7973. Engine.prototype.getAlphaTesting = function () {
  7974. return this._alphaTest;
  7975. };
  7976. // Textures
  7977. Engine.prototype.wipeCaches = function () {
  7978. this.resetTextureCache();
  7979. this._currentEffect = null;
  7980. this._stencilState.reset();
  7981. this._depthCullingState.reset();
  7982. this.setDepthFunctionToLessOrEqual();
  7983. this._alphaState.reset();
  7984. this._cachedVertexBuffers = null;
  7985. this._cachedIndexBuffer = null;
  7986. this._cachedEffectForVertexBuffers = null;
  7987. };
  7988. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7989. var gl = this._gl;
  7990. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7991. var magFilter = gl.NEAREST;
  7992. var minFilter = gl.NEAREST;
  7993. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7994. magFilter = gl.LINEAR;
  7995. minFilter = gl.LINEAR;
  7996. }
  7997. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7998. magFilter = gl.LINEAR;
  7999. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8000. }
  8001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  8002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  8003. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8004. texture.samplingMode = samplingMode;
  8005. };
  8006. /**
  8007. * Set the compressed texture format to use, based on the formats you have,
  8008. * the formats supported by the hardware / browser, and those currently implemented
  8009. * in BJS.
  8010. *
  8011. * Note: The result of this call is not taken into account texture is base64 or when
  8012. * using a database / manifest.
  8013. *
  8014. * @param {Array<string>} formatsAvailable - Extension names including dot. Case
  8015. * and order do not matter.
  8016. * @returns The extension selected.
  8017. */
  8018. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8019. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8020. // code to allow the formats to be added as they can be developed / hw tested
  8021. if (this._texturesSupported[i] === '.astc')
  8022. continue;
  8023. if (this._texturesSupported[i] === '.pvr')
  8024. continue;
  8025. if (this._texturesSupported[i] === '.etc1')
  8026. continue;
  8027. if (this._texturesSupported[i] === '.etc2')
  8028. continue;
  8029. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8030. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8031. return this._textureFormatInUse = this._texturesSupported[i];
  8032. }
  8033. }
  8034. }
  8035. // actively set format to nothing, to allow this to be called more than once
  8036. // and possibly fail the 2nd time
  8037. return this._textureFormatInUse = null;
  8038. };
  8039. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8040. var _this = this;
  8041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8042. if (onLoad === void 0) { onLoad = null; }
  8043. if (onError === void 0) { onError = null; }
  8044. if (buffer === void 0) { buffer = null; }
  8045. var texture = this._gl.createTexture();
  8046. var extension;
  8047. var fromData = false;
  8048. if (url.substr(0, 5) === "data:") {
  8049. fromData = true;
  8050. }
  8051. if (!fromData) {
  8052. var lastDot = url.lastIndexOf('.');
  8053. extension = url.substring(lastDot).toLowerCase();
  8054. if (this._textureFormatInUse && !fromData && !scene.database) {
  8055. extension = this._textureFormatInUse;
  8056. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8057. }
  8058. }
  8059. else {
  8060. var oldUrl = url;
  8061. fromData = oldUrl.split(':');
  8062. url = oldUrl;
  8063. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8064. }
  8065. var isDDS = (extension === ".dds");
  8066. var isTGA = (extension === ".tga");
  8067. scene._addPendingData(texture);
  8068. texture.url = url;
  8069. texture.noMipmap = noMipmap;
  8070. texture.references = 1;
  8071. texture.samplingMode = samplingMode;
  8072. texture.onLoadedCallbacks = [onLoad];
  8073. this._loadedTexturesCache.push(texture);
  8074. var onerror = function () {
  8075. scene._removePendingData(texture);
  8076. if (onError) {
  8077. onError();
  8078. }
  8079. };
  8080. var callback;
  8081. if (isTGA) {
  8082. callback = function (arrayBuffer) {
  8083. var data = new Uint8Array(arrayBuffer);
  8084. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8085. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8086. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8087. }, samplingMode);
  8088. };
  8089. if (!(fromData instanceof Array))
  8090. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  8091. callback(arrayBuffer);
  8092. }, null, scene.database, true, onerror);
  8093. else
  8094. callback(buffer);
  8095. }
  8096. else if (isDDS) {
  8097. callback = function (data) {
  8098. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8099. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8100. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8101. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8102. }, samplingMode);
  8103. };
  8104. if (!(fromData instanceof Array))
  8105. BABYLON.Tools.LoadFile(url, function (data) {
  8106. callback(data);
  8107. }, null, scene.database, true, onerror);
  8108. else
  8109. callback(buffer);
  8110. }
  8111. else {
  8112. var onload = function (img) {
  8113. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8114. var isPot = (img.width === potWidth && img.height === potHeight);
  8115. if (!isPot) {
  8116. _this._prepareWorkingCanvas();
  8117. _this._workingCanvas.width = potWidth;
  8118. _this._workingCanvas.height = potHeight;
  8119. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8120. _this._workingContext.imageSmoothingEnabled = false;
  8121. _this._workingContext.mozImageSmoothingEnabled = false;
  8122. _this._workingContext.oImageSmoothingEnabled = false;
  8123. _this._workingContext.webkitImageSmoothingEnabled = false;
  8124. _this._workingContext.msImageSmoothingEnabled = false;
  8125. }
  8126. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8127. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8128. _this._workingContext.imageSmoothingEnabled = true;
  8129. _this._workingContext.mozImageSmoothingEnabled = true;
  8130. _this._workingContext.oImageSmoothingEnabled = true;
  8131. _this._workingContext.webkitImageSmoothingEnabled = true;
  8132. _this._workingContext.msImageSmoothingEnabled = true;
  8133. }
  8134. }
  8135. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8136. }, samplingMode);
  8137. };
  8138. if (!(fromData instanceof Array))
  8139. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8140. else
  8141. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8142. }
  8143. return texture;
  8144. };
  8145. Engine.prototype._getInternalFormat = function (format) {
  8146. var internalFormat = this._gl.RGBA;
  8147. switch (format) {
  8148. case Engine.TEXTUREFORMAT_ALPHA:
  8149. internalFormat = this._gl.ALPHA;
  8150. break;
  8151. case Engine.TEXTUREFORMAT_LUMINANCE:
  8152. internalFormat = this._gl.LUMINANCE;
  8153. break;
  8154. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8155. internalFormat = this._gl.LUMINANCE_ALPHA;
  8156. break;
  8157. case Engine.TEXTUREFORMAT_RGB:
  8158. internalFormat = this._gl.RGB;
  8159. break;
  8160. case Engine.TEXTUREFORMAT_RGBA:
  8161. internalFormat = this._gl.RGBA;
  8162. break;
  8163. }
  8164. return internalFormat;
  8165. };
  8166. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8167. if (compression === void 0) { compression = null; }
  8168. var internalFormat = this._getInternalFormat(format);
  8169. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8170. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8171. if (texture._width % 4 !== 0) {
  8172. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8173. }
  8174. if (compression) {
  8175. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8176. }
  8177. else {
  8178. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8179. }
  8180. if (texture.generateMipMaps) {
  8181. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8182. }
  8183. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8184. this.resetTextureCache();
  8185. texture.isReady = true;
  8186. };
  8187. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8188. if (compression === void 0) { compression = null; }
  8189. var texture = this._gl.createTexture();
  8190. texture._baseWidth = width;
  8191. texture._baseHeight = height;
  8192. texture._width = width;
  8193. texture._height = height;
  8194. texture.references = 1;
  8195. this.updateRawTexture(texture, data, format, invertY, compression);
  8196. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8197. // Filters
  8198. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8199. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8201. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8202. texture.samplingMode = samplingMode;
  8203. this._loadedTexturesCache.push(texture);
  8204. return texture;
  8205. };
  8206. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8207. var texture = this._gl.createTexture();
  8208. texture._baseWidth = width;
  8209. texture._baseHeight = height;
  8210. if (generateMipMaps) {
  8211. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8212. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8213. }
  8214. this.resetTextureCache();
  8215. texture._width = width;
  8216. texture._height = height;
  8217. texture.isReady = false;
  8218. texture.generateMipMaps = generateMipMaps;
  8219. texture.references = 1;
  8220. texture.samplingMode = samplingMode;
  8221. this.updateTextureSamplingMode(samplingMode, texture);
  8222. this._loadedTexturesCache.push(texture);
  8223. return texture;
  8224. };
  8225. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8226. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8227. if (texture.isCube) {
  8228. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8229. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8230. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8231. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8232. }
  8233. else {
  8234. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8235. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8236. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8237. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8238. }
  8239. };
  8240. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8241. if (premulAlpha === void 0) { premulAlpha = false; }
  8242. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8244. if (premulAlpha) {
  8245. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8246. }
  8247. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8248. if (texture.generateMipMaps) {
  8249. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8250. }
  8251. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8252. if (premulAlpha) {
  8253. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8254. }
  8255. this.resetTextureCache();
  8256. texture.isReady = true;
  8257. };
  8258. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8259. if (texture._isDisabled) {
  8260. return;
  8261. }
  8262. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8263. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8264. try {
  8265. // Testing video texture support
  8266. if (this._videoTextureSupported === undefined) {
  8267. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8268. if (this._gl.getError() !== 0) {
  8269. this._videoTextureSupported = false;
  8270. }
  8271. else {
  8272. this._videoTextureSupported = true;
  8273. }
  8274. }
  8275. // Copy video through the current working canvas if video texture is not supported
  8276. if (!this._videoTextureSupported) {
  8277. if (!texture._workingCanvas) {
  8278. texture._workingCanvas = document.createElement("canvas");
  8279. texture._workingContext = texture._workingCanvas.getContext("2d");
  8280. texture._workingCanvas.width = texture._width;
  8281. texture._workingCanvas.height = texture._height;
  8282. }
  8283. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8284. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8285. }
  8286. else {
  8287. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8288. }
  8289. if (texture.generateMipMaps) {
  8290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8291. }
  8292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8293. this.resetTextureCache();
  8294. texture.isReady = true;
  8295. }
  8296. catch (ex) {
  8297. // Something unexpected
  8298. // Let's disable the texture
  8299. texture._isDisabled = true;
  8300. }
  8301. };
  8302. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8303. // old version had a "generateMipMaps" arg instead of options.
  8304. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8305. // in the same way, generateDepthBuffer is defaulted to true
  8306. var generateMipMaps = false;
  8307. var generateDepthBuffer = true;
  8308. var generateStencilBuffer = false;
  8309. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8310. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8311. if (options !== undefined) {
  8312. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8313. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8314. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8315. type = options.type === undefined ? type : options.type;
  8316. if (options.samplingMode !== undefined) {
  8317. samplingMode = options.samplingMode;
  8318. }
  8319. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8320. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8321. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8322. }
  8323. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8324. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8325. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8326. }
  8327. }
  8328. var gl = this._gl;
  8329. var texture = gl.createTexture();
  8330. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8331. var width = size.width || size;
  8332. var height = size.height || size;
  8333. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8334. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8335. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8336. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8337. }
  8338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8342. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8343. var depthStencilBuffer;
  8344. // Create the depth/stencil buffer
  8345. if (generateStencilBuffer) {
  8346. depthStencilBuffer = gl.createRenderbuffer();
  8347. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8348. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8349. }
  8350. else if (generateDepthBuffer) {
  8351. depthStencilBuffer = gl.createRenderbuffer();
  8352. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8353. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8354. }
  8355. // Create the framebuffer
  8356. var framebuffer = gl.createFramebuffer();
  8357. this.bindUnboundFramebuffer(framebuffer);
  8358. // Manage attachments
  8359. if (generateStencilBuffer) {
  8360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8361. }
  8362. else if (generateDepthBuffer) {
  8363. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8364. }
  8365. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8366. if (generateMipMaps) {
  8367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8368. }
  8369. // Unbind
  8370. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8371. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8372. this.bindUnboundFramebuffer(null);
  8373. texture._framebuffer = framebuffer;
  8374. if (generateDepthBuffer) {
  8375. texture._depthBuffer = depthStencilBuffer;
  8376. }
  8377. texture._baseWidth = width;
  8378. texture._baseHeight = height;
  8379. texture._width = width;
  8380. texture._height = height;
  8381. texture.isReady = true;
  8382. texture.generateMipMaps = generateMipMaps;
  8383. texture.references = 1;
  8384. texture.samplingMode = samplingMode;
  8385. texture.type = type;
  8386. this.resetTextureCache();
  8387. this._loadedTexturesCache.push(texture);
  8388. return texture;
  8389. };
  8390. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8391. var gl = this._gl;
  8392. var texture = gl.createTexture();
  8393. var generateMipMaps = true;
  8394. var generateDepthBuffer = true;
  8395. var generateStencilBuffer = false;
  8396. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8397. if (options !== undefined) {
  8398. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8399. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8400. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8401. if (options.samplingMode !== undefined) {
  8402. samplingMode = options.samplingMode;
  8403. }
  8404. }
  8405. texture.isCube = true;
  8406. texture.references = 1;
  8407. texture.generateMipMaps = generateMipMaps;
  8408. texture.references = 1;
  8409. texture.samplingMode = samplingMode;
  8410. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8412. for (var face = 0; face < 6; face++) {
  8413. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8414. }
  8415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8419. // Create the depth buffer
  8420. var depthStencilBuffer;
  8421. // Create the depth/stencil buffer
  8422. if (generateStencilBuffer) {
  8423. depthStencilBuffer = gl.createRenderbuffer();
  8424. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8425. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8426. }
  8427. else if (generateDepthBuffer) {
  8428. depthStencilBuffer = gl.createRenderbuffer();
  8429. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8430. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8431. }
  8432. // Create the framebuffer
  8433. var framebuffer = gl.createFramebuffer();
  8434. this.bindUnboundFramebuffer(framebuffer);
  8435. // Manage attachments
  8436. if (generateStencilBuffer) {
  8437. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8438. }
  8439. else if (generateDepthBuffer) {
  8440. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8441. }
  8442. // Mipmaps
  8443. if (texture.generateMipMaps) {
  8444. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8445. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8446. }
  8447. // Unbind
  8448. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8449. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8450. this.bindUnboundFramebuffer(null);
  8451. texture._framebuffer = framebuffer;
  8452. if (generateDepthBuffer) {
  8453. texture._depthBuffer = depthStencilBuffer;
  8454. }
  8455. texture._width = size;
  8456. texture._height = size;
  8457. texture.isReady = true;
  8458. this.resetTextureCache();
  8459. this._loadedTexturesCache.push(texture);
  8460. return texture;
  8461. };
  8462. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8463. var _this = this;
  8464. if (onLoad === void 0) { onLoad = null; }
  8465. if (onError === void 0) { onError = null; }
  8466. var gl = this._gl;
  8467. var texture = gl.createTexture();
  8468. texture.isCube = true;
  8469. texture.url = rootUrl;
  8470. texture.references = 1;
  8471. texture.onLoadedCallbacks = [];
  8472. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8473. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8474. if (isDDS) {
  8475. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8476. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8477. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8478. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8480. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8481. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8482. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8483. }
  8484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8488. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8489. _this.resetTextureCache();
  8490. texture._width = info.width;
  8491. texture._height = info.height;
  8492. texture.isReady = true;
  8493. }, null, null, true, onError);
  8494. }
  8495. else {
  8496. cascadeLoad(rootUrl, scene, function (imgs) {
  8497. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8498. var height = width;
  8499. _this._prepareWorkingCanvas();
  8500. _this._workingCanvas.width = width;
  8501. _this._workingCanvas.height = height;
  8502. var faces = [
  8503. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8504. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8505. ];
  8506. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8507. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8508. for (var index = 0; index < faces.length; index++) {
  8509. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8510. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8511. }
  8512. if (!noMipmap) {
  8513. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8514. }
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8520. _this.resetTextureCache();
  8521. texture._width = width;
  8522. texture._height = height;
  8523. texture.isReady = true;
  8524. texture.onLoadedCallbacks.forEach(function (callback) {
  8525. callback();
  8526. });
  8527. if (onLoad) {
  8528. onLoad();
  8529. }
  8530. }, files, onError);
  8531. }
  8532. this._loadedTexturesCache.push(texture);
  8533. return texture;
  8534. };
  8535. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8536. texture._width = width;
  8537. texture._height = height;
  8538. texture._size = width * height;
  8539. texture._baseWidth = width;
  8540. texture._baseHeight = height;
  8541. };
  8542. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8543. var _this = this;
  8544. var gl = this._gl;
  8545. var texture = gl.createTexture();
  8546. scene._addPendingData(texture);
  8547. texture.isCube = true;
  8548. texture.references = 1;
  8549. texture.url = url;
  8550. var internalFormat = this._getInternalFormat(format);
  8551. var textureType = gl.UNSIGNED_BYTE;
  8552. if (type === Engine.TEXTURETYPE_FLOAT) {
  8553. textureType = gl.FLOAT;
  8554. }
  8555. var width = size;
  8556. var height = width;
  8557. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8558. texture._width = width;
  8559. texture._height = height;
  8560. var onerror = function () {
  8561. scene._removePendingData(texture);
  8562. };
  8563. var internalCallback = function (data) {
  8564. var rgbeDataArrays = callback(data);
  8565. var facesIndex = [
  8566. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8567. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8568. ];
  8569. width = texture._width;
  8570. height = texture._height;
  8571. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8573. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8574. if (!noMipmap && isPot) {
  8575. if (mipmmapGenerator) {
  8576. var arrayTemp = [];
  8577. // Data are known to be in +X +Y +Z -X -Y -Z
  8578. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8579. arrayTemp.push(rgbeDataArrays[0]); // +X
  8580. arrayTemp.push(rgbeDataArrays[3]); // -X
  8581. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8582. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8583. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8584. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8585. var mipData = mipmmapGenerator(arrayTemp);
  8586. for (var level = 0; level < mipData.length; level++) {
  8587. var mipSize = width >> level;
  8588. // mipData is order in +X -X +Y -Y +Z -Z
  8589. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8590. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8591. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8592. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8593. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8594. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8595. }
  8596. }
  8597. else {
  8598. // Data are known to be in +X +Y +Z -X -Y -Z
  8599. for (var index = 0; index < facesIndex.length; index++) {
  8600. var faceData = rgbeDataArrays[index];
  8601. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8602. }
  8603. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8604. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8605. // By following the webgl standard changes from Revision 7, 2014/11/24
  8606. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8607. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8608. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8609. // Data are known to be in +X +Y +Z -X -Y -Z
  8610. for (var index = 0; index < facesIndex.length; index++) {
  8611. var faceData = rgbeDataArrays[index];
  8612. // Create a new RGBA Face.
  8613. var newFaceData = new Float32Array(width * height * 4);
  8614. for (var x = 0; x < width; x++) {
  8615. for (var y = 0; y < height; y++) {
  8616. var index_1 = (y * width + x) * 3;
  8617. var newIndex = (y * width + x) * 4;
  8618. // Map Old Value to new value.
  8619. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8620. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8621. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8622. // Add fully opaque alpha channel.
  8623. newFaceData[newIndex + 3] = 1;
  8624. }
  8625. }
  8626. // Reupload the face.
  8627. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8628. }
  8629. // Try to generate mipmap again.
  8630. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8631. }
  8632. }
  8633. }
  8634. else {
  8635. noMipmap = true;
  8636. }
  8637. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8640. }
  8641. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8644. }
  8645. else {
  8646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8648. }
  8649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8651. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8652. texture.isReady = true;
  8653. _this.resetTextureCache();
  8654. scene._removePendingData(texture);
  8655. };
  8656. BABYLON.Tools.LoadFile(url, function (data) {
  8657. internalCallback(data);
  8658. }, onerror, scene.database, true);
  8659. return texture;
  8660. };
  8661. ;
  8662. Engine.prototype._releaseTexture = function (texture) {
  8663. var gl = this._gl;
  8664. if (texture._framebuffer) {
  8665. gl.deleteFramebuffer(texture._framebuffer);
  8666. }
  8667. if (texture._depthBuffer) {
  8668. gl.deleteRenderbuffer(texture._depthBuffer);
  8669. }
  8670. gl.deleteTexture(texture);
  8671. // Unbind channels
  8672. this.unbindAllTextures();
  8673. var index = this._loadedTexturesCache.indexOf(texture);
  8674. if (index !== -1) {
  8675. this._loadedTexturesCache.splice(index, 1);
  8676. }
  8677. };
  8678. Engine.prototype.setProgram = function (program) {
  8679. if (this._currentProgram !== program) {
  8680. this._gl.useProgram(program);
  8681. this._currentProgram = program;
  8682. }
  8683. };
  8684. Engine.prototype.bindSamplers = function (effect) {
  8685. this.setProgram(effect.getProgram());
  8686. var samplers = effect.getSamplers();
  8687. for (var index = 0; index < samplers.length; index++) {
  8688. var uniform = effect.getUniform(samplers[index]);
  8689. this._gl.uniform1i(uniform, index);
  8690. }
  8691. this._currentEffect = null;
  8692. };
  8693. Engine.prototype.activateTexture = function (texture) {
  8694. if (this._activeTexture !== texture) {
  8695. this._gl.activeTexture(texture);
  8696. this._activeTexture = texture;
  8697. }
  8698. };
  8699. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8700. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8701. this._gl.bindTexture(target, texture);
  8702. this._activeTexturesCache[this._activeTexture] = texture;
  8703. }
  8704. };
  8705. Engine.prototype._bindTexture = function (channel, texture) {
  8706. if (channel < 0) {
  8707. return;
  8708. }
  8709. this.activateTexture(this._gl["TEXTURE" + channel]);
  8710. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8711. };
  8712. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8713. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8714. };
  8715. Engine.prototype.unbindAllTextures = function () {
  8716. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8717. this.activateTexture(this._gl["TEXTURE" + channel]);
  8718. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8719. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8720. }
  8721. };
  8722. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8723. if (channel < 0) {
  8724. return;
  8725. }
  8726. this._gl.uniform1i(uniform, channel);
  8727. this._setTexture(channel, texture);
  8728. };
  8729. Engine.prototype._setTexture = function (channel, texture) {
  8730. // Not ready?
  8731. if (!texture || !texture.isReady()) {
  8732. if (this._activeTexturesCache[channel] != null) {
  8733. this.activateTexture(this._gl["TEXTURE" + channel]);
  8734. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8735. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8736. }
  8737. return;
  8738. }
  8739. // Video
  8740. var alreadyActivated = false;
  8741. if (texture instanceof BABYLON.VideoTexture) {
  8742. this.activateTexture(this._gl["TEXTURE" + channel]);
  8743. alreadyActivated = true;
  8744. texture.update();
  8745. }
  8746. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8747. texture.delayLoad();
  8748. return;
  8749. }
  8750. var internalTexture = texture.getInternalTexture();
  8751. if (this._activeTexturesCache[channel] === internalTexture) {
  8752. return;
  8753. }
  8754. if (!alreadyActivated) {
  8755. this.activateTexture(this._gl["TEXTURE" + channel]);
  8756. }
  8757. if (internalTexture.isCube) {
  8758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8759. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8760. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8761. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8762. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8763. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8764. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8765. }
  8766. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8767. }
  8768. else {
  8769. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8770. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8771. internalTexture._cachedWrapU = texture.wrapU;
  8772. switch (texture.wrapU) {
  8773. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8774. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8775. break;
  8776. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8777. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8778. break;
  8779. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8780. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8781. break;
  8782. }
  8783. }
  8784. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8785. internalTexture._cachedWrapV = texture.wrapV;
  8786. switch (texture.wrapV) {
  8787. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8789. break;
  8790. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8792. break;
  8793. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8795. break;
  8796. }
  8797. }
  8798. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8799. }
  8800. };
  8801. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8802. if (channel < 0) {
  8803. return;
  8804. }
  8805. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8806. this._textureUnits = new Int32Array(textures.length);
  8807. }
  8808. for (var i = 0; i < textures.length; i++) {
  8809. this._textureUnits[i] = channel + i;
  8810. }
  8811. this._gl.uniform1iv(uniform, this._textureUnits);
  8812. for (var index = 0; index < textures.length; index++) {
  8813. this._setTexture(channel + index, textures[index]);
  8814. }
  8815. };
  8816. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8817. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8818. var value = texture.anisotropicFilteringLevel;
  8819. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8820. value = 1;
  8821. }
  8822. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8823. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8824. texture._cachedAnisotropicFilteringLevel = value;
  8825. }
  8826. };
  8827. Engine.prototype.readPixels = function (x, y, width, height) {
  8828. var data = new Uint8Array(height * width * 4);
  8829. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8830. return data;
  8831. };
  8832. /**
  8833. * Add an externaly attached data from its key.
  8834. * This method call will fail and return false, if such key already exists.
  8835. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8836. * @param key the unique key that identifies the data
  8837. * @param data the data object to associate to the key for this Engine instance
  8838. * @return true if no such key were already present and the data was added successfully, false otherwise
  8839. */
  8840. Engine.prototype.addExternalData = function (key, data) {
  8841. return this._externalData.add(key, data);
  8842. };
  8843. /**
  8844. * Get an externaly attached data from its key
  8845. * @param key the unique key that identifies the data
  8846. * @return the associated data, if present (can be null), or undefined if not present
  8847. */
  8848. Engine.prototype.getExternalData = function (key) {
  8849. return this._externalData.get(key);
  8850. };
  8851. /**
  8852. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8853. * @param key the unique key that identifies the data
  8854. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8855. * @return the associated data, can be null if the factory returned null.
  8856. */
  8857. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8858. return this._externalData.getOrAddWithFactory(key, factory);
  8859. };
  8860. /**
  8861. * Remove an externaly attached data from the Engine instance
  8862. * @param key the unique key that identifies the data
  8863. * @return true if the data was successfully removed, false if it doesn't exist
  8864. */
  8865. Engine.prototype.removeExternalData = function (key) {
  8866. return this._externalData.remove(key);
  8867. };
  8868. Engine.prototype.releaseInternalTexture = function (texture) {
  8869. if (!texture) {
  8870. return;
  8871. }
  8872. texture.references--;
  8873. // Final reference ?
  8874. if (texture.references === 0) {
  8875. var texturesCache = this.getLoadedTexturesCache();
  8876. var index = texturesCache.indexOf(texture);
  8877. if (index > -1) {
  8878. texturesCache.splice(index, 1);
  8879. }
  8880. this._releaseTexture(texture);
  8881. }
  8882. };
  8883. Engine.prototype.unbindAllAttributes = function () {
  8884. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8885. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8886. continue;
  8887. }
  8888. if (this._vertexAttribArraysEnabled[i]) {
  8889. this._gl.disableVertexAttribArray(i);
  8890. this._vertexAttribArraysEnabled[i] = false;
  8891. }
  8892. }
  8893. };
  8894. // Dispose
  8895. Engine.prototype.dispose = function () {
  8896. this.hideLoadingUI();
  8897. this.stopRenderLoop();
  8898. // Release scenes
  8899. while (this.scenes.length) {
  8900. this.scenes[0].dispose();
  8901. }
  8902. // Release audio engine
  8903. Engine.audioEngine.dispose();
  8904. // Release effects
  8905. for (var name in this._compiledEffects) {
  8906. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8907. }
  8908. // Unbind
  8909. this.unbindAllAttributes();
  8910. this._gl = null;
  8911. //WebVR
  8912. this.disableVR();
  8913. // Events
  8914. window.removeEventListener("blur", this._onBlur);
  8915. window.removeEventListener("focus", this._onFocus);
  8916. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8917. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8918. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8919. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8920. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8921. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8922. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8923. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8924. };
  8925. // Loading screen
  8926. Engine.prototype.displayLoadingUI = function () {
  8927. this._loadingScreen.displayLoadingUI();
  8928. };
  8929. Engine.prototype.hideLoadingUI = function () {
  8930. this._loadingScreen.hideLoadingUI();
  8931. };
  8932. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8933. get: function () {
  8934. return this._loadingScreen;
  8935. },
  8936. set: function (loadingScreen) {
  8937. this._loadingScreen = loadingScreen;
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8943. set: function (text) {
  8944. this._loadingScreen.loadingUIText = text;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8950. set: function (color) {
  8951. this._loadingScreen.loadingUIBackgroundColor = color;
  8952. },
  8953. enumerable: true,
  8954. configurable: true
  8955. });
  8956. Engine.prototype.attachContextLostEvent = function (callback) {
  8957. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8958. };
  8959. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8960. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8961. };
  8962. Engine.prototype.getVertexShaderSource = function (program) {
  8963. var shaders = this._gl.getAttachedShaders(program);
  8964. return this._gl.getShaderSource(shaders[0]);
  8965. };
  8966. Engine.prototype.getFragmentShaderSource = function (program) {
  8967. var shaders = this._gl.getAttachedShaders(program);
  8968. return this._gl.getShaderSource(shaders[1]);
  8969. };
  8970. // FPS
  8971. Engine.prototype.getFps = function () {
  8972. return this.fps;
  8973. };
  8974. Engine.prototype.getDeltaTime = function () {
  8975. return this.deltaTime;
  8976. };
  8977. Engine.prototype._measureFps = function () {
  8978. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8979. var length = this.previousFramesDuration.length;
  8980. if (length >= 2) {
  8981. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8982. }
  8983. if (length >= this.fpsRange) {
  8984. if (length > this.fpsRange) {
  8985. this.previousFramesDuration.splice(0, 1);
  8986. length = this.previousFramesDuration.length;
  8987. }
  8988. var sum = 0;
  8989. for (var id = 0; id < length - 1; id++) {
  8990. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8991. }
  8992. this.fps = 1000.0 / (sum / (length - 1));
  8993. }
  8994. };
  8995. Engine.prototype._canRenderToFloatTexture = function () {
  8996. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8997. };
  8998. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8999. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  9000. };
  9001. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9002. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9003. var tempcanvas = document.createElement("canvas");
  9004. tempcanvas.height = 16;
  9005. tempcanvas.width = 16;
  9006. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9007. // extension.
  9008. var ext = gl.getExtension(extension);
  9009. if (!ext) {
  9010. return false;
  9011. }
  9012. // setup GLSL program
  9013. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9014. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  9015. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9016. gl.useProgram(program);
  9017. // look up where the vertex data needs to go.
  9018. var positionLocation = gl.getAttribLocation(program, "a_position");
  9019. var colorLoc = gl.getUniformLocation(program, "u_color");
  9020. // provide texture coordinates for the rectangle.
  9021. var positionBuffer = gl.createBuffer();
  9022. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9023. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9024. -1.0, -1.0,
  9025. 1.0, -1.0,
  9026. -1.0, 1.0,
  9027. -1.0, 1.0,
  9028. 1.0, -1.0,
  9029. 1.0, 1.0
  9030. ]), gl.STATIC_DRAW);
  9031. gl.enableVertexAttribArray(positionLocation);
  9032. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9033. var whiteTex = gl.createTexture();
  9034. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9035. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9036. var tex = gl.createTexture();
  9037. gl.bindTexture(gl.TEXTURE_2D, tex);
  9038. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9041. var fb = gl.createFramebuffer();
  9042. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9044. var cleanup = function () {
  9045. gl.deleteProgram(program);
  9046. gl.disableVertexAttribArray(positionLocation);
  9047. gl.deleteBuffer(positionBuffer);
  9048. gl.deleteFramebuffer(fb);
  9049. gl.deleteTexture(whiteTex);
  9050. gl.deleteTexture(tex);
  9051. };
  9052. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9053. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9054. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9055. cleanup();
  9056. return false;
  9057. }
  9058. // Draw the rectangle.
  9059. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9060. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9061. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9062. gl.bindTexture(gl.TEXTURE_2D, tex);
  9063. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9064. gl.clearColor(1, 0, 0, 1);
  9065. gl.clear(gl.COLOR_BUFFER_BIT);
  9066. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9067. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9068. var pixel = new Uint8Array(4);
  9069. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9070. if (pixel[0] !== 0 ||
  9071. pixel[1] < 248 ||
  9072. pixel[2] < 248 ||
  9073. pixel[3] < 254) {
  9074. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9075. cleanup();
  9076. return false;
  9077. }
  9078. // Succesfully rendered to "format" texture.
  9079. cleanup();
  9080. return true;
  9081. };
  9082. // Statics
  9083. Engine.isSupported = function () {
  9084. try {
  9085. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9086. if (navigator.isCocoonJS) {
  9087. return true;
  9088. }
  9089. var tempcanvas = document.createElement("canvas");
  9090. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9091. return gl != null && !!window.WebGLRenderingContext;
  9092. }
  9093. catch (e) {
  9094. return false;
  9095. }
  9096. };
  9097. return Engine;
  9098. }());
  9099. // Const statics
  9100. Engine._ALPHA_DISABLE = 0;
  9101. Engine._ALPHA_ADD = 1;
  9102. Engine._ALPHA_COMBINE = 2;
  9103. Engine._ALPHA_SUBTRACT = 3;
  9104. Engine._ALPHA_MULTIPLY = 4;
  9105. Engine._ALPHA_MAXIMIZED = 5;
  9106. Engine._ALPHA_ONEONE = 6;
  9107. Engine._DELAYLOADSTATE_NONE = 0;
  9108. Engine._DELAYLOADSTATE_LOADED = 1;
  9109. Engine._DELAYLOADSTATE_LOADING = 2;
  9110. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9111. Engine._TEXTUREFORMAT_ALPHA = 0;
  9112. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9113. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9114. Engine._TEXTUREFORMAT_RGB = 4;
  9115. Engine._TEXTUREFORMAT_RGBA = 5;
  9116. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9117. Engine._TEXTURETYPE_FLOAT = 1;
  9118. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9119. // Depht or Stencil test Constants.
  9120. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9121. 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.
  9122. 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.
  9123. 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.
  9124. 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.
  9125. 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.
  9126. 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.
  9127. 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.
  9128. // Stencil Actions Constants.
  9129. Engine._KEEP = 0x1E00;
  9130. Engine._REPLACE = 0x1E01;
  9131. Engine._INCR = 0x1E02;
  9132. Engine._DECR = 0x1E03;
  9133. Engine._INVERT = 0x150A;
  9134. Engine._INCR_WRAP = 0x8507;
  9135. Engine._DECR_WRAP = 0x8508;
  9136. // Updatable statics so stick with vars here
  9137. Engine.CollisionsEpsilon = 0.001;
  9138. Engine.CodeRepository = "src/";
  9139. Engine.ShadersRepository = "src/Shaders/";
  9140. BABYLON.Engine = Engine;
  9141. })(BABYLON || (BABYLON = {}));
  9142. //# sourceMappingURL=babylon.engine.js.map
  9143. var BABYLON;
  9144. (function (BABYLON) {
  9145. /**
  9146. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9147. */
  9148. var Node = (function () {
  9149. /**
  9150. * @constructor
  9151. * @param {string} name - the name and id to be given to this node
  9152. * @param {BABYLON.Scene} the scene this node will be added to
  9153. */
  9154. function Node(name, scene) {
  9155. this.state = "";
  9156. this.metadata = null;
  9157. this.doNotSerialize = false;
  9158. this.animations = new Array();
  9159. this._ranges = {};
  9160. this._childrenFlag = -1;
  9161. this._isEnabled = true;
  9162. this._isReady = true;
  9163. this._currentRenderId = -1;
  9164. this._parentRenderId = -1;
  9165. /**
  9166. * An event triggered when the mesh is disposed.
  9167. * @type {BABYLON.Observable}
  9168. */
  9169. this.onDisposeObservable = new BABYLON.Observable();
  9170. this.name = name;
  9171. this.id = name;
  9172. this._scene = scene;
  9173. this._initCache();
  9174. }
  9175. Object.defineProperty(Node.prototype, "parent", {
  9176. get: function () {
  9177. return this._parentNode;
  9178. },
  9179. set: function (parent) {
  9180. if (this._parentNode === parent) {
  9181. return;
  9182. }
  9183. if (this._parentNode) {
  9184. var index = this._parentNode._children.indexOf(this);
  9185. if (index !== -1) {
  9186. this._parentNode._children.splice(index, 1);
  9187. }
  9188. }
  9189. this._parentNode = parent;
  9190. if (this._parentNode) {
  9191. if (!this._parentNode._children) {
  9192. this._parentNode._children = new Array();
  9193. }
  9194. this._parentNode._children.push(this);
  9195. }
  9196. },
  9197. enumerable: true,
  9198. configurable: true
  9199. });
  9200. Node.prototype.getClassName = function () {
  9201. return "Node";
  9202. };
  9203. Object.defineProperty(Node.prototype, "onDispose", {
  9204. set: function (callback) {
  9205. if (this._onDisposeObserver) {
  9206. this.onDisposeObservable.remove(this._onDisposeObserver);
  9207. }
  9208. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9209. },
  9210. enumerable: true,
  9211. configurable: true
  9212. });
  9213. Node.prototype.getScene = function () {
  9214. return this._scene;
  9215. };
  9216. Node.prototype.getEngine = function () {
  9217. return this._scene.getEngine();
  9218. };
  9219. // override it in derived class
  9220. Node.prototype.getWorldMatrix = function () {
  9221. return BABYLON.Matrix.Identity();
  9222. };
  9223. // override it in derived class if you add new variables to the cache
  9224. // and call the parent class method
  9225. Node.prototype._initCache = function () {
  9226. this._cache = {};
  9227. this._cache.parent = undefined;
  9228. };
  9229. Node.prototype.updateCache = function (force) {
  9230. if (!force && this.isSynchronized())
  9231. return;
  9232. this._cache.parent = this.parent;
  9233. this._updateCache();
  9234. };
  9235. // override it in derived class if you add new variables to the cache
  9236. // and call the parent class method if !ignoreParentClass
  9237. Node.prototype._updateCache = function (ignoreParentClass) {
  9238. };
  9239. // override it in derived class if you add new variables to the cache
  9240. Node.prototype._isSynchronized = function () {
  9241. return true;
  9242. };
  9243. Node.prototype._markSyncedWithParent = function () {
  9244. this._parentRenderId = this.parent._currentRenderId;
  9245. };
  9246. Node.prototype.isSynchronizedWithParent = function () {
  9247. if (!this.parent) {
  9248. return true;
  9249. }
  9250. if (this._parentRenderId !== this.parent._currentRenderId) {
  9251. return false;
  9252. }
  9253. return this.parent.isSynchronized();
  9254. };
  9255. Node.prototype.isSynchronized = function (updateCache) {
  9256. var check = this.hasNewParent();
  9257. check = check || !this.isSynchronizedWithParent();
  9258. check = check || !this._isSynchronized();
  9259. if (updateCache)
  9260. this.updateCache(true);
  9261. return !check;
  9262. };
  9263. Node.prototype.hasNewParent = function (update) {
  9264. if (this._cache.parent === this.parent)
  9265. return false;
  9266. if (update)
  9267. this._cache.parent = this.parent;
  9268. return true;
  9269. };
  9270. /**
  9271. * Is this node ready to be used/rendered
  9272. * @return {boolean} is it ready
  9273. */
  9274. Node.prototype.isReady = function () {
  9275. return this._isReady;
  9276. };
  9277. /**
  9278. * Is this node enabled.
  9279. * If the node has a parent and is enabled, the parent will be inspected as well.
  9280. * @return {boolean} whether this node (and its parent) is enabled.
  9281. * @see setEnabled
  9282. */
  9283. Node.prototype.isEnabled = function () {
  9284. if (!this._isEnabled) {
  9285. return false;
  9286. }
  9287. if (this.parent) {
  9288. return this.parent.isEnabled();
  9289. }
  9290. return true;
  9291. };
  9292. /**
  9293. * Set the enabled state of this node.
  9294. * @param {boolean} value - the new enabled state
  9295. * @see isEnabled
  9296. */
  9297. Node.prototype.setEnabled = function (value) {
  9298. this._isEnabled = value;
  9299. };
  9300. /**
  9301. * Is this node a descendant of the given node.
  9302. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9303. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9304. * @see parent
  9305. */
  9306. Node.prototype.isDescendantOf = function (ancestor) {
  9307. if (this.parent) {
  9308. if (this.parent === ancestor) {
  9309. return true;
  9310. }
  9311. return this.parent.isDescendantOf(ancestor);
  9312. }
  9313. return false;
  9314. };
  9315. /**
  9316. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9317. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9318. * @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.
  9319. * @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.
  9320. */
  9321. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9322. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9323. if (!this._children) {
  9324. return;
  9325. }
  9326. for (var index = 0; index < this._children.length; index++) {
  9327. var item = this._children[index];
  9328. if (!predicate || predicate(item)) {
  9329. results.push(item);
  9330. }
  9331. if (!directDescendantsOnly) {
  9332. item._getDescendants(results, false, predicate);
  9333. }
  9334. }
  9335. };
  9336. /**
  9337. * Will return all nodes that have this node as ascendant.
  9338. * @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.
  9339. * @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.
  9340. * @return {BABYLON.Node[]} all children nodes of all types.
  9341. */
  9342. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9343. var results = [];
  9344. this._getDescendants(results, directDescendantsOnly, predicate);
  9345. return results;
  9346. };
  9347. /**
  9348. * @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.
  9349. * @Deprecated, legacy support.
  9350. * use getDecendants instead.
  9351. */
  9352. Node.prototype.getChildren = function (predicate) {
  9353. return this.getDescendants(true, predicate);
  9354. };
  9355. /**
  9356. * Get all child-meshes of this node.
  9357. */
  9358. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9359. var results = [];
  9360. this._getDescendants(results, directDecendantsOnly, function (node) {
  9361. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9362. });
  9363. return results;
  9364. };
  9365. Node.prototype._setReady = function (state) {
  9366. if (state === this._isReady) {
  9367. return;
  9368. }
  9369. if (!state) {
  9370. this._isReady = false;
  9371. return;
  9372. }
  9373. this._isReady = true;
  9374. if (this.onReady) {
  9375. this.onReady(this);
  9376. }
  9377. };
  9378. Node.prototype.getAnimationByName = function (name) {
  9379. for (var i = 0; i < this.animations.length; i++) {
  9380. var animation = this.animations[i];
  9381. if (animation.name === name) {
  9382. return animation;
  9383. }
  9384. }
  9385. return null;
  9386. };
  9387. Node.prototype.createAnimationRange = function (name, from, to) {
  9388. // check name not already in use
  9389. if (!this._ranges[name]) {
  9390. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9391. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9392. if (this.animations[i]) {
  9393. this.animations[i].createRange(name, from, to);
  9394. }
  9395. }
  9396. }
  9397. };
  9398. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9399. if (deleteFrames === void 0) { deleteFrames = true; }
  9400. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9401. if (this.animations[i]) {
  9402. this.animations[i].deleteRange(name, deleteFrames);
  9403. }
  9404. }
  9405. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9406. };
  9407. Node.prototype.getAnimationRange = function (name) {
  9408. return this._ranges[name];
  9409. };
  9410. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9411. var range = this.getAnimationRange(name);
  9412. if (!range) {
  9413. return null;
  9414. }
  9415. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9416. };
  9417. Node.prototype.serializeAnimationRanges = function () {
  9418. var serializationRanges = [];
  9419. for (var name in this._ranges) {
  9420. var range = {};
  9421. range.name = name;
  9422. range.from = this._ranges[name].from;
  9423. range.to = this._ranges[name].to;
  9424. serializationRanges.push(range);
  9425. }
  9426. return serializationRanges;
  9427. };
  9428. Node.prototype.dispose = function () {
  9429. this.parent = null;
  9430. // Callback
  9431. this.onDisposeObservable.notifyObservers(this);
  9432. this.onDisposeObservable.clear();
  9433. };
  9434. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9435. if (parsedNode.ranges) {
  9436. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9437. var data = parsedNode.ranges[index];
  9438. node.createAnimationRange(data.name, data.from, data.to);
  9439. }
  9440. }
  9441. };
  9442. return Node;
  9443. }());
  9444. __decorate([
  9445. BABYLON.serialize()
  9446. ], Node.prototype, "name", void 0);
  9447. __decorate([
  9448. BABYLON.serialize()
  9449. ], Node.prototype, "id", void 0);
  9450. __decorate([
  9451. BABYLON.serialize()
  9452. ], Node.prototype, "uniqueId", void 0);
  9453. __decorate([
  9454. BABYLON.serialize()
  9455. ], Node.prototype, "state", void 0);
  9456. __decorate([
  9457. BABYLON.serialize()
  9458. ], Node.prototype, "metadata", void 0);
  9459. BABYLON.Node = Node;
  9460. })(BABYLON || (BABYLON = {}));
  9461. //# sourceMappingURL=babylon.node.js.map
  9462. var BABYLON;
  9463. (function (BABYLON) {
  9464. var FilesInput = (function () {
  9465. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9466. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9467. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9468. this._engine = p_engine;
  9469. this._canvas = p_canvas;
  9470. this._currentScene = p_scene;
  9471. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9472. this._progressCallback = p_progressCallback;
  9473. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9474. this._textureLoadingCallback = p_textureLoadingCallback;
  9475. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9476. }
  9477. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9478. var _this = this;
  9479. if (p_elementToMonitor) {
  9480. this._elementToMonitor = p_elementToMonitor;
  9481. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9482. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9483. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9484. }
  9485. };
  9486. FilesInput.prototype.renderFunction = function () {
  9487. if (this._additionnalRenderLoopLogicCallback) {
  9488. this._additionnalRenderLoopLogicCallback();
  9489. }
  9490. if (this._currentScene) {
  9491. if (this._textureLoadingCallback) {
  9492. var remaining = this._currentScene.getWaitingItemsCount();
  9493. if (remaining > 0) {
  9494. this._textureLoadingCallback(remaining);
  9495. }
  9496. }
  9497. this._currentScene.render();
  9498. }
  9499. };
  9500. FilesInput.prototype.drag = function (e) {
  9501. e.stopPropagation();
  9502. e.preventDefault();
  9503. };
  9504. FilesInput.prototype.drop = function (eventDrop) {
  9505. eventDrop.stopPropagation();
  9506. eventDrop.preventDefault();
  9507. this.loadFiles(eventDrop);
  9508. };
  9509. FilesInput.prototype.loadFiles = function (event) {
  9510. if (this._startingProcessingFilesCallback)
  9511. this._startingProcessingFilesCallback();
  9512. // Handling data transfer via drag'n'drop
  9513. if (event && event.dataTransfer && event.dataTransfer.files) {
  9514. this._filesToLoad = event.dataTransfer.files;
  9515. }
  9516. // Handling files from input files
  9517. if (event && event.target && event.target.files) {
  9518. this._filesToLoad = event.target.files;
  9519. }
  9520. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9521. for (var i = 0; i < this._filesToLoad.length; i++) {
  9522. switch (this._filesToLoad[i].type) {
  9523. case "image/jpeg":
  9524. case "image/png":
  9525. case "image/bmp":
  9526. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9527. break;
  9528. case "image/targa":
  9529. case "image/vnd.ms-dds":
  9530. case "audio/wav":
  9531. case "audio/x-wav":
  9532. case "audio/mp3":
  9533. case "audio/mpeg":
  9534. case "audio/mpeg3":
  9535. case "audio/x-mpeg-3":
  9536. case "audio/ogg":
  9537. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9538. break;
  9539. default:
  9540. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9541. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9542. }
  9543. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9544. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9545. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9546. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9547. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9548. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9549. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9550. this._sceneFileToLoad = this._filesToLoad[i];
  9551. }
  9552. break;
  9553. }
  9554. }
  9555. this.reload();
  9556. }
  9557. };
  9558. FilesInput.prototype.reload = function () {
  9559. var _this = this;
  9560. var that = this;
  9561. // If a ".babylon" file has been provided
  9562. if (this._sceneFileToLoad) {
  9563. if (this._currentScene) {
  9564. if (BABYLON.Tools.errorsCount > 0) {
  9565. BABYLON.Tools.ClearLogCache();
  9566. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9567. }
  9568. this._engine.stopRenderLoop();
  9569. this._currentScene.dispose();
  9570. }
  9571. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9572. that._currentScene = newScene;
  9573. // Wait for textures and shaders to be ready
  9574. that._currentScene.executeWhenReady(function () {
  9575. // Attach camera to canvas inputs
  9576. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9577. that._currentScene.createDefaultCameraOrLight();
  9578. }
  9579. that._currentScene.activeCamera.attachControl(that._canvas);
  9580. if (that._sceneLoadedCallback) {
  9581. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9582. }
  9583. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9584. });
  9585. }, function (progress) {
  9586. if (_this._progressCallback) {
  9587. _this._progressCallback(progress);
  9588. }
  9589. });
  9590. }
  9591. else {
  9592. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9593. }
  9594. };
  9595. return FilesInput;
  9596. }());
  9597. FilesInput.FilesTextures = new Array();
  9598. FilesInput.FilesToLoad = new Array();
  9599. BABYLON.FilesInput = FilesInput;
  9600. })(BABYLON || (BABYLON = {}));
  9601. //# sourceMappingURL=babylon.filesInput.js.map
  9602. var BABYLON;
  9603. (function (BABYLON) {
  9604. var IntersectionInfo = (function () {
  9605. function IntersectionInfo(bu, bv, distance) {
  9606. this.bu = bu;
  9607. this.bv = bv;
  9608. this.distance = distance;
  9609. this.faceId = 0;
  9610. this.subMeshId = 0;
  9611. }
  9612. return IntersectionInfo;
  9613. }());
  9614. BABYLON.IntersectionInfo = IntersectionInfo;
  9615. var PickingInfo = (function () {
  9616. function PickingInfo() {
  9617. this.hit = false;
  9618. this.distance = 0;
  9619. this.pickedPoint = null;
  9620. this.pickedMesh = null;
  9621. this.bu = 0;
  9622. this.bv = 0;
  9623. this.faceId = -1;
  9624. this.subMeshId = 0;
  9625. this.pickedSprite = null;
  9626. }
  9627. // Methods
  9628. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9629. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9630. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9631. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9632. return null;
  9633. }
  9634. var indices = this.pickedMesh.getIndices();
  9635. var result;
  9636. if (useVerticesNormals) {
  9637. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9638. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9639. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9640. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9641. normal0 = normal0.scale(this.bu);
  9642. normal1 = normal1.scale(this.bv);
  9643. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9644. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9645. }
  9646. else {
  9647. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9648. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9649. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9650. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9651. var p1p2 = vertex1.subtract(vertex2);
  9652. var p3p2 = vertex3.subtract(vertex2);
  9653. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9654. }
  9655. if (useWorldCoordinates) {
  9656. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9657. }
  9658. return BABYLON.Vector3.Normalize(result);
  9659. };
  9660. PickingInfo.prototype.getTextureCoordinates = function () {
  9661. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9662. return null;
  9663. }
  9664. var indices = this.pickedMesh.getIndices();
  9665. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9666. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9667. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9668. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9669. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9670. uv1 = uv1.scale(this.bu);
  9671. uv2 = uv2.scale(this.bv);
  9672. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9673. };
  9674. return PickingInfo;
  9675. }());
  9676. BABYLON.PickingInfo = PickingInfo;
  9677. })(BABYLON || (BABYLON = {}));
  9678. //# sourceMappingURL=babylon.pickingInfo.js.map
  9679. var BABYLON;
  9680. (function (BABYLON) {
  9681. var BoundingSphere = (function () {
  9682. function BoundingSphere(minimum, maximum) {
  9683. this.minimum = minimum;
  9684. this.maximum = maximum;
  9685. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9686. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9687. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9688. this.radius = distance * 0.5;
  9689. this.centerWorld = BABYLON.Vector3.Zero();
  9690. this._update(BABYLON.Matrix.Identity());
  9691. }
  9692. // Methods
  9693. BoundingSphere.prototype._update = function (world) {
  9694. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9695. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9696. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9697. };
  9698. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9699. for (var i = 0; i < 6; i++) {
  9700. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9701. return false;
  9702. }
  9703. return true;
  9704. };
  9705. BoundingSphere.prototype.intersectsPoint = function (point) {
  9706. var x = this.centerWorld.x - point.x;
  9707. var y = this.centerWorld.y - point.y;
  9708. var z = this.centerWorld.z - point.z;
  9709. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9710. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9711. return false;
  9712. return true;
  9713. };
  9714. // Statics
  9715. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9716. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9717. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9718. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9719. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9720. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9721. return false;
  9722. return true;
  9723. };
  9724. return BoundingSphere;
  9725. }());
  9726. BABYLON.BoundingSphere = BoundingSphere;
  9727. })(BABYLON || (BABYLON = {}));
  9728. //# sourceMappingURL=babylon.boundingSphere.js.map
  9729. var BABYLON;
  9730. (function (BABYLON) {
  9731. var BoundingBox = (function () {
  9732. function BoundingBox(minimum, maximum) {
  9733. this.minimum = minimum;
  9734. this.maximum = maximum;
  9735. this.vectors = new Array();
  9736. this.vectorsWorld = new Array();
  9737. // Bounding vectors
  9738. this.vectors.push(this.minimum.clone());
  9739. this.vectors.push(this.maximum.clone());
  9740. this.vectors.push(this.minimum.clone());
  9741. this.vectors[2].x = this.maximum.x;
  9742. this.vectors.push(this.minimum.clone());
  9743. this.vectors[3].y = this.maximum.y;
  9744. this.vectors.push(this.minimum.clone());
  9745. this.vectors[4].z = this.maximum.z;
  9746. this.vectors.push(this.maximum.clone());
  9747. this.vectors[5].z = this.minimum.z;
  9748. this.vectors.push(this.maximum.clone());
  9749. this.vectors[6].x = this.minimum.x;
  9750. this.vectors.push(this.maximum.clone());
  9751. this.vectors[7].y = this.minimum.y;
  9752. // OBB
  9753. this.center = this.maximum.add(this.minimum).scale(0.5);
  9754. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9755. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9756. // World
  9757. for (var index = 0; index < this.vectors.length; index++) {
  9758. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9759. }
  9760. this.minimumWorld = BABYLON.Vector3.Zero();
  9761. this.maximumWorld = BABYLON.Vector3.Zero();
  9762. this._update(BABYLON.Matrix.Identity());
  9763. }
  9764. // Methods
  9765. BoundingBox.prototype.getWorldMatrix = function () {
  9766. return this._worldMatrix;
  9767. };
  9768. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9769. this._worldMatrix.copyFrom(matrix);
  9770. return this;
  9771. };
  9772. BoundingBox.prototype._update = function (world) {
  9773. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9774. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9775. for (var index = 0; index < this.vectors.length; index++) {
  9776. var v = this.vectorsWorld[index];
  9777. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9778. if (v.x < this.minimumWorld.x)
  9779. this.minimumWorld.x = v.x;
  9780. if (v.y < this.minimumWorld.y)
  9781. this.minimumWorld.y = v.y;
  9782. if (v.z < this.minimumWorld.z)
  9783. this.minimumWorld.z = v.z;
  9784. if (v.x > this.maximumWorld.x)
  9785. this.maximumWorld.x = v.x;
  9786. if (v.y > this.maximumWorld.y)
  9787. this.maximumWorld.y = v.y;
  9788. if (v.z > this.maximumWorld.z)
  9789. this.maximumWorld.z = v.z;
  9790. }
  9791. // OBB
  9792. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9793. this.center.scaleInPlace(0.5);
  9794. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9795. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9796. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9797. this._worldMatrix = world;
  9798. };
  9799. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9800. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9801. };
  9802. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9803. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9804. };
  9805. BoundingBox.prototype.intersectsPoint = function (point) {
  9806. var delta = -BABYLON.Epsilon;
  9807. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9808. return false;
  9809. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9810. return false;
  9811. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9812. return false;
  9813. return true;
  9814. };
  9815. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9816. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9817. };
  9818. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9819. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9820. return false;
  9821. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9822. return false;
  9823. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9824. return false;
  9825. return true;
  9826. };
  9827. // Statics
  9828. BoundingBox.Intersects = function (box0, box1) {
  9829. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9830. return false;
  9831. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9832. return false;
  9833. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9834. return false;
  9835. return true;
  9836. };
  9837. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9838. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9839. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9840. return (num <= (sphereRadius * sphereRadius));
  9841. };
  9842. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9843. for (var p = 0; p < 6; p++) {
  9844. for (var i = 0; i < 8; i++) {
  9845. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9846. return false;
  9847. }
  9848. }
  9849. }
  9850. return true;
  9851. };
  9852. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9853. for (var p = 0; p < 6; p++) {
  9854. var inCount = 8;
  9855. for (var i = 0; i < 8; i++) {
  9856. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9857. --inCount;
  9858. }
  9859. else {
  9860. break;
  9861. }
  9862. }
  9863. if (inCount === 0)
  9864. return false;
  9865. }
  9866. return true;
  9867. };
  9868. return BoundingBox;
  9869. }());
  9870. BABYLON.BoundingBox = BoundingBox;
  9871. })(BABYLON || (BABYLON = {}));
  9872. //# sourceMappingURL=babylon.boundingBox.js.map
  9873. var BABYLON;
  9874. (function (BABYLON) {
  9875. var computeBoxExtents = function (axis, box) {
  9876. var p = BABYLON.Vector3.Dot(box.center, axis);
  9877. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9878. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9879. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9880. var r = r0 + r1 + r2;
  9881. return {
  9882. min: p - r,
  9883. max: p + r
  9884. };
  9885. };
  9886. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9887. var axisOverlap = function (axis, box0, box1) {
  9888. var result0 = computeBoxExtents(axis, box0);
  9889. var result1 = computeBoxExtents(axis, box1);
  9890. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9891. };
  9892. var BoundingInfo = (function () {
  9893. function BoundingInfo(minimum, maximum) {
  9894. this.minimum = minimum;
  9895. this.maximum = maximum;
  9896. this._isLocked = false;
  9897. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9898. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9899. }
  9900. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9901. get: function () {
  9902. return this._isLocked;
  9903. },
  9904. set: function (value) {
  9905. this._isLocked = value;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. // Methods
  9911. BoundingInfo.prototype.update = function (world) {
  9912. if (this._isLocked) {
  9913. return;
  9914. }
  9915. this.boundingBox._update(world);
  9916. this.boundingSphere._update(world);
  9917. };
  9918. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9919. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9920. return false;
  9921. return this.boundingBox.isInFrustum(frustumPlanes);
  9922. };
  9923. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9924. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9925. };
  9926. BoundingInfo.prototype._checkCollision = function (collider) {
  9927. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9928. };
  9929. BoundingInfo.prototype.intersectsPoint = function (point) {
  9930. if (!this.boundingSphere.centerWorld) {
  9931. return false;
  9932. }
  9933. if (!this.boundingSphere.intersectsPoint(point)) {
  9934. return false;
  9935. }
  9936. if (!this.boundingBox.intersectsPoint(point)) {
  9937. return false;
  9938. }
  9939. return true;
  9940. };
  9941. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9942. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9943. return false;
  9944. }
  9945. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9946. return false;
  9947. }
  9948. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9949. return false;
  9950. }
  9951. if (!precise) {
  9952. return true;
  9953. }
  9954. var box0 = this.boundingBox;
  9955. var box1 = boundingInfo.boundingBox;
  9956. if (!axisOverlap(box0.directions[0], box0, box1))
  9957. return false;
  9958. if (!axisOverlap(box0.directions[1], box0, box1))
  9959. return false;
  9960. if (!axisOverlap(box0.directions[2], box0, box1))
  9961. return false;
  9962. if (!axisOverlap(box1.directions[0], box0, box1))
  9963. return false;
  9964. if (!axisOverlap(box1.directions[1], box0, box1))
  9965. return false;
  9966. if (!axisOverlap(box1.directions[2], box0, box1))
  9967. return false;
  9968. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9969. return false;
  9970. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9971. return false;
  9972. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9973. return false;
  9974. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9975. return false;
  9976. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9977. return false;
  9978. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9979. return false;
  9980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9981. return false;
  9982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9983. return false;
  9984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9985. return false;
  9986. return true;
  9987. };
  9988. return BoundingInfo;
  9989. }());
  9990. BABYLON.BoundingInfo = BoundingInfo;
  9991. })(BABYLON || (BABYLON = {}));
  9992. //# sourceMappingURL=babylon.boundingInfo.js.map
  9993. var BABYLON;
  9994. (function (BABYLON) {
  9995. var Ray = (function () {
  9996. function Ray(origin, direction, length) {
  9997. if (length === void 0) { length = Number.MAX_VALUE; }
  9998. this.origin = origin;
  9999. this.direction = direction;
  10000. this.length = length;
  10001. this._show = false;
  10002. }
  10003. // Methods
  10004. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10005. var d = 0.0;
  10006. var maxValue = Number.MAX_VALUE;
  10007. var inv;
  10008. var min;
  10009. var max;
  10010. var temp;
  10011. if (Math.abs(this.direction.x) < 0.0000001) {
  10012. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10013. return false;
  10014. }
  10015. }
  10016. else {
  10017. inv = 1.0 / this.direction.x;
  10018. min = (minimum.x - this.origin.x) * inv;
  10019. max = (maximum.x - this.origin.x) * inv;
  10020. if (max === -Infinity) {
  10021. max = Infinity;
  10022. }
  10023. if (min > max) {
  10024. temp = min;
  10025. min = max;
  10026. max = temp;
  10027. }
  10028. d = Math.max(min, d);
  10029. maxValue = Math.min(max, maxValue);
  10030. if (d > maxValue) {
  10031. return false;
  10032. }
  10033. }
  10034. if (Math.abs(this.direction.y) < 0.0000001) {
  10035. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10036. return false;
  10037. }
  10038. }
  10039. else {
  10040. inv = 1.0 / this.direction.y;
  10041. min = (minimum.y - this.origin.y) * inv;
  10042. max = (maximum.y - this.origin.y) * inv;
  10043. if (max === -Infinity) {
  10044. max = Infinity;
  10045. }
  10046. if (min > max) {
  10047. temp = min;
  10048. min = max;
  10049. max = temp;
  10050. }
  10051. d = Math.max(min, d);
  10052. maxValue = Math.min(max, maxValue);
  10053. if (d > maxValue) {
  10054. return false;
  10055. }
  10056. }
  10057. if (Math.abs(this.direction.z) < 0.0000001) {
  10058. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10059. return false;
  10060. }
  10061. }
  10062. else {
  10063. inv = 1.0 / this.direction.z;
  10064. min = (minimum.z - this.origin.z) * inv;
  10065. max = (maximum.z - this.origin.z) * inv;
  10066. if (max === -Infinity) {
  10067. max = Infinity;
  10068. }
  10069. if (min > max) {
  10070. temp = min;
  10071. min = max;
  10072. max = temp;
  10073. }
  10074. d = Math.max(min, d);
  10075. maxValue = Math.min(max, maxValue);
  10076. if (d > maxValue) {
  10077. return false;
  10078. }
  10079. }
  10080. return true;
  10081. };
  10082. Ray.prototype.intersectsBox = function (box) {
  10083. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10084. };
  10085. Ray.prototype.intersectsSphere = function (sphere) {
  10086. var x = sphere.center.x - this.origin.x;
  10087. var y = sphere.center.y - this.origin.y;
  10088. var z = sphere.center.z - this.origin.z;
  10089. var pyth = (x * x) + (y * y) + (z * z);
  10090. var rr = sphere.radius * sphere.radius;
  10091. if (pyth <= rr) {
  10092. return true;
  10093. }
  10094. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10095. if (dot < 0.0) {
  10096. return false;
  10097. }
  10098. var temp = pyth - (dot * dot);
  10099. return temp <= rr;
  10100. };
  10101. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10102. if (!this._edge1) {
  10103. this._edge1 = BABYLON.Vector3.Zero();
  10104. this._edge2 = BABYLON.Vector3.Zero();
  10105. this._pvec = BABYLON.Vector3.Zero();
  10106. this._tvec = BABYLON.Vector3.Zero();
  10107. this._qvec = BABYLON.Vector3.Zero();
  10108. }
  10109. vertex1.subtractToRef(vertex0, this._edge1);
  10110. vertex2.subtractToRef(vertex0, this._edge2);
  10111. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10112. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10113. if (det === 0) {
  10114. return null;
  10115. }
  10116. var invdet = 1 / det;
  10117. this.origin.subtractToRef(vertex0, this._tvec);
  10118. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10119. if (bu < 0 || bu > 1.0) {
  10120. return null;
  10121. }
  10122. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10123. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10124. if (bv < 0 || bu + bv > 1.0) {
  10125. return null;
  10126. }
  10127. //check if the distance is longer than the predefined length.
  10128. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10129. if (distance > this.length) {
  10130. return null;
  10131. }
  10132. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10133. };
  10134. Ray.prototype.intersectsPlane = function (plane) {
  10135. var distance;
  10136. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10137. if (Math.abs(result1) < 9.99999997475243E-07) {
  10138. return null;
  10139. }
  10140. else {
  10141. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10142. distance = (-plane.d - result2) / result1;
  10143. if (distance < 0.0) {
  10144. if (distance < -9.99999997475243E-07) {
  10145. return null;
  10146. }
  10147. else {
  10148. return 0;
  10149. }
  10150. }
  10151. return distance;
  10152. }
  10153. };
  10154. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10155. var tm = BABYLON.Tmp.Matrix[0];
  10156. mesh.getWorldMatrix().invertToRef(tm);
  10157. if (this._tmpRay) {
  10158. Ray.TransformToRef(this, tm, this._tmpRay);
  10159. }
  10160. else {
  10161. this._tmpRay = Ray.Transform(this, tm);
  10162. }
  10163. return mesh.intersects(this._tmpRay, fastCheck);
  10164. };
  10165. Ray.prototype.show = function (scene, color) {
  10166. if (!this._show) {
  10167. this._renderFunction = this._render.bind(this);
  10168. this._show = true;
  10169. this._scene = scene;
  10170. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10171. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10172. this._scene.registerBeforeRender(this._renderFunction);
  10173. }
  10174. if (color) {
  10175. this._renderLine.color.copyFrom(color);
  10176. }
  10177. };
  10178. Ray.prototype.hide = function () {
  10179. if (this._show) {
  10180. this._show = false;
  10181. this._scene.unregisterBeforeRender(this._renderFunction);
  10182. }
  10183. if (this._renderLine) {
  10184. this._renderLine.dispose();
  10185. this._renderLine = null;
  10186. this._renderPoints = null;
  10187. }
  10188. };
  10189. Ray.prototype._render = function () {
  10190. var point = this._renderPoints[1];
  10191. point.copyFrom(this.direction);
  10192. point.scaleInPlace(this.length);
  10193. point.addInPlace(this.origin);
  10194. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10195. };
  10196. /**
  10197. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10198. * @param sega the first point of the segment to test the intersection against
  10199. * @param segb the second point of the segment to test the intersection against
  10200. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10201. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10202. */
  10203. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10204. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10205. var u = segb.subtract(sega);
  10206. var v = rsegb.subtract(this.origin);
  10207. var w = sega.subtract(this.origin);
  10208. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10209. var b = BABYLON.Vector3.Dot(u, v);
  10210. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10211. var d = BABYLON.Vector3.Dot(u, w);
  10212. var e = BABYLON.Vector3.Dot(v, w);
  10213. var D = a * c - b * b; // always >= 0
  10214. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10215. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10216. // compute the line parameters of the two closest points
  10217. if (D < Ray.smallnum) {
  10218. sN = 0.0; // force using point P0 on segment S1
  10219. sD = 1.0; // to prevent possible division by 0.0 later
  10220. tN = e;
  10221. tD = c;
  10222. }
  10223. else {
  10224. sN = (b * e - c * d);
  10225. tN = (a * e - b * d);
  10226. if (sN < 0.0) {
  10227. sN = 0.0;
  10228. tN = e;
  10229. tD = c;
  10230. }
  10231. else if (sN > sD) {
  10232. sN = sD;
  10233. tN = e + b;
  10234. tD = c;
  10235. }
  10236. }
  10237. if (tN < 0.0) {
  10238. tN = 0.0;
  10239. // recompute sc for this edge
  10240. if (-d < 0.0) {
  10241. sN = 0.0;
  10242. }
  10243. else if (-d > a)
  10244. sN = sD;
  10245. else {
  10246. sN = -d;
  10247. sD = a;
  10248. }
  10249. }
  10250. else if (tN > tD) {
  10251. tN = tD;
  10252. // recompute sc for this edge
  10253. if ((-d + b) < 0.0) {
  10254. sN = 0;
  10255. }
  10256. else if ((-d + b) > a) {
  10257. sN = sD;
  10258. }
  10259. else {
  10260. sN = (-d + b);
  10261. sD = a;
  10262. }
  10263. }
  10264. // finally do the division to get sc and tc
  10265. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10266. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10267. // get the difference of the two closest points
  10268. var qtc = v.multiplyByFloats(tc, tc, tc);
  10269. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10270. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10271. if (isIntersected) {
  10272. return qtc.length();
  10273. }
  10274. return -1;
  10275. };
  10276. // Statics
  10277. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10278. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10279. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10280. var direction = end.subtract(start);
  10281. direction.normalize();
  10282. return new Ray(start, direction);
  10283. };
  10284. /**
  10285. * 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
  10286. * transformed to the given world matrix.
  10287. * @param origin The origin point
  10288. * @param end The end point
  10289. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10290. */
  10291. Ray.CreateNewFromTo = function (origin, end, world) {
  10292. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10293. var direction = end.subtract(origin);
  10294. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10295. direction.normalize();
  10296. return Ray.Transform(new Ray(origin, direction, length), world);
  10297. };
  10298. Ray.Transform = function (ray, matrix) {
  10299. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10300. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10301. newDirection.normalize();
  10302. return new Ray(newOrigin, newDirection, ray.length);
  10303. };
  10304. Ray.TransformToRef = function (ray, matrix, result) {
  10305. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10306. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10307. ray.direction.normalize();
  10308. };
  10309. return Ray;
  10310. }());
  10311. Ray.smallnum = 0.00000001;
  10312. Ray.rayl = 10e8;
  10313. BABYLON.Ray = Ray;
  10314. })(BABYLON || (BABYLON = {}));
  10315. //# sourceMappingURL=babylon.ray.js.map
  10316. var BABYLON;
  10317. (function (BABYLON) {
  10318. var AbstractMesh = (function (_super) {
  10319. __extends(AbstractMesh, _super);
  10320. // Constructor
  10321. function AbstractMesh(name, scene) {
  10322. var _this = _super.call(this, name, scene) || this;
  10323. // Events
  10324. /**
  10325. * An event triggered when this mesh collides with another one
  10326. * @type {BABYLON.Observable}
  10327. */
  10328. _this.onCollideObservable = new BABYLON.Observable();
  10329. /**
  10330. * An event triggered when the collision's position changes
  10331. * @type {BABYLON.Observable}
  10332. */
  10333. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10334. /**
  10335. * An event triggered after the world matrix is updated
  10336. * @type {BABYLON.Observable}
  10337. */
  10338. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10339. // Properties
  10340. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10341. _this.position = new BABYLON.Vector3(0, 0, 0);
  10342. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10343. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10344. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10345. _this.visibility = 1.0;
  10346. _this.alphaIndex = Number.MAX_VALUE;
  10347. _this.infiniteDistance = false;
  10348. _this.isVisible = true;
  10349. _this.isPickable = true;
  10350. _this.showBoundingBox = false;
  10351. _this.showSubMeshesBoundingBox = false;
  10352. _this.isBlocker = false;
  10353. _this.renderingGroupId = 0;
  10354. _this.receiveShadows = false;
  10355. _this.renderOutline = false;
  10356. _this.outlineColor = BABYLON.Color3.Red();
  10357. _this.outlineWidth = 0.02;
  10358. _this.renderOverlay = false;
  10359. _this.overlayColor = BABYLON.Color3.Red();
  10360. _this.overlayAlpha = 0.5;
  10361. _this.hasVertexAlpha = false;
  10362. _this.useVertexColors = true;
  10363. _this.applyFog = true;
  10364. _this.computeBonesUsingShaders = true;
  10365. _this.scalingDeterminant = 1;
  10366. _this.numBoneInfluencers = 4;
  10367. _this.useOctreeForRenderingSelection = true;
  10368. _this.useOctreeForPicking = true;
  10369. _this.useOctreeForCollisions = true;
  10370. _this.layerMask = 0x0FFFFFFF;
  10371. _this.alwaysSelectAsActiveMesh = false;
  10372. // Collisions
  10373. _this._checkCollisions = false;
  10374. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10375. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10376. _this._collider = new BABYLON.Collider();
  10377. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10378. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10379. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10380. // Edges
  10381. _this.edgesWidth = 1;
  10382. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10383. // Cache
  10384. _this._localWorld = BABYLON.Matrix.Zero();
  10385. _this._worldMatrix = BABYLON.Matrix.Zero();
  10386. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10387. _this._absolutePosition = BABYLON.Vector3.Zero();
  10388. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10389. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10390. _this._isDirty = false;
  10391. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10392. _this._isDisposed = false;
  10393. _this._renderId = 0;
  10394. _this._intersectionsInProgress = new Array();
  10395. _this._isWorldMatrixFrozen = false;
  10396. _this._unIndexed = false;
  10397. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10398. if (collidedMesh === void 0) { collidedMesh = null; }
  10399. //TODO move this to the collision coordinator!
  10400. if (_this.getScene().workerCollisions)
  10401. newPosition.multiplyInPlace(_this._collider.radius);
  10402. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10403. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10404. _this.position.addInPlace(_this._diffPositionForCollisions);
  10405. }
  10406. if (collidedMesh) {
  10407. _this.onCollideObservable.notifyObservers(collidedMesh);
  10408. }
  10409. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10410. };
  10411. scene.addMesh(_this);
  10412. return _this;
  10413. }
  10414. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10415. get: function () {
  10416. return AbstractMesh._BILLBOARDMODE_NONE;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10422. get: function () {
  10423. return AbstractMesh._BILLBOARDMODE_X;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10429. get: function () {
  10430. return AbstractMesh._BILLBOARDMODE_Y;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10436. get: function () {
  10437. return AbstractMesh._BILLBOARDMODE_Z;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10443. get: function () {
  10444. return AbstractMesh._BILLBOARDMODE_ALL;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10450. set: function (callback) {
  10451. if (this._onCollideObserver) {
  10452. this.onCollideObservable.remove(this._onCollideObserver);
  10453. }
  10454. this._onCollideObserver = this.onCollideObservable.add(callback);
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10460. set: function (callback) {
  10461. if (this._onCollisionPositionChangeObserver) {
  10462. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10463. }
  10464. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10465. },
  10466. enumerable: true,
  10467. configurable: true
  10468. });
  10469. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10470. get: function () {
  10471. return this._skeleton;
  10472. },
  10473. set: function (value) {
  10474. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10475. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10476. }
  10477. if (value && value.needInitialSkinMatrix) {
  10478. value._registerMeshWithPoseMatrix(this);
  10479. }
  10480. this._skeleton = value;
  10481. if (!this._skeleton) {
  10482. this._bonesTransformMatrices = null;
  10483. }
  10484. },
  10485. enumerable: true,
  10486. configurable: true
  10487. });
  10488. AbstractMesh.prototype.getClassName = function () {
  10489. return "AbstractMesh";
  10490. };
  10491. /**
  10492. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10493. */
  10494. AbstractMesh.prototype.toString = function (fullDetails) {
  10495. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10496. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10497. if (this._skeleton) {
  10498. ret += ", skeleton: " + this._skeleton.name;
  10499. }
  10500. if (fullDetails) {
  10501. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10502. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10503. }
  10504. return ret;
  10505. };
  10506. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10507. /**
  10508. * Getting the rotation object.
  10509. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10510. */
  10511. get: function () {
  10512. return this._rotation;
  10513. },
  10514. set: function (newRotation) {
  10515. this._rotation = newRotation;
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10521. get: function () {
  10522. return this._scaling;
  10523. },
  10524. set: function (newScaling) {
  10525. this._scaling = newScaling;
  10526. if (this.physicsImpostor) {
  10527. this.physicsImpostor.forceUpdate();
  10528. }
  10529. },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10534. get: function () {
  10535. return this._rotationQuaternion;
  10536. },
  10537. set: function (quaternion) {
  10538. this._rotationQuaternion = quaternion;
  10539. //reset the rotation vector.
  10540. if (quaternion && this.rotation.length()) {
  10541. this.rotation.copyFromFloats(0, 0, 0);
  10542. }
  10543. },
  10544. enumerable: true,
  10545. configurable: true
  10546. });
  10547. // Methods
  10548. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10549. this._poseMatrix.copyFrom(matrix);
  10550. };
  10551. AbstractMesh.prototype.getPoseMatrix = function () {
  10552. return this._poseMatrix;
  10553. };
  10554. AbstractMesh.prototype.disableEdgesRendering = function () {
  10555. if (this._edgesRenderer !== undefined) {
  10556. this._edgesRenderer.dispose();
  10557. this._edgesRenderer = undefined;
  10558. }
  10559. };
  10560. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10561. if (epsilon === void 0) { epsilon = 0.95; }
  10562. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10563. this.disableEdgesRendering();
  10564. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10565. };
  10566. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10567. get: function () {
  10568. return false;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. AbstractMesh.prototype.getLOD = function (camera) {
  10574. return this;
  10575. };
  10576. AbstractMesh.prototype.getTotalVertices = function () {
  10577. return 0;
  10578. };
  10579. AbstractMesh.prototype.getIndices = function () {
  10580. return null;
  10581. };
  10582. AbstractMesh.prototype.getVerticesData = function (kind) {
  10583. return null;
  10584. };
  10585. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10586. return false;
  10587. };
  10588. AbstractMesh.prototype.getBoundingInfo = function () {
  10589. if (this._masterMesh) {
  10590. return this._masterMesh.getBoundingInfo();
  10591. }
  10592. if (!this._boundingInfo) {
  10593. this._updateBoundingInfo();
  10594. }
  10595. return this._boundingInfo;
  10596. };
  10597. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10598. this._boundingInfo = boundingInfo;
  10599. };
  10600. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10601. get: function () {
  10602. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. AbstractMesh.prototype._preActivate = function () {
  10608. };
  10609. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10610. };
  10611. AbstractMesh.prototype._activate = function (renderId) {
  10612. this._renderId = renderId;
  10613. };
  10614. AbstractMesh.prototype.getWorldMatrix = function () {
  10615. if (this._masterMesh) {
  10616. return this._masterMesh.getWorldMatrix();
  10617. }
  10618. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10619. this.computeWorldMatrix();
  10620. }
  10621. return this._worldMatrix;
  10622. };
  10623. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10624. get: function () {
  10625. return this._worldMatrix;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10631. get: function () {
  10632. return this._absolutePosition;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10638. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10639. this.computeWorldMatrix(true);
  10640. this._isWorldMatrixFrozen = true;
  10641. };
  10642. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10643. this._isWorldMatrixFrozen = false;
  10644. this.computeWorldMatrix(true);
  10645. };
  10646. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10647. get: function () {
  10648. return this._isWorldMatrixFrozen;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10654. axis.normalize();
  10655. if (!this.rotationQuaternion) {
  10656. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10657. this.rotation = BABYLON.Vector3.Zero();
  10658. }
  10659. var rotationQuaternion;
  10660. if (!space || space === BABYLON.Space.LOCAL) {
  10661. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10662. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10663. }
  10664. else {
  10665. if (this.parent) {
  10666. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10667. invertParentWorldMatrix.invert();
  10668. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10669. }
  10670. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10671. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10672. }
  10673. };
  10674. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10675. var displacementVector = axis.scale(distance);
  10676. if (!space || space === BABYLON.Space.LOCAL) {
  10677. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10678. this.setPositionWithLocalVector(tempV3);
  10679. }
  10680. else {
  10681. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10682. }
  10683. };
  10684. AbstractMesh.prototype.getAbsolutePosition = function () {
  10685. this.computeWorldMatrix();
  10686. return this._absolutePosition;
  10687. };
  10688. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10689. if (!absolutePosition) {
  10690. return;
  10691. }
  10692. var absolutePositionX;
  10693. var absolutePositionY;
  10694. var absolutePositionZ;
  10695. if (absolutePosition.x === undefined) {
  10696. if (arguments.length < 3) {
  10697. return;
  10698. }
  10699. absolutePositionX = arguments[0];
  10700. absolutePositionY = arguments[1];
  10701. absolutePositionZ = arguments[2];
  10702. }
  10703. else {
  10704. absolutePositionX = absolutePosition.x;
  10705. absolutePositionY = absolutePosition.y;
  10706. absolutePositionZ = absolutePosition.z;
  10707. }
  10708. if (this.parent) {
  10709. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10710. invertParentWorldMatrix.invert();
  10711. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10712. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10713. }
  10714. else {
  10715. this.position.x = absolutePositionX;
  10716. this.position.y = absolutePositionY;
  10717. this.position.z = absolutePositionZ;
  10718. }
  10719. };
  10720. // ================================== Point of View Movement =================================
  10721. /**
  10722. * Perform relative position change from the point of view of behind the front of the mesh.
  10723. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10724. * Supports definition of mesh facing forward or backward.
  10725. * @param {number} amountRight
  10726. * @param {number} amountUp
  10727. * @param {number} amountForward
  10728. */
  10729. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10730. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10731. };
  10732. /**
  10733. * Calculate relative position change from the point of view of behind the front of the mesh.
  10734. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10735. * Supports definition of mesh facing forward or backward.
  10736. * @param {number} amountRight
  10737. * @param {number} amountUp
  10738. * @param {number} amountForward
  10739. */
  10740. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10741. var rotMatrix = new BABYLON.Matrix();
  10742. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10743. rotQuaternion.toRotationMatrix(rotMatrix);
  10744. var translationDelta = BABYLON.Vector3.Zero();
  10745. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10747. return translationDelta;
  10748. };
  10749. // ================================== Point of View Rotation =================================
  10750. /**
  10751. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10752. * Supports definition of mesh facing forward or backward.
  10753. * @param {number} flipBack
  10754. * @param {number} twirlClockwise
  10755. * @param {number} tiltRight
  10756. */
  10757. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10758. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10759. };
  10760. /**
  10761. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10762. * Supports definition of mesh facing forward or backward.
  10763. * @param {number} flipBack
  10764. * @param {number} twirlClockwise
  10765. * @param {number} tiltRight
  10766. */
  10767. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10768. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10769. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10770. };
  10771. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10772. this._pivotMatrix = matrix;
  10773. this._cache.pivotMatrixUpdated = true;
  10774. };
  10775. AbstractMesh.prototype.getPivotMatrix = function () {
  10776. return this._pivotMatrix;
  10777. };
  10778. AbstractMesh.prototype._isSynchronized = function () {
  10779. if (this._isDirty) {
  10780. return false;
  10781. }
  10782. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10783. return false;
  10784. if (this._cache.pivotMatrixUpdated) {
  10785. return false;
  10786. }
  10787. if (this.infiniteDistance) {
  10788. return false;
  10789. }
  10790. if (!this._cache.position.equals(this.position))
  10791. return false;
  10792. if (this.rotationQuaternion) {
  10793. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10794. return false;
  10795. }
  10796. if (!this._cache.rotation.equals(this.rotation))
  10797. return false;
  10798. if (!this._cache.scaling.equals(this.scaling))
  10799. return false;
  10800. return true;
  10801. };
  10802. AbstractMesh.prototype._initCache = function () {
  10803. _super.prototype._initCache.call(this);
  10804. this._cache.localMatrixUpdated = false;
  10805. this._cache.position = BABYLON.Vector3.Zero();
  10806. this._cache.scaling = BABYLON.Vector3.Zero();
  10807. this._cache.rotation = BABYLON.Vector3.Zero();
  10808. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10809. this._cache.billboardMode = -1;
  10810. };
  10811. AbstractMesh.prototype.markAsDirty = function (property) {
  10812. if (property === "rotation") {
  10813. this.rotationQuaternion = null;
  10814. }
  10815. this._currentRenderId = Number.MAX_VALUE;
  10816. this._isDirty = true;
  10817. };
  10818. AbstractMesh.prototype._updateBoundingInfo = function () {
  10819. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10820. this._boundingInfo.update(this.worldMatrixFromCache);
  10821. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10822. };
  10823. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10824. if (!this.subMeshes) {
  10825. return;
  10826. }
  10827. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10828. var subMesh = this.subMeshes[subIndex];
  10829. if (!subMesh.IsGlobal) {
  10830. subMesh.updateBoundingInfo(matrix);
  10831. }
  10832. }
  10833. };
  10834. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10835. if (this._isWorldMatrixFrozen) {
  10836. return this._worldMatrix;
  10837. }
  10838. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10839. this._currentRenderId = this.getScene().getRenderId();
  10840. return this._worldMatrix;
  10841. }
  10842. this._cache.position.copyFrom(this.position);
  10843. this._cache.scaling.copyFrom(this.scaling);
  10844. this._cache.pivotMatrixUpdated = false;
  10845. this._cache.billboardMode = this.billboardMode;
  10846. this._currentRenderId = this.getScene().getRenderId();
  10847. this._isDirty = false;
  10848. // Scaling
  10849. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10850. // Rotation
  10851. //rotate, if quaternion is set and rotation was used
  10852. if (this.rotationQuaternion) {
  10853. var len = this.rotation.length();
  10854. if (len) {
  10855. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10856. this.rotation.copyFromFloats(0, 0, 0);
  10857. }
  10858. }
  10859. if (this.rotationQuaternion) {
  10860. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10861. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10862. }
  10863. else {
  10864. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10865. this._cache.rotation.copyFrom(this.rotation);
  10866. }
  10867. // Translation
  10868. if (this.infiniteDistance && !this.parent) {
  10869. var camera = this.getScene().activeCamera;
  10870. if (camera) {
  10871. var cameraWorldMatrix = camera.getWorldMatrix();
  10872. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10873. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10874. }
  10875. }
  10876. else {
  10877. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10878. }
  10879. // Composing transformations
  10880. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10881. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10882. // Billboarding
  10883. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10884. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10885. var localPosition = BABYLON.Tmp.Vector3[0];
  10886. if (this.parent && this.parent.getWorldMatrix) {
  10887. this._markSyncedWithParent();
  10888. var parentMatrix;
  10889. if (this._meshToBoneReferal) {
  10890. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10891. parentMatrix = BABYLON.Tmp.Matrix[6];
  10892. }
  10893. else {
  10894. parentMatrix = this.parent.getWorldMatrix();
  10895. }
  10896. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10897. localPosition = BABYLON.Tmp.Vector3[1];
  10898. }
  10899. var zero = this.getScene().activeCamera.globalPosition.clone();
  10900. if (this.parent && this.parent.position) {
  10901. localPosition.addInPlace(this.parent.position);
  10902. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10903. }
  10904. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10905. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10906. zero.x = localPosition.x + BABYLON.Epsilon;
  10907. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10908. zero.y = localPosition.y + BABYLON.Epsilon;
  10909. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10910. zero.z = localPosition.z + BABYLON.Epsilon;
  10911. }
  10912. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10913. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10914. BABYLON.Tmp.Matrix[3].invert();
  10915. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10916. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10917. }
  10918. // Local world
  10919. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10920. // Parent
  10921. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10922. this._markSyncedWithParent();
  10923. if (this._meshToBoneReferal) {
  10924. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10925. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10926. }
  10927. else {
  10928. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10929. }
  10930. }
  10931. else {
  10932. this._worldMatrix.copyFrom(this._localWorld);
  10933. }
  10934. // Bounding info
  10935. this._updateBoundingInfo();
  10936. // Absolute position
  10937. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10938. // Callbacks
  10939. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10940. if (!this._poseMatrix) {
  10941. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10942. }
  10943. return this._worldMatrix;
  10944. };
  10945. /**
  10946. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10947. * @param func: callback function to add
  10948. */
  10949. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10950. this.onAfterWorldMatrixUpdateObservable.add(func);
  10951. };
  10952. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10953. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10954. };
  10955. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10956. this.computeWorldMatrix();
  10957. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10958. };
  10959. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10960. this.computeWorldMatrix();
  10961. var invLocalWorldMatrix = this._localWorld.clone();
  10962. invLocalWorldMatrix.invert();
  10963. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10964. };
  10965. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10966. this.computeWorldMatrix(true);
  10967. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10968. };
  10969. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10970. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10971. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10972. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10973. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10974. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10975. /// <returns>Mesh oriented towards targetMesh</returns>
  10976. if (yawCor === void 0) { yawCor = 0; }
  10977. if (pitchCor === void 0) { pitchCor = 0; }
  10978. if (rollCor === void 0) { rollCor = 0; }
  10979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10980. var dv = AbstractMesh._lookAtVectorCache;
  10981. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10982. targetPoint.subtractToRef(pos, dv);
  10983. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10984. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10985. var pitch = Math.atan2(dv.y, len);
  10986. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10987. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10988. };
  10989. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10990. this._meshToBoneReferal = affectedMesh;
  10991. this.parent = bone;
  10992. if (bone.getWorldMatrix().determinant() < 0) {
  10993. this.scalingDeterminant *= -1;
  10994. }
  10995. };
  10996. AbstractMesh.prototype.detachFromBone = function () {
  10997. if (this.parent.getWorldMatrix().determinant() < 0) {
  10998. this.scalingDeterminant *= -1;
  10999. }
  11000. this._meshToBoneReferal = null;
  11001. this.parent = null;
  11002. };
  11003. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11004. return this._boundingInfo.isInFrustum(frustumPlanes);
  11005. };
  11006. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11007. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11008. ;
  11009. };
  11010. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11011. if (!this._boundingInfo || !mesh._boundingInfo) {
  11012. return false;
  11013. }
  11014. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11015. };
  11016. AbstractMesh.prototype.intersectsPoint = function (point) {
  11017. if (!this._boundingInfo) {
  11018. return false;
  11019. }
  11020. return this._boundingInfo.intersectsPoint(point);
  11021. };
  11022. // Physics
  11023. /**
  11024. * @Deprecated. Use new PhysicsImpostor instead.
  11025. * */
  11026. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11027. //legacy support
  11028. if (impostor.impostor) {
  11029. options = impostor;
  11030. impostor = impostor.impostor;
  11031. }
  11032. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11033. return this.physicsImpostor.physicsBody;
  11034. };
  11035. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11036. return this.physicsImpostor;
  11037. };
  11038. /**
  11039. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11040. */
  11041. AbstractMesh.prototype.getPhysicsMass = function () {
  11042. return this.physicsImpostor.getParam("mass");
  11043. };
  11044. /**
  11045. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11046. */
  11047. AbstractMesh.prototype.getPhysicsFriction = function () {
  11048. return this.physicsImpostor.getParam("friction");
  11049. };
  11050. /**
  11051. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11052. */
  11053. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11054. return this.physicsImpostor.getParam("restitution");
  11055. };
  11056. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11057. if (!camera) {
  11058. camera = this.getScene().activeCamera;
  11059. }
  11060. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11061. };
  11062. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11063. if (!camera) {
  11064. camera = this.getScene().activeCamera;
  11065. }
  11066. return this.absolutePosition.subtract(camera.position).length();
  11067. };
  11068. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11069. if (!this.physicsImpostor) {
  11070. return;
  11071. }
  11072. this.physicsImpostor.applyImpulse(force, contactPoint);
  11073. };
  11074. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11075. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11076. return;
  11077. }
  11078. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11079. mainPivot: pivot1,
  11080. connectedPivot: pivot2,
  11081. nativeParams: options
  11082. });
  11083. };
  11084. /**
  11085. * @Deprecated
  11086. */
  11087. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11088. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11089. this.updatePhysicsBody();
  11090. };
  11091. /**
  11092. * @Deprecated
  11093. * Calling this function is not needed anymore.
  11094. * The physics engine takes care of transofmration automatically.
  11095. */
  11096. AbstractMesh.prototype.updatePhysicsBody = function () {
  11097. //Unneeded
  11098. };
  11099. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11100. // Collisions
  11101. get: function () {
  11102. return this._checkCollisions;
  11103. },
  11104. set: function (collisionEnabled) {
  11105. this._checkCollisions = collisionEnabled;
  11106. if (this.getScene().workerCollisions) {
  11107. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11108. }
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11114. var globalPosition = this.getAbsolutePosition();
  11115. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11116. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11117. this._collider.radius = this.ellipsoid;
  11118. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11119. };
  11120. // Submeshes octree
  11121. /**
  11122. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11123. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11124. */
  11125. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11126. if (maxCapacity === void 0) { maxCapacity = 64; }
  11127. if (maxDepth === void 0) { maxDepth = 2; }
  11128. if (!this._submeshesOctree) {
  11129. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11130. }
  11131. this.computeWorldMatrix(true);
  11132. // Update octree
  11133. var bbox = this.getBoundingInfo().boundingBox;
  11134. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11135. return this._submeshesOctree;
  11136. };
  11137. // Collisions
  11138. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11139. this._generatePointsArray();
  11140. // Transformation
  11141. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11142. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11143. subMesh._lastColliderWorldVertices = [];
  11144. subMesh._trianglePlanes = [];
  11145. var start = subMesh.verticesStart;
  11146. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11147. for (var i = start; i < end; i++) {
  11148. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11149. }
  11150. }
  11151. // Collide
  11152. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11153. if (collider.collisionFound) {
  11154. collider.collidedMesh = this;
  11155. }
  11156. };
  11157. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11158. var subMeshes;
  11159. var len;
  11160. // Octrees
  11161. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11162. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11163. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11164. len = intersections.length;
  11165. subMeshes = intersections.data;
  11166. }
  11167. else {
  11168. subMeshes = this.subMeshes;
  11169. len = subMeshes.length;
  11170. }
  11171. for (var index = 0; index < len; index++) {
  11172. var subMesh = subMeshes[index];
  11173. // Bounding test
  11174. if (len > 1 && !subMesh._checkCollision(collider))
  11175. continue;
  11176. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11177. }
  11178. };
  11179. AbstractMesh.prototype._checkCollision = function (collider) {
  11180. // Bounding box test
  11181. if (!this._boundingInfo._checkCollision(collider))
  11182. return;
  11183. // Transformation matrix
  11184. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11185. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11186. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11187. };
  11188. // Picking
  11189. AbstractMesh.prototype._generatePointsArray = function () {
  11190. return false;
  11191. };
  11192. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11193. var pickingInfo = new BABYLON.PickingInfo();
  11194. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11195. return pickingInfo;
  11196. }
  11197. if (!this._generatePointsArray()) {
  11198. return pickingInfo;
  11199. }
  11200. var intersectInfo = null;
  11201. // Octrees
  11202. var subMeshes;
  11203. var len;
  11204. if (this._submeshesOctree && this.useOctreeForPicking) {
  11205. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11206. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11207. len = intersections.length;
  11208. subMeshes = intersections.data;
  11209. }
  11210. else {
  11211. subMeshes = this.subMeshes;
  11212. len = subMeshes.length;
  11213. }
  11214. for (var index = 0; index < len; index++) {
  11215. var subMesh = subMeshes[index];
  11216. // Bounding test
  11217. if (len > 1 && !subMesh.canIntersects(ray))
  11218. continue;
  11219. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11220. if (currentIntersectInfo) {
  11221. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11222. intersectInfo = currentIntersectInfo;
  11223. intersectInfo.subMeshId = index;
  11224. if (fastCheck) {
  11225. break;
  11226. }
  11227. }
  11228. }
  11229. }
  11230. if (intersectInfo) {
  11231. // Get picked point
  11232. var world = this.getWorldMatrix();
  11233. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11234. var direction = ray.direction.clone();
  11235. direction = direction.scale(intersectInfo.distance);
  11236. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11237. var pickedPoint = worldOrigin.add(worldDirection);
  11238. // Return result
  11239. pickingInfo.hit = true;
  11240. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11241. pickingInfo.pickedPoint = pickedPoint;
  11242. pickingInfo.pickedMesh = this;
  11243. pickingInfo.bu = intersectInfo.bu;
  11244. pickingInfo.bv = intersectInfo.bv;
  11245. pickingInfo.faceId = intersectInfo.faceId;
  11246. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11247. return pickingInfo;
  11248. }
  11249. return pickingInfo;
  11250. };
  11251. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11252. return null;
  11253. };
  11254. AbstractMesh.prototype.releaseSubMeshes = function () {
  11255. if (this.subMeshes) {
  11256. while (this.subMeshes.length) {
  11257. this.subMeshes[0].dispose();
  11258. }
  11259. }
  11260. else {
  11261. this.subMeshes = new Array();
  11262. }
  11263. };
  11264. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11265. var _this = this;
  11266. var index;
  11267. // Action manager
  11268. if (this.actionManager) {
  11269. this.actionManager.dispose();
  11270. this.actionManager = null;
  11271. }
  11272. // Skeleton
  11273. this.skeleton = null;
  11274. // Animations
  11275. this.getScene().stopAnimation(this);
  11276. // Physics
  11277. if (this.physicsImpostor) {
  11278. this.physicsImpostor.dispose();
  11279. }
  11280. // Intersections in progress
  11281. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11282. var other = this._intersectionsInProgress[index];
  11283. var pos = other._intersectionsInProgress.indexOf(this);
  11284. other._intersectionsInProgress.splice(pos, 1);
  11285. }
  11286. this._intersectionsInProgress = [];
  11287. // Lights
  11288. var lights = this.getScene().lights;
  11289. lights.forEach(function (light) {
  11290. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11291. if (meshIndex !== -1) {
  11292. light.includedOnlyMeshes.splice(meshIndex, 1);
  11293. }
  11294. meshIndex = light.excludedMeshes.indexOf(_this);
  11295. if (meshIndex !== -1) {
  11296. light.excludedMeshes.splice(meshIndex, 1);
  11297. }
  11298. // Shadow generators
  11299. var generator = light.getShadowGenerator();
  11300. if (generator) {
  11301. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11302. if (meshIndex !== -1) {
  11303. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11304. }
  11305. }
  11306. });
  11307. // Edges
  11308. if (this._edgesRenderer) {
  11309. this._edgesRenderer.dispose();
  11310. this._edgesRenderer = null;
  11311. }
  11312. // SubMeshes
  11313. this.releaseSubMeshes();
  11314. // Engine
  11315. this.getScene().getEngine().unbindAllAttributes();
  11316. // Remove from scene
  11317. this.getScene().removeMesh(this);
  11318. if (!doNotRecurse) {
  11319. // Particles
  11320. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11321. if (this.getScene().particleSystems[index].emitter === this) {
  11322. this.getScene().particleSystems[index].dispose();
  11323. index--;
  11324. }
  11325. }
  11326. // Children
  11327. var objects = this.getDescendants(true);
  11328. for (index = 0; index < objects.length; index++) {
  11329. objects[index].dispose();
  11330. }
  11331. }
  11332. else {
  11333. var childMeshes = this.getChildMeshes(true);
  11334. for (index = 0; index < childMeshes.length; index++) {
  11335. var child = childMeshes[index];
  11336. child.parent = null;
  11337. child.computeWorldMatrix(true);
  11338. }
  11339. }
  11340. this.onAfterWorldMatrixUpdateObservable.clear();
  11341. this.onCollideObservable.clear();
  11342. this.onCollisionPositionChangeObservable.clear();
  11343. this._isDisposed = true;
  11344. _super.prototype.dispose.call(this);
  11345. };
  11346. AbstractMesh.prototype.getDirection = function (localAxis) {
  11347. var result = BABYLON.Vector3.Zero();
  11348. this.getDirectionToRef(localAxis, result);
  11349. return result;
  11350. };
  11351. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11352. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11353. };
  11354. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11356. if (this.getScene().getRenderId() == 0) {
  11357. this.computeWorldMatrix(true);
  11358. }
  11359. var wm = this.getWorldMatrix();
  11360. if (space == BABYLON.Space.WORLD) {
  11361. var tmat = BABYLON.Tmp.Matrix[0];
  11362. wm.invertToRef(tmat);
  11363. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11364. }
  11365. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11366. this._pivotMatrix.m[12] = -point.x;
  11367. this._pivotMatrix.m[13] = -point.y;
  11368. this._pivotMatrix.m[14] = -point.z;
  11369. this._cache.pivotMatrixUpdated = true;
  11370. };
  11371. AbstractMesh.prototype.getPivotPoint = function () {
  11372. var point = BABYLON.Vector3.Zero();
  11373. this.getPivotPointToRef(point);
  11374. return point;
  11375. };
  11376. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11377. result.x = -this._pivotMatrix.m[12];
  11378. result.y = -this._pivotMatrix.m[13];
  11379. result.z = -this._pivotMatrix.m[14];
  11380. };
  11381. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11382. var point = BABYLON.Vector3.Zero();
  11383. this.getAbsolutePivotPointToRef(point);
  11384. return point;
  11385. };
  11386. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11387. result.x = this._pivotMatrix.m[12];
  11388. result.y = this._pivotMatrix.m[13];
  11389. result.z = this._pivotMatrix.m[14];
  11390. this.getPivotPointToRef(result);
  11391. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11392. };
  11393. return AbstractMesh;
  11394. }(BABYLON.Node));
  11395. // Statics
  11396. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11397. AbstractMesh._BILLBOARDMODE_X = 1;
  11398. AbstractMesh._BILLBOARDMODE_Y = 2;
  11399. AbstractMesh._BILLBOARDMODE_Z = 4;
  11400. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11401. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11402. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11403. BABYLON.AbstractMesh = AbstractMesh;
  11404. })(BABYLON || (BABYLON = {}));
  11405. //# sourceMappingURL=babylon.abstractMesh.js.map
  11406. var BABYLON;
  11407. (function (BABYLON) {
  11408. var Light = (function (_super) {
  11409. __extends(Light, _super);
  11410. function Light(name, scene) {
  11411. var _this = _super.call(this, name, scene) || this;
  11412. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11413. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11414. _this.intensity = 1.0;
  11415. _this.range = Number.MAX_VALUE;
  11416. _this.includeOnlyWithLayerMask = 0;
  11417. _this.includedOnlyMeshes = new Array();
  11418. _this.excludedMeshes = new Array();
  11419. _this.excludeWithLayerMask = 0;
  11420. _this.lightmapMode = 0;
  11421. // PBR Properties.
  11422. _this.radius = 0.00001;
  11423. _this._excludedMeshesIds = new Array();
  11424. _this._includedOnlyMeshesIds = new Array();
  11425. scene.addLight(_this);
  11426. return _this;
  11427. }
  11428. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11429. /**
  11430. * If every light affecting the material is in this lightmapMode,
  11431. * material.lightmapTexture adds or multiplies
  11432. * (depends on material.useLightmapAsShadowmap)
  11433. * after every other light calculations.
  11434. */
  11435. get: function () {
  11436. return Light._LIGHTMAP_DEFAULT;
  11437. },
  11438. enumerable: true,
  11439. configurable: true
  11440. });
  11441. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11442. /**
  11443. * material.lightmapTexture as only diffuse lighting from this light
  11444. * adds pnly specular lighting from this light
  11445. * adds dynamic shadows
  11446. */
  11447. get: function () {
  11448. return Light._LIGHTMAP_SPECULAR;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11454. /**
  11455. * material.lightmapTexture as only lighting
  11456. * no light calculation from this light
  11457. * only adds dynamic shadows from this light
  11458. */
  11459. get: function () {
  11460. return Light._LIGHTMAP_SHADOWSONLY;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Light.prototype.getClassName = function () {
  11466. return "Light";
  11467. };
  11468. /**
  11469. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11470. */
  11471. Light.prototype.toString = function (fullDetails) {
  11472. var ret = "Name: " + this.name;
  11473. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11474. if (this.animations) {
  11475. for (var i = 0; i < this.animations.length; i++) {
  11476. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11477. }
  11478. }
  11479. if (fullDetails) {
  11480. }
  11481. return ret;
  11482. };
  11483. Light.prototype.getShadowGenerator = function () {
  11484. return this._shadowGenerator;
  11485. };
  11486. Light.prototype.getAbsolutePosition = function () {
  11487. return BABYLON.Vector3.Zero();
  11488. };
  11489. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11490. };
  11491. Light.prototype._getWorldMatrix = function () {
  11492. return BABYLON.Matrix.Identity();
  11493. };
  11494. Light.prototype.canAffectMesh = function (mesh) {
  11495. if (!mesh) {
  11496. return true;
  11497. }
  11498. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11499. return false;
  11500. }
  11501. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11502. return false;
  11503. }
  11504. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11505. return false;
  11506. }
  11507. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11508. return false;
  11509. }
  11510. return true;
  11511. };
  11512. Light.prototype.getWorldMatrix = function () {
  11513. this._currentRenderId = this.getScene().getRenderId();
  11514. var worldMatrix = this._getWorldMatrix();
  11515. if (this.parent && this.parent.getWorldMatrix) {
  11516. if (!this._parentedWorldMatrix) {
  11517. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11518. }
  11519. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11520. this._markSyncedWithParent();
  11521. return this._parentedWorldMatrix;
  11522. }
  11523. return worldMatrix;
  11524. };
  11525. Light.prototype.dispose = function () {
  11526. if (this._shadowGenerator) {
  11527. this._shadowGenerator.dispose();
  11528. this._shadowGenerator = null;
  11529. }
  11530. // Animations
  11531. this.getScene().stopAnimation(this);
  11532. // Remove from scene
  11533. this.getScene().removeLight(this);
  11534. _super.prototype.dispose.call(this);
  11535. };
  11536. Light.prototype.getTypeID = function () {
  11537. return 0;
  11538. };
  11539. Light.prototype.clone = function (name) {
  11540. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11541. };
  11542. Light.prototype.serialize = function () {
  11543. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11544. // Type
  11545. serializationObject.type = this.getTypeID();
  11546. // Parent
  11547. if (this.parent) {
  11548. serializationObject.parentId = this.parent.id;
  11549. }
  11550. // Inclusion / exclusions
  11551. if (this.excludedMeshes.length > 0) {
  11552. serializationObject.excludedMeshesIds = [];
  11553. this.excludedMeshes.forEach(function (mesh) {
  11554. serializationObject.excludedMeshesIds.push(mesh.id);
  11555. });
  11556. }
  11557. if (this.includedOnlyMeshes.length > 0) {
  11558. serializationObject.includedOnlyMeshesIds = [];
  11559. this.includedOnlyMeshes.forEach(function (mesh) {
  11560. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11561. });
  11562. }
  11563. // Animations
  11564. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11565. serializationObject.ranges = this.serializeAnimationRanges();
  11566. return serializationObject;
  11567. };
  11568. Light.GetConstructorFromName = function (type, name, scene) {
  11569. switch (type) {
  11570. case 0:
  11571. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11572. case 1:
  11573. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11574. case 2:
  11575. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11576. case 3:
  11577. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11578. }
  11579. };
  11580. Light.Parse = function (parsedLight, scene) {
  11581. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11582. // Inclusion / exclusions
  11583. if (parsedLight.excludedMeshesIds) {
  11584. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11585. }
  11586. if (parsedLight.includedOnlyMeshesIds) {
  11587. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11588. }
  11589. // Parent
  11590. if (parsedLight.parentId) {
  11591. light._waitingParentId = parsedLight.parentId;
  11592. }
  11593. // Animations
  11594. if (parsedLight.animations) {
  11595. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11596. var parsedAnimation = parsedLight.animations[animationIndex];
  11597. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11598. }
  11599. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11600. }
  11601. if (parsedLight.autoAnimate) {
  11602. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11603. }
  11604. return light;
  11605. };
  11606. return Light;
  11607. }(BABYLON.Node));
  11608. //lightmapMode Consts
  11609. Light._LIGHTMAP_DEFAULT = 0;
  11610. Light._LIGHTMAP_SPECULAR = 1;
  11611. Light._LIGHTMAP_SHADOWSONLY = 2;
  11612. __decorate([
  11613. BABYLON.serializeAsColor3()
  11614. ], Light.prototype, "diffuse", void 0);
  11615. __decorate([
  11616. BABYLON.serializeAsColor3()
  11617. ], Light.prototype, "specular", void 0);
  11618. __decorate([
  11619. BABYLON.serialize()
  11620. ], Light.prototype, "intensity", void 0);
  11621. __decorate([
  11622. BABYLON.serialize()
  11623. ], Light.prototype, "range", void 0);
  11624. __decorate([
  11625. BABYLON.serialize()
  11626. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11627. __decorate([
  11628. BABYLON.serialize()
  11629. ], Light.prototype, "excludeWithLayerMask", void 0);
  11630. __decorate([
  11631. BABYLON.serialize()
  11632. ], Light.prototype, "lightmapMode", void 0);
  11633. __decorate([
  11634. BABYLON.serialize()
  11635. ], Light.prototype, "radius", void 0);
  11636. BABYLON.Light = Light;
  11637. })(BABYLON || (BABYLON = {}));
  11638. //# sourceMappingURL=babylon.light.js.map
  11639. var BABYLON;
  11640. (function (BABYLON) {
  11641. var PointLight = (function (_super) {
  11642. __extends(PointLight, _super);
  11643. function PointLight(name, position, scene) {
  11644. var _this = _super.call(this, name, scene) || this;
  11645. _this.position = position;
  11646. return _this;
  11647. }
  11648. PointLight.prototype.getClassName = function () {
  11649. return "PointLight";
  11650. };
  11651. PointLight.prototype.getAbsolutePosition = function () {
  11652. return this.transformedPosition ? this.transformedPosition : this.position;
  11653. };
  11654. PointLight.prototype.computeTransformedPosition = function () {
  11655. if (this.parent && this.parent.getWorldMatrix) {
  11656. if (!this.transformedPosition) {
  11657. this.transformedPosition = BABYLON.Vector3.Zero();
  11658. }
  11659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11660. return true;
  11661. }
  11662. return false;
  11663. };
  11664. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11665. if (this.parent && this.parent.getWorldMatrix) {
  11666. this.computeTransformedPosition();
  11667. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11668. return;
  11669. }
  11670. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11671. };
  11672. PointLight.prototype.needCube = function () {
  11673. return true;
  11674. };
  11675. PointLight.prototype.supportsVSM = function () {
  11676. return false;
  11677. };
  11678. PointLight.prototype.needRefreshPerFrame = function () {
  11679. return false;
  11680. };
  11681. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11682. switch (faceIndex) {
  11683. case 0:
  11684. return new BABYLON.Vector3(1, 0, 0);
  11685. case 1:
  11686. return new BABYLON.Vector3(-1, 0, 0);
  11687. case 2:
  11688. return new BABYLON.Vector3(0, -1, 0);
  11689. case 3:
  11690. return new BABYLON.Vector3(0, 1, 0);
  11691. case 4:
  11692. return new BABYLON.Vector3(0, 0, 1);
  11693. case 5:
  11694. return new BABYLON.Vector3(0, 0, -1);
  11695. }
  11696. return BABYLON.Vector3.Zero();
  11697. };
  11698. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11699. var activeCamera = this.getScene().activeCamera;
  11700. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11701. };
  11702. PointLight.prototype._getWorldMatrix = function () {
  11703. if (!this._worldMatrix) {
  11704. this._worldMatrix = BABYLON.Matrix.Identity();
  11705. }
  11706. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11707. return this._worldMatrix;
  11708. };
  11709. PointLight.prototype.getTypeID = function () {
  11710. return 0;
  11711. };
  11712. return PointLight;
  11713. }(BABYLON.Light));
  11714. __decorate([
  11715. BABYLON.serializeAsVector3()
  11716. ], PointLight.prototype, "position", void 0);
  11717. BABYLON.PointLight = PointLight;
  11718. })(BABYLON || (BABYLON = {}));
  11719. //# sourceMappingURL=babylon.pointLight.js.map
  11720. var BABYLON;
  11721. (function (BABYLON) {
  11722. var SpotLight = (function (_super) {
  11723. __extends(SpotLight, _super);
  11724. function SpotLight(name, position, direction, angle, exponent, scene) {
  11725. var _this = _super.call(this, name, scene) || this;
  11726. _this.position = position;
  11727. _this.direction = direction;
  11728. _this.angle = angle;
  11729. _this.exponent = exponent;
  11730. return _this;
  11731. }
  11732. SpotLight.prototype.getClassName = function () {
  11733. return "SpotLight";
  11734. };
  11735. SpotLight.prototype.getAbsolutePosition = function () {
  11736. return this.transformedPosition ? this.transformedPosition : this.position;
  11737. };
  11738. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11739. var activeCamera = this.getScene().activeCamera;
  11740. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11741. };
  11742. SpotLight.prototype.needCube = function () {
  11743. return false;
  11744. };
  11745. SpotLight.prototype.supportsVSM = function () {
  11746. return true;
  11747. };
  11748. SpotLight.prototype.needRefreshPerFrame = function () {
  11749. return false;
  11750. };
  11751. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11752. return this.direction;
  11753. };
  11754. SpotLight.prototype.setDirectionToTarget = function (target) {
  11755. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11756. return this.direction;
  11757. };
  11758. SpotLight.prototype.computeTransformedPosition = function () {
  11759. if (this.parent && this.parent.getWorldMatrix) {
  11760. if (!this.transformedPosition) {
  11761. this.transformedPosition = BABYLON.Vector3.Zero();
  11762. }
  11763. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11764. return true;
  11765. }
  11766. return false;
  11767. };
  11768. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11769. var normalizeDirection;
  11770. if (this.parent && this.parent.getWorldMatrix) {
  11771. if (!this._transformedDirection) {
  11772. this._transformedDirection = BABYLON.Vector3.Zero();
  11773. }
  11774. this.computeTransformedPosition();
  11775. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11776. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11777. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11778. }
  11779. else {
  11780. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11781. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11782. }
  11783. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11784. };
  11785. SpotLight.prototype._getWorldMatrix = function () {
  11786. if (!this._worldMatrix) {
  11787. this._worldMatrix = BABYLON.Matrix.Identity();
  11788. }
  11789. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11790. return this._worldMatrix;
  11791. };
  11792. SpotLight.prototype.getTypeID = function () {
  11793. return 2;
  11794. };
  11795. SpotLight.prototype.getRotation = function () {
  11796. this.direction.normalize();
  11797. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11798. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11799. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11800. };
  11801. return SpotLight;
  11802. }(BABYLON.Light));
  11803. __decorate([
  11804. BABYLON.serializeAsVector3()
  11805. ], SpotLight.prototype, "position", void 0);
  11806. __decorate([
  11807. BABYLON.serializeAsVector3()
  11808. ], SpotLight.prototype, "direction", void 0);
  11809. __decorate([
  11810. BABYLON.serialize()
  11811. ], SpotLight.prototype, "angle", void 0);
  11812. __decorate([
  11813. BABYLON.serialize()
  11814. ], SpotLight.prototype, "exponent", void 0);
  11815. BABYLON.SpotLight = SpotLight;
  11816. })(BABYLON || (BABYLON = {}));
  11817. //# sourceMappingURL=babylon.spotLight.js.map
  11818. var BABYLON;
  11819. (function (BABYLON) {
  11820. var HemisphericLight = (function (_super) {
  11821. __extends(HemisphericLight, _super);
  11822. function HemisphericLight(name, direction, scene) {
  11823. var _this = _super.call(this, name, scene) || this;
  11824. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11825. _this.direction = direction;
  11826. return _this;
  11827. }
  11828. HemisphericLight.prototype.getClassName = function () {
  11829. return "HemisphericLight";
  11830. };
  11831. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11832. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11833. return this.direction;
  11834. };
  11835. HemisphericLight.prototype.getShadowGenerator = function () {
  11836. return null;
  11837. };
  11838. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11839. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11840. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11841. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11842. };
  11843. HemisphericLight.prototype._getWorldMatrix = function () {
  11844. if (!this._worldMatrix) {
  11845. this._worldMatrix = BABYLON.Matrix.Identity();
  11846. }
  11847. return this._worldMatrix;
  11848. };
  11849. HemisphericLight.prototype.getTypeID = function () {
  11850. return 3;
  11851. };
  11852. return HemisphericLight;
  11853. }(BABYLON.Light));
  11854. __decorate([
  11855. BABYLON.serializeAsColor3()
  11856. ], HemisphericLight.prototype, "groundColor", void 0);
  11857. __decorate([
  11858. BABYLON.serializeAsVector3()
  11859. ], HemisphericLight.prototype, "direction", void 0);
  11860. BABYLON.HemisphericLight = HemisphericLight;
  11861. })(BABYLON || (BABYLON = {}));
  11862. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11863. var BABYLON;
  11864. (function (BABYLON) {
  11865. var DirectionalLight = (function (_super) {
  11866. __extends(DirectionalLight, _super);
  11867. function DirectionalLight(name, direction, scene) {
  11868. var _this = _super.call(this, name, scene) || this;
  11869. _this.shadowOrthoScale = 0.5;
  11870. _this.autoUpdateExtends = true;
  11871. // Cache
  11872. _this._orthoLeft = Number.MAX_VALUE;
  11873. _this._orthoRight = Number.MIN_VALUE;
  11874. _this._orthoTop = Number.MIN_VALUE;
  11875. _this._orthoBottom = Number.MAX_VALUE;
  11876. _this.position = direction.scale(-1);
  11877. _this.direction = direction;
  11878. return _this;
  11879. }
  11880. DirectionalLight.prototype.getClassName = function () {
  11881. return "DirectionalLight";
  11882. };
  11883. DirectionalLight.prototype.getAbsolutePosition = function () {
  11884. return this.transformedPosition ? this.transformedPosition : this.position;
  11885. };
  11886. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11887. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11888. return this.direction;
  11889. };
  11890. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11891. var activeCamera = this.getScene().activeCamera;
  11892. // Check extends
  11893. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11894. var tempVector3 = BABYLON.Vector3.Zero();
  11895. this._orthoLeft = Number.MAX_VALUE;
  11896. this._orthoRight = Number.MIN_VALUE;
  11897. this._orthoTop = Number.MIN_VALUE;
  11898. this._orthoBottom = Number.MAX_VALUE;
  11899. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11900. var mesh = renderList[meshIndex];
  11901. if (!mesh) {
  11902. continue;
  11903. }
  11904. var boundingInfo = mesh.getBoundingInfo();
  11905. if (!boundingInfo) {
  11906. continue;
  11907. }
  11908. var boundingBox = boundingInfo.boundingBox;
  11909. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11910. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11911. if (tempVector3.x < this._orthoLeft)
  11912. this._orthoLeft = tempVector3.x;
  11913. if (tempVector3.y < this._orthoBottom)
  11914. this._orthoBottom = tempVector3.y;
  11915. if (tempVector3.x > this._orthoRight)
  11916. this._orthoRight = tempVector3.x;
  11917. if (tempVector3.y > this._orthoTop)
  11918. this._orthoTop = tempVector3.y;
  11919. }
  11920. }
  11921. }
  11922. var xOffset = this._orthoRight - this._orthoLeft;
  11923. var yOffset = this._orthoTop - this._orthoBottom;
  11924. 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);
  11925. };
  11926. DirectionalLight.prototype.supportsVSM = function () {
  11927. return true;
  11928. };
  11929. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11930. return true;
  11931. };
  11932. DirectionalLight.prototype.needCube = function () {
  11933. return false;
  11934. };
  11935. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11936. return this.direction;
  11937. };
  11938. DirectionalLight.prototype.computeTransformedPosition = function () {
  11939. if (this.parent && this.parent.getWorldMatrix) {
  11940. if (!this.transformedPosition) {
  11941. this.transformedPosition = BABYLON.Vector3.Zero();
  11942. }
  11943. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11944. return true;
  11945. }
  11946. return false;
  11947. };
  11948. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11949. if (this.parent && this.parent.getWorldMatrix) {
  11950. if (!this._transformedDirection) {
  11951. this._transformedDirection = BABYLON.Vector3.Zero();
  11952. }
  11953. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11954. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11955. return;
  11956. }
  11957. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11958. };
  11959. DirectionalLight.prototype._getWorldMatrix = function () {
  11960. if (!this._worldMatrix) {
  11961. this._worldMatrix = BABYLON.Matrix.Identity();
  11962. }
  11963. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11964. return this._worldMatrix;
  11965. };
  11966. DirectionalLight.prototype.getTypeID = function () {
  11967. return 1;
  11968. };
  11969. return DirectionalLight;
  11970. }(BABYLON.Light));
  11971. __decorate([
  11972. BABYLON.serializeAsVector3()
  11973. ], DirectionalLight.prototype, "position", void 0);
  11974. __decorate([
  11975. BABYLON.serializeAsVector3()
  11976. ], DirectionalLight.prototype, "direction", void 0);
  11977. __decorate([
  11978. BABYLON.serialize()
  11979. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11980. __decorate([
  11981. BABYLON.serialize()
  11982. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11983. BABYLON.DirectionalLight = DirectionalLight;
  11984. })(BABYLON || (BABYLON = {}));
  11985. //# sourceMappingURL=babylon.directionalLight.js.map
  11986. var BABYLON;
  11987. (function (BABYLON) {
  11988. var ShadowGenerator = (function () {
  11989. function ShadowGenerator(mapSize, light) {
  11990. var _this = this;
  11991. // Members
  11992. this._filter = ShadowGenerator.FILTER_NONE;
  11993. this.blurScale = 2;
  11994. this._blurBoxOffset = 0;
  11995. this._bias = 0.00005;
  11996. this._lightDirection = BABYLON.Vector3.Zero();
  11997. this.forceBackFacesOnly = false;
  11998. this._darkness = 0;
  11999. this._transparencyShadow = false;
  12000. this._viewMatrix = BABYLON.Matrix.Zero();
  12001. this._projectionMatrix = BABYLON.Matrix.Zero();
  12002. this._transformMatrix = BABYLON.Matrix.Zero();
  12003. this._worldViewProjection = BABYLON.Matrix.Zero();
  12004. this._currentFaceIndex = 0;
  12005. this._currentFaceIndexCache = 0;
  12006. this._useFullFloat = true;
  12007. this._light = light;
  12008. this._scene = light.getScene();
  12009. this._mapSize = mapSize;
  12010. light._shadowGenerator = this;
  12011. // Texture type fallback from float to int if not supported.
  12012. var textureType;
  12013. var caps = this._scene.getEngine().getCaps();
  12014. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12015. this._useFullFloat = true;
  12016. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12017. }
  12018. else {
  12019. this._useFullFloat = false;
  12020. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12021. }
  12022. // Render target
  12023. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12024. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12025. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12026. this._shadowMap.anisotropicFilteringLevel = 1;
  12027. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12028. this._shadowMap.renderParticles = false;
  12029. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12030. _this._currentFaceIndex = faceIndex;
  12031. });
  12032. this._shadowMap.onAfterUnbindObservable.add(function () {
  12033. if (!_this.useBlurVarianceShadowMap) {
  12034. return;
  12035. }
  12036. if (!_this._shadowMap2) {
  12037. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12038. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12039. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12040. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12041. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12042. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12043. effect.setTexture("textureSampler", _this._shadowMap);
  12044. });
  12045. _this.blurBoxOffset = 1;
  12046. }
  12047. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12048. });
  12049. // Custom render function
  12050. var renderSubMesh = function (subMesh) {
  12051. var mesh = subMesh.getRenderingMesh();
  12052. var scene = _this._scene;
  12053. var engine = scene.getEngine();
  12054. // Culling
  12055. engine.setState(subMesh.getMaterial().backFaceCulling);
  12056. // Managing instances
  12057. var batch = mesh._getInstancesRenderList(subMesh._id);
  12058. if (batch.mustReturn) {
  12059. return;
  12060. }
  12061. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12062. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12063. engine.enableEffect(_this._effect);
  12064. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12065. var material = subMesh.getMaterial();
  12066. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12067. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12068. if (_this.getLight().needCube()) {
  12069. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12070. }
  12071. // Alpha test
  12072. if (material && material.needAlphaTesting()) {
  12073. var alphaTexture = material.getAlphaTestTexture();
  12074. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12075. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12076. }
  12077. // Bones
  12078. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12079. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12080. }
  12081. if (_this.forceBackFacesOnly) {
  12082. engine.setState(true, 0, false, true);
  12083. }
  12084. // Draw
  12085. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12086. if (_this.forceBackFacesOnly) {
  12087. engine.setState(true, 0, false, false);
  12088. }
  12089. }
  12090. else {
  12091. // Need to reset refresh rate of the shadowMap
  12092. _this._shadowMap.resetRefreshCounter();
  12093. }
  12094. };
  12095. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12096. var index;
  12097. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12098. renderSubMesh(opaqueSubMeshes.data[index]);
  12099. }
  12100. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12101. renderSubMesh(alphaTestSubMeshes.data[index]);
  12102. }
  12103. if (_this._transparencyShadow) {
  12104. for (index = 0; index < transparentSubMeshes.length; index++) {
  12105. renderSubMesh(transparentSubMeshes.data[index]);
  12106. }
  12107. }
  12108. };
  12109. this._shadowMap.onClearObservable.add(function (engine) {
  12110. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12111. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12112. }
  12113. else {
  12114. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12115. }
  12116. });
  12117. }
  12118. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12119. // Static
  12120. get: function () {
  12121. return ShadowGenerator._FILTER_NONE;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12127. get: function () {
  12128. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12134. get: function () {
  12135. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12141. get: function () {
  12142. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12148. get: function () {
  12149. return this._bias;
  12150. },
  12151. set: function (bias) {
  12152. this._bias = bias;
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12158. get: function () {
  12159. return this._blurBoxOffset;
  12160. },
  12161. set: function (value) {
  12162. var _this = this;
  12163. if (this._blurBoxOffset === value) {
  12164. return;
  12165. }
  12166. this._blurBoxOffset = value;
  12167. if (this._boxBlurPostprocess) {
  12168. this._boxBlurPostprocess.dispose();
  12169. }
  12170. 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);
  12171. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12172. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12173. });
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12179. get: function () {
  12180. return this._filter;
  12181. },
  12182. set: function (value) {
  12183. if (this._filter === value) {
  12184. return;
  12185. }
  12186. this._filter = value;
  12187. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12188. this._shadowMap.anisotropicFilteringLevel = 16;
  12189. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12190. }
  12191. else {
  12192. this._shadowMap.anisotropicFilteringLevel = 1;
  12193. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12194. }
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12200. get: function () {
  12201. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12202. },
  12203. set: function (value) {
  12204. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12210. get: function () {
  12211. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12212. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12213. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12214. },
  12215. set: function (value) {
  12216. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12222. get: function () {
  12223. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12224. },
  12225. set: function (value) {
  12226. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12232. var defines = [];
  12233. if (this._useFullFloat) {
  12234. defines.push("#define FULLFLOAT");
  12235. }
  12236. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12237. defines.push("#define VSM");
  12238. }
  12239. if (this.getLight().needCube()) {
  12240. defines.push("#define CUBEMAP");
  12241. }
  12242. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12243. var mesh = subMesh.getMesh();
  12244. var material = subMesh.getMaterial();
  12245. // Alpha test
  12246. if (material && material.needAlphaTesting()) {
  12247. defines.push("#define ALPHATEST");
  12248. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12249. attribs.push(BABYLON.VertexBuffer.UVKind);
  12250. defines.push("#define UV1");
  12251. }
  12252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12253. var alphaTexture = material.getAlphaTestTexture();
  12254. if (alphaTexture.coordinatesIndex === 1) {
  12255. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12256. defines.push("#define UV2");
  12257. }
  12258. }
  12259. }
  12260. // Bones
  12261. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12262. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12263. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12264. if (mesh.numBoneInfluencers > 4) {
  12265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12267. }
  12268. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12269. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12270. }
  12271. else {
  12272. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12273. }
  12274. // Instances
  12275. if (useInstances) {
  12276. defines.push("#define INSTANCES");
  12277. attribs.push("world0");
  12278. attribs.push("world1");
  12279. attribs.push("world2");
  12280. attribs.push("world3");
  12281. }
  12282. // Get correct effect
  12283. var join = defines.join("\n");
  12284. if (this._cachedDefines !== join) {
  12285. this._cachedDefines = join;
  12286. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12287. }
  12288. return this._effect.isReady();
  12289. };
  12290. ShadowGenerator.prototype.getShadowMap = function () {
  12291. return this._shadowMap;
  12292. };
  12293. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12294. if (this._shadowMap2) {
  12295. return this._shadowMap2;
  12296. }
  12297. return this._shadowMap;
  12298. };
  12299. ShadowGenerator.prototype.getLight = function () {
  12300. return this._light;
  12301. };
  12302. // Methods
  12303. ShadowGenerator.prototype.getTransformMatrix = function () {
  12304. var scene = this._scene;
  12305. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12306. return this._transformMatrix;
  12307. }
  12308. this._currentRenderID = scene.getRenderId();
  12309. this._currentFaceIndexCache = this._currentFaceIndex;
  12310. var lightPosition = this._light.position;
  12311. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12312. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12313. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12314. }
  12315. if (this._light.computeTransformedPosition()) {
  12316. lightPosition = this._light.transformedPosition;
  12317. }
  12318. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12319. this._cachedPosition = lightPosition.clone();
  12320. this._cachedDirection = this._lightDirection.clone();
  12321. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12322. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12323. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12324. }
  12325. return this._transformMatrix;
  12326. };
  12327. ShadowGenerator.prototype.getDarkness = function () {
  12328. return this._darkness;
  12329. };
  12330. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12331. if (darkness >= 1.0)
  12332. this._darkness = 1.0;
  12333. else if (darkness <= 0.0)
  12334. this._darkness = 0.0;
  12335. else
  12336. this._darkness = darkness;
  12337. };
  12338. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12339. this._transparencyShadow = hasShadow;
  12340. };
  12341. ShadowGenerator.prototype._packHalf = function (depth) {
  12342. var scale = depth * 255.0;
  12343. var fract = scale - Math.floor(scale);
  12344. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12345. };
  12346. ShadowGenerator.prototype.dispose = function () {
  12347. this._shadowMap.dispose();
  12348. if (this._shadowMap2) {
  12349. this._shadowMap2.dispose();
  12350. }
  12351. if (this._downSamplePostprocess) {
  12352. this._downSamplePostprocess.dispose();
  12353. }
  12354. if (this._boxBlurPostprocess) {
  12355. this._boxBlurPostprocess.dispose();
  12356. }
  12357. };
  12358. ShadowGenerator.prototype.serialize = function () {
  12359. var serializationObject = {};
  12360. serializationObject.lightId = this._light.id;
  12361. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12362. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12363. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12364. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12365. serializationObject.renderList = [];
  12366. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12367. var mesh = this.getShadowMap().renderList[meshIndex];
  12368. serializationObject.renderList.push(mesh.id);
  12369. }
  12370. return serializationObject;
  12371. };
  12372. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12373. //casting to point light, as light is missing the position attr and typescript complains.
  12374. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12375. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12376. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12377. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12378. meshes.forEach(function (mesh) {
  12379. shadowGenerator.getShadowMap().renderList.push(mesh);
  12380. });
  12381. }
  12382. if (parsedShadowGenerator.usePoissonSampling) {
  12383. shadowGenerator.usePoissonSampling = true;
  12384. }
  12385. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12386. shadowGenerator.useVarianceShadowMap = true;
  12387. }
  12388. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12389. shadowGenerator.useBlurVarianceShadowMap = true;
  12390. if (parsedShadowGenerator.blurScale) {
  12391. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12392. }
  12393. if (parsedShadowGenerator.blurBoxOffset) {
  12394. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12395. }
  12396. }
  12397. if (parsedShadowGenerator.bias !== undefined) {
  12398. shadowGenerator.bias = parsedShadowGenerator.bias;
  12399. }
  12400. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12401. return shadowGenerator;
  12402. };
  12403. return ShadowGenerator;
  12404. }());
  12405. ShadowGenerator._FILTER_NONE = 0;
  12406. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12407. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12408. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12409. BABYLON.ShadowGenerator = ShadowGenerator;
  12410. })(BABYLON || (BABYLON = {}));
  12411. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12412. var BABYLON;
  12413. (function (BABYLON) {
  12414. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12415. if (boxMin.x > sphereCenter.x + sphereRadius)
  12416. return false;
  12417. if (sphereCenter.x - sphereRadius > boxMax.x)
  12418. return false;
  12419. if (boxMin.y > sphereCenter.y + sphereRadius)
  12420. return false;
  12421. if (sphereCenter.y - sphereRadius > boxMax.y)
  12422. return false;
  12423. if (boxMin.z > sphereCenter.z + sphereRadius)
  12424. return false;
  12425. if (sphereCenter.z - sphereRadius > boxMax.z)
  12426. return false;
  12427. return true;
  12428. };
  12429. var getLowestRoot = (function () {
  12430. var result = { root: 0, found: false };
  12431. return function (a, b, c, maxR) {
  12432. result.root = 0;
  12433. result.found = false;
  12434. var determinant = b * b - 4.0 * a * c;
  12435. if (determinant < 0)
  12436. return result;
  12437. var sqrtD = Math.sqrt(determinant);
  12438. var r1 = (-b - sqrtD) / (2.0 * a);
  12439. var r2 = (-b + sqrtD) / (2.0 * a);
  12440. if (r1 > r2) {
  12441. var temp = r2;
  12442. r2 = r1;
  12443. r1 = temp;
  12444. }
  12445. if (r1 > 0 && r1 < maxR) {
  12446. result.root = r1;
  12447. result.found = true;
  12448. return result;
  12449. }
  12450. if (r2 > 0 && r2 < maxR) {
  12451. result.root = r2;
  12452. result.found = true;
  12453. return result;
  12454. }
  12455. return result;
  12456. };
  12457. })();
  12458. var Collider = (function () {
  12459. function Collider() {
  12460. this.radius = new BABYLON.Vector3(1, 1, 1);
  12461. this.retry = 0;
  12462. this.basePointWorld = BABYLON.Vector3.Zero();
  12463. this.velocityWorld = BABYLON.Vector3.Zero();
  12464. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12465. this._collisionPoint = BABYLON.Vector3.Zero();
  12466. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12467. this._tempVector = BABYLON.Vector3.Zero();
  12468. this._tempVector2 = BABYLON.Vector3.Zero();
  12469. this._tempVector3 = BABYLON.Vector3.Zero();
  12470. this._tempVector4 = BABYLON.Vector3.Zero();
  12471. this._edge = BABYLON.Vector3.Zero();
  12472. this._baseToVertex = BABYLON.Vector3.Zero();
  12473. this._destinationPoint = BABYLON.Vector3.Zero();
  12474. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12475. this._displacementVector = BABYLON.Vector3.Zero();
  12476. }
  12477. // Methods
  12478. Collider.prototype._initialize = function (source, dir, e) {
  12479. this.velocity = dir;
  12480. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12481. this.basePoint = source;
  12482. source.multiplyToRef(this.radius, this.basePointWorld);
  12483. dir.multiplyToRef(this.radius, this.velocityWorld);
  12484. this.velocityWorldLength = this.velocityWorld.length();
  12485. this.epsilon = e;
  12486. this.collisionFound = false;
  12487. };
  12488. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12489. pa.subtractToRef(point, this._tempVector);
  12490. pb.subtractToRef(point, this._tempVector2);
  12491. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12492. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12493. if (d < 0)
  12494. return false;
  12495. pc.subtractToRef(point, this._tempVector3);
  12496. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12497. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12498. if (d < 0)
  12499. return false;
  12500. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12501. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12502. return d >= 0;
  12503. };
  12504. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12505. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12506. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12507. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12508. return false;
  12509. }
  12510. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12511. return false;
  12512. return true;
  12513. };
  12514. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12515. var t0;
  12516. var embeddedInPlane = false;
  12517. //defensive programming, actually not needed.
  12518. if (!trianglePlaneArray) {
  12519. trianglePlaneArray = [];
  12520. }
  12521. if (!trianglePlaneArray[faceIndex]) {
  12522. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12523. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12524. }
  12525. var trianglePlane = trianglePlaneArray[faceIndex];
  12526. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12527. return;
  12528. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12529. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12530. if (normalDotVelocity == 0) {
  12531. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12532. return;
  12533. embeddedInPlane = true;
  12534. t0 = 0;
  12535. }
  12536. else {
  12537. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12538. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12539. if (t0 > t1) {
  12540. var temp = t1;
  12541. t1 = t0;
  12542. t0 = temp;
  12543. }
  12544. if (t0 > 1.0 || t1 < 0.0)
  12545. return;
  12546. if (t0 < 0)
  12547. t0 = 0;
  12548. if (t0 > 1.0)
  12549. t0 = 1.0;
  12550. }
  12551. this._collisionPoint.copyFromFloats(0, 0, 0);
  12552. var found = false;
  12553. var t = 1.0;
  12554. if (!embeddedInPlane) {
  12555. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12556. this.velocity.scaleToRef(t0, this._tempVector);
  12557. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12558. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12559. found = true;
  12560. t = t0;
  12561. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12562. }
  12563. }
  12564. if (!found) {
  12565. var velocitySquaredLength = this.velocity.lengthSquared();
  12566. var a = velocitySquaredLength;
  12567. this.basePoint.subtractToRef(p1, this._tempVector);
  12568. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12569. var c = this._tempVector.lengthSquared() - 1.0;
  12570. var lowestRoot = getLowestRoot(a, b, c, t);
  12571. if (lowestRoot.found) {
  12572. t = lowestRoot.root;
  12573. found = true;
  12574. this._collisionPoint.copyFrom(p1);
  12575. }
  12576. this.basePoint.subtractToRef(p2, this._tempVector);
  12577. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12578. c = this._tempVector.lengthSquared() - 1.0;
  12579. lowestRoot = getLowestRoot(a, b, c, t);
  12580. if (lowestRoot.found) {
  12581. t = lowestRoot.root;
  12582. found = true;
  12583. this._collisionPoint.copyFrom(p2);
  12584. }
  12585. this.basePoint.subtractToRef(p3, this._tempVector);
  12586. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12587. c = this._tempVector.lengthSquared() - 1.0;
  12588. lowestRoot = getLowestRoot(a, b, c, t);
  12589. if (lowestRoot.found) {
  12590. t = lowestRoot.root;
  12591. found = true;
  12592. this._collisionPoint.copyFrom(p3);
  12593. }
  12594. p2.subtractToRef(p1, this._edge);
  12595. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12596. var edgeSquaredLength = this._edge.lengthSquared();
  12597. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12598. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12599. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12600. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12601. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12602. lowestRoot = getLowestRoot(a, b, c, t);
  12603. if (lowestRoot.found) {
  12604. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12605. if (f >= 0.0 && f <= 1.0) {
  12606. t = lowestRoot.root;
  12607. found = true;
  12608. this._edge.scaleInPlace(f);
  12609. p1.addToRef(this._edge, this._collisionPoint);
  12610. }
  12611. }
  12612. p3.subtractToRef(p2, this._edge);
  12613. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12614. edgeSquaredLength = this._edge.lengthSquared();
  12615. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12616. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12617. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12618. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12619. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12620. lowestRoot = getLowestRoot(a, b, c, t);
  12621. if (lowestRoot.found) {
  12622. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12623. if (f >= 0.0 && f <= 1.0) {
  12624. t = lowestRoot.root;
  12625. found = true;
  12626. this._edge.scaleInPlace(f);
  12627. p2.addToRef(this._edge, this._collisionPoint);
  12628. }
  12629. }
  12630. p1.subtractToRef(p3, this._edge);
  12631. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12632. edgeSquaredLength = this._edge.lengthSquared();
  12633. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12634. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12635. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12636. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12637. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12638. lowestRoot = getLowestRoot(a, b, c, t);
  12639. if (lowestRoot.found) {
  12640. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12641. if (f >= 0.0 && f <= 1.0) {
  12642. t = lowestRoot.root;
  12643. found = true;
  12644. this._edge.scaleInPlace(f);
  12645. p3.addToRef(this._edge, this._collisionPoint);
  12646. }
  12647. }
  12648. }
  12649. if (found) {
  12650. var distToCollision = t * this.velocity.length();
  12651. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12652. if (!this.intersectionPoint) {
  12653. this.intersectionPoint = this._collisionPoint.clone();
  12654. }
  12655. else {
  12656. this.intersectionPoint.copyFrom(this._collisionPoint);
  12657. }
  12658. this.nearestDistance = distToCollision;
  12659. this.collisionFound = true;
  12660. }
  12661. }
  12662. };
  12663. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12664. for (var i = indexStart; i < indexEnd; i += 3) {
  12665. var p1 = pts[indices[i] - decal];
  12666. var p2 = pts[indices[i + 1] - decal];
  12667. var p3 = pts[indices[i + 2] - decal];
  12668. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12669. }
  12670. };
  12671. Collider.prototype._getResponse = function (pos, vel) {
  12672. pos.addToRef(vel, this._destinationPoint);
  12673. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12674. this.basePoint.addToRef(vel, pos);
  12675. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12676. this._slidePlaneNormal.normalize();
  12677. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12678. pos.addInPlace(this._displacementVector);
  12679. this.intersectionPoint.addInPlace(this._displacementVector);
  12680. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12681. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12682. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12683. };
  12684. return Collider;
  12685. }());
  12686. BABYLON.Collider = Collider;
  12687. })(BABYLON || (BABYLON = {}));
  12688. //# sourceMappingURL=babylon.collider.js.map
  12689. var BABYLON;
  12690. (function (BABYLON) {
  12691. //WebWorker code will be inserted to this variable.
  12692. BABYLON.CollisionWorker = "";
  12693. var WorkerTaskType;
  12694. (function (WorkerTaskType) {
  12695. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12696. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12697. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12698. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12699. var WorkerReplyType;
  12700. (function (WorkerReplyType) {
  12701. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12702. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12703. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12704. var CollisionCoordinatorWorker = (function () {
  12705. function CollisionCoordinatorWorker() {
  12706. var _this = this;
  12707. this._scaledPosition = BABYLON.Vector3.Zero();
  12708. this._scaledVelocity = BABYLON.Vector3.Zero();
  12709. this.onMeshUpdated = function (mesh) {
  12710. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12711. };
  12712. this.onGeometryUpdated = function (geometry) {
  12713. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12714. };
  12715. this._afterRender = function () {
  12716. if (!_this._init)
  12717. return;
  12718. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12719. return;
  12720. }
  12721. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12722. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12723. if (_this._runningUpdated > 4) {
  12724. return;
  12725. }
  12726. ++_this._runningUpdated;
  12727. var payload = {
  12728. updatedMeshes: _this._addUpdateMeshesList,
  12729. updatedGeometries: _this._addUpdateGeometriesList,
  12730. removedGeometries: _this._toRemoveGeometryArray,
  12731. removedMeshes: _this._toRemoveMeshesArray
  12732. };
  12733. var message = {
  12734. payload: payload,
  12735. taskType: WorkerTaskType.UPDATE
  12736. };
  12737. var serializable = [];
  12738. for (var id in payload.updatedGeometries) {
  12739. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12740. //prepare transferables
  12741. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12742. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12743. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12744. }
  12745. }
  12746. _this._worker.postMessage(message, serializable);
  12747. _this._addUpdateMeshesList = {};
  12748. _this._addUpdateGeometriesList = {};
  12749. _this._toRemoveGeometryArray = [];
  12750. _this._toRemoveMeshesArray = [];
  12751. };
  12752. this._onMessageFromWorker = function (e) {
  12753. var returnData = e.data;
  12754. if (returnData.error != WorkerReplyType.SUCCESS) {
  12755. //TODO what errors can be returned from the worker?
  12756. BABYLON.Tools.Warn("error returned from worker!");
  12757. return;
  12758. }
  12759. switch (returnData.taskType) {
  12760. case WorkerTaskType.INIT:
  12761. _this._init = true;
  12762. //Update the worked with ALL of the scene's current state
  12763. _this._scene.meshes.forEach(function (mesh) {
  12764. _this.onMeshAdded(mesh);
  12765. });
  12766. _this._scene.getGeometries().forEach(function (geometry) {
  12767. _this.onGeometryAdded(geometry);
  12768. });
  12769. break;
  12770. case WorkerTaskType.UPDATE:
  12771. _this._runningUpdated--;
  12772. break;
  12773. case WorkerTaskType.COLLIDE:
  12774. _this._runningCollisionTask = false;
  12775. var returnPayload = returnData.payload;
  12776. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12777. return;
  12778. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12779. //cleanup
  12780. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12781. break;
  12782. }
  12783. };
  12784. this._collisionsCallbackArray = [];
  12785. this._init = false;
  12786. this._runningUpdated = 0;
  12787. this._runningCollisionTask = false;
  12788. this._addUpdateMeshesList = {};
  12789. this._addUpdateGeometriesList = {};
  12790. this._toRemoveGeometryArray = [];
  12791. this._toRemoveMeshesArray = [];
  12792. }
  12793. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12794. if (!this._init)
  12795. return;
  12796. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12797. return;
  12798. position.divideToRef(collider.radius, this._scaledPosition);
  12799. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12800. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12801. var payload = {
  12802. collider: {
  12803. position: this._scaledPosition.asArray(),
  12804. velocity: this._scaledVelocity.asArray(),
  12805. radius: collider.radius.asArray()
  12806. },
  12807. collisionId: collisionIndex,
  12808. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12809. maximumRetry: maximumRetry
  12810. };
  12811. var message = {
  12812. payload: payload,
  12813. taskType: WorkerTaskType.COLLIDE
  12814. };
  12815. this._worker.postMessage(message);
  12816. };
  12817. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12818. this._scene = scene;
  12819. this._scene.registerAfterRender(this._afterRender);
  12820. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12821. this._worker = new Worker(workerUrl);
  12822. this._worker.onmessage = this._onMessageFromWorker;
  12823. var message = {
  12824. payload: {},
  12825. taskType: WorkerTaskType.INIT
  12826. };
  12827. this._worker.postMessage(message);
  12828. };
  12829. CollisionCoordinatorWorker.prototype.destroy = function () {
  12830. this._scene.unregisterAfterRender(this._afterRender);
  12831. this._worker.terminate();
  12832. };
  12833. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12834. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12835. this.onMeshUpdated(mesh);
  12836. };
  12837. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12838. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12839. };
  12840. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12841. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12842. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12843. this.onGeometryUpdated(geometry);
  12844. };
  12845. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12846. this._toRemoveGeometryArray.push(geometry.id);
  12847. };
  12848. return CollisionCoordinatorWorker;
  12849. }());
  12850. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12851. var submeshes = [];
  12852. if (mesh.subMeshes) {
  12853. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12854. return {
  12855. position: idx,
  12856. verticesStart: sm.verticesStart,
  12857. verticesCount: sm.verticesCount,
  12858. indexStart: sm.indexStart,
  12859. indexCount: sm.indexCount,
  12860. hasMaterial: !!sm.getMaterial(),
  12861. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12862. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12863. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12864. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12865. };
  12866. });
  12867. }
  12868. var geometryId = null;
  12869. if (mesh instanceof BABYLON.Mesh) {
  12870. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12871. }
  12872. else if (mesh instanceof BABYLON.InstancedMesh) {
  12873. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12874. }
  12875. return {
  12876. uniqueId: mesh.uniqueId,
  12877. id: mesh.id,
  12878. name: mesh.name,
  12879. geometryId: geometryId,
  12880. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12881. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12882. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12883. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12884. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12885. subMeshes: submeshes,
  12886. checkCollisions: mesh.checkCollisions
  12887. };
  12888. };
  12889. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12890. return {
  12891. id: geometry.id,
  12892. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12893. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12894. indices: new Int32Array(geometry.getIndices() || []),
  12895. };
  12896. };
  12897. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12898. var CollisionCoordinatorLegacy = (function () {
  12899. function CollisionCoordinatorLegacy() {
  12900. this._scaledPosition = BABYLON.Vector3.Zero();
  12901. this._scaledVelocity = BABYLON.Vector3.Zero();
  12902. this._finalPosition = BABYLON.Vector3.Zero();
  12903. }
  12904. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12905. position.divideToRef(collider.radius, this._scaledPosition);
  12906. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12907. collider.collidedMesh = null;
  12908. collider.retry = 0;
  12909. collider.initialVelocity = this._scaledVelocity;
  12910. collider.initialPosition = this._scaledPosition;
  12911. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12912. this._finalPosition.multiplyInPlace(collider.radius);
  12913. //run the callback
  12914. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12915. };
  12916. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12917. this._scene = scene;
  12918. };
  12919. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12920. //Legacy need no destruction method.
  12921. };
  12922. //No update in legacy mode
  12923. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12924. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12925. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12926. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12927. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12928. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12929. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12930. if (excludedMesh === void 0) { excludedMesh = null; }
  12931. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12932. if (collider.retry >= maximumRetry) {
  12933. finalPosition.copyFrom(position);
  12934. return;
  12935. }
  12936. collider._initialize(position, velocity, closeDistance);
  12937. // Check all meshes
  12938. for (var index = 0; index < this._scene.meshes.length; index++) {
  12939. var mesh = this._scene.meshes[index];
  12940. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12941. mesh._checkCollision(collider);
  12942. }
  12943. }
  12944. if (!collider.collisionFound) {
  12945. position.addToRef(velocity, finalPosition);
  12946. return;
  12947. }
  12948. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12949. collider._getResponse(position, velocity);
  12950. }
  12951. if (velocity.length() <= closeDistance) {
  12952. finalPosition.copyFrom(position);
  12953. return;
  12954. }
  12955. collider.retry++;
  12956. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12957. };
  12958. return CollisionCoordinatorLegacy;
  12959. }());
  12960. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12961. })(BABYLON || (BABYLON = {}));
  12962. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  12963. var BABYLON;
  12964. (function (BABYLON) {
  12965. var Camera = (function (_super) {
  12966. __extends(Camera, _super);
  12967. function Camera(name, position, scene) {
  12968. var _this = _super.call(this, name, scene) || this;
  12969. _this.upVector = BABYLON.Vector3.Up();
  12970. _this.orthoLeft = null;
  12971. _this.orthoRight = null;
  12972. _this.orthoBottom = null;
  12973. _this.orthoTop = null;
  12974. _this.fov = 0.8;
  12975. _this.minZ = 1.0;
  12976. _this.maxZ = 10000.0;
  12977. _this.inertia = 0.9;
  12978. _this.mode = Camera.PERSPECTIVE_CAMERA;
  12979. _this.isIntermediate = false;
  12980. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12981. _this.layerMask = 0x0FFFFFFF;
  12982. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12983. // Camera rig members
  12984. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  12985. _this._rigCameras = new Array();
  12986. // Cache
  12987. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  12988. _this._projectionMatrix = new BABYLON.Matrix();
  12989. _this._doNotComputeProjectionMatrix = false;
  12990. _this._postProcesses = new Array();
  12991. _this._transformMatrix = BABYLON.Matrix.Zero();
  12992. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12993. _this._activeMeshes = new BABYLON.SmartArray(256);
  12994. _this._globalPosition = BABYLON.Vector3.Zero();
  12995. _this._refreshFrustumPlanes = true;
  12996. scene.addCamera(_this);
  12997. if (!scene.activeCamera) {
  12998. scene.activeCamera = _this;
  12999. }
  13000. _this.position = position;
  13001. return _this;
  13002. }
  13003. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13004. get: function () {
  13005. return Camera._PERSPECTIVE_CAMERA;
  13006. },
  13007. enumerable: true,
  13008. configurable: true
  13009. });
  13010. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13011. get: function () {
  13012. return Camera._ORTHOGRAPHIC_CAMERA;
  13013. },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13018. get: function () {
  13019. return Camera._FOVMODE_VERTICAL_FIXED;
  13020. },
  13021. enumerable: true,
  13022. configurable: true
  13023. });
  13024. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13025. get: function () {
  13026. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13027. },
  13028. enumerable: true,
  13029. configurable: true
  13030. });
  13031. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13032. get: function () {
  13033. return Camera._RIG_MODE_NONE;
  13034. },
  13035. enumerable: true,
  13036. configurable: true
  13037. });
  13038. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13039. get: function () {
  13040. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13041. },
  13042. enumerable: true,
  13043. configurable: true
  13044. });
  13045. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13046. get: function () {
  13047. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13048. },
  13049. enumerable: true,
  13050. configurable: true
  13051. });
  13052. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13053. get: function () {
  13054. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13055. },
  13056. enumerable: true,
  13057. configurable: true
  13058. });
  13059. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13060. get: function () {
  13061. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13062. },
  13063. enumerable: true,
  13064. configurable: true
  13065. });
  13066. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13067. get: function () {
  13068. return Camera._RIG_MODE_VR;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13074. get: function () {
  13075. return Camera._RIG_MODE_WEBVR;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. Camera.prototype.getClassName = function () {
  13081. return "Camera";
  13082. };
  13083. /**
  13084. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13085. */
  13086. Camera.prototype.toString = function (fullDetails) {
  13087. var ret = "Name: " + this.name;
  13088. ret += ", type: " + this.getClassName();
  13089. if (this.animations) {
  13090. for (var i = 0; i < this.animations.length; i++) {
  13091. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13092. }
  13093. }
  13094. if (fullDetails) {
  13095. }
  13096. return ret;
  13097. };
  13098. Object.defineProperty(Camera.prototype, "globalPosition", {
  13099. get: function () {
  13100. return this._globalPosition;
  13101. },
  13102. enumerable: true,
  13103. configurable: true
  13104. });
  13105. Camera.prototype.getActiveMeshes = function () {
  13106. return this._activeMeshes;
  13107. };
  13108. Camera.prototype.isActiveMesh = function (mesh) {
  13109. return (this._activeMeshes.indexOf(mesh) !== -1);
  13110. };
  13111. //Cache
  13112. Camera.prototype._initCache = function () {
  13113. _super.prototype._initCache.call(this);
  13114. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13115. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13116. this._cache.mode = undefined;
  13117. this._cache.minZ = undefined;
  13118. this._cache.maxZ = undefined;
  13119. this._cache.fov = undefined;
  13120. this._cache.fovMode = undefined;
  13121. this._cache.aspectRatio = undefined;
  13122. this._cache.orthoLeft = undefined;
  13123. this._cache.orthoRight = undefined;
  13124. this._cache.orthoBottom = undefined;
  13125. this._cache.orthoTop = undefined;
  13126. this._cache.renderWidth = undefined;
  13127. this._cache.renderHeight = undefined;
  13128. };
  13129. Camera.prototype._updateCache = function (ignoreParentClass) {
  13130. if (!ignoreParentClass) {
  13131. _super.prototype._updateCache.call(this);
  13132. }
  13133. var engine = this.getEngine();
  13134. this._cache.position.copyFrom(this.position);
  13135. this._cache.upVector.copyFrom(this.upVector);
  13136. this._cache.mode = this.mode;
  13137. this._cache.minZ = this.minZ;
  13138. this._cache.maxZ = this.maxZ;
  13139. this._cache.fov = this.fov;
  13140. this._cache.fovMode = this.fovMode;
  13141. this._cache.aspectRatio = engine.getAspectRatio(this);
  13142. this._cache.orthoLeft = this.orthoLeft;
  13143. this._cache.orthoRight = this.orthoRight;
  13144. this._cache.orthoBottom = this.orthoBottom;
  13145. this._cache.orthoTop = this.orthoTop;
  13146. this._cache.renderWidth = engine.getRenderWidth();
  13147. this._cache.renderHeight = engine.getRenderHeight();
  13148. };
  13149. Camera.prototype._updateFromScene = function () {
  13150. this.updateCache();
  13151. this.update();
  13152. };
  13153. // Synchronized
  13154. Camera.prototype._isSynchronized = function () {
  13155. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13156. };
  13157. Camera.prototype._isSynchronizedViewMatrix = function () {
  13158. if (!_super.prototype._isSynchronized.call(this))
  13159. return false;
  13160. return this._cache.position.equals(this.position)
  13161. && this._cache.upVector.equals(this.upVector)
  13162. && this.isSynchronizedWithParent();
  13163. };
  13164. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13165. var check = this._cache.mode === this.mode
  13166. && this._cache.minZ === this.minZ
  13167. && this._cache.maxZ === this.maxZ;
  13168. if (!check) {
  13169. return false;
  13170. }
  13171. var engine = this.getEngine();
  13172. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13173. check = this._cache.fov === this.fov
  13174. && this._cache.fovMode === this.fovMode
  13175. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13176. }
  13177. else {
  13178. check = this._cache.orthoLeft === this.orthoLeft
  13179. && this._cache.orthoRight === this.orthoRight
  13180. && this._cache.orthoBottom === this.orthoBottom
  13181. && this._cache.orthoTop === this.orthoTop
  13182. && this._cache.renderWidth === engine.getRenderWidth()
  13183. && this._cache.renderHeight === engine.getRenderHeight();
  13184. }
  13185. return check;
  13186. };
  13187. // Controls
  13188. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13189. };
  13190. Camera.prototype.detachControl = function (element) {
  13191. };
  13192. Camera.prototype.update = function () {
  13193. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13194. this._updateRigCameras();
  13195. }
  13196. this._checkInputs();
  13197. };
  13198. Camera.prototype._checkInputs = function () {
  13199. };
  13200. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13201. // invalidate framebuffer
  13202. if (this._postProcesses.length > 0) {
  13203. this._postProcesses[0].markTextureDirty();
  13204. }
  13205. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13206. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13207. var cam = this._rigCameras[i];
  13208. var rigPostProcess = cam._rigPostProcess;
  13209. // for VR rig, there does not have to be a post process
  13210. if (rigPostProcess) {
  13211. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13212. if (isPass) {
  13213. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13214. cam.isIntermediate = this._postProcesses.length === 0;
  13215. }
  13216. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13217. rigPostProcess.markTextureDirty();
  13218. }
  13219. else {
  13220. cam._postProcesses = this._postProcesses.slice(0);
  13221. }
  13222. }
  13223. };
  13224. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13225. if (insertAt === void 0) { insertAt = null; }
  13226. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13227. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13228. return 0;
  13229. }
  13230. if (insertAt == null || insertAt < 0) {
  13231. this._postProcesses.push(postProcess);
  13232. }
  13233. else {
  13234. this._postProcesses.splice(insertAt, 0, postProcess);
  13235. }
  13236. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13237. return this._postProcesses.indexOf(postProcess);
  13238. };
  13239. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13240. if (atIndices === void 0) { atIndices = null; }
  13241. var result = [];
  13242. var i;
  13243. var index;
  13244. if (!atIndices) {
  13245. var idx = this._postProcesses.indexOf(postProcess);
  13246. if (idx !== -1) {
  13247. this._postProcesses.splice(idx, 1);
  13248. }
  13249. }
  13250. else {
  13251. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13252. // iterate descending, so can just splice as we go
  13253. for (i = atIndices.length - 1; i >= 0; i--) {
  13254. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13255. result.push(i);
  13256. continue;
  13257. }
  13258. this._postProcesses.splice(index, 1);
  13259. }
  13260. }
  13261. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13262. return result;
  13263. };
  13264. Camera.prototype.getWorldMatrix = function () {
  13265. if (!this._worldMatrix) {
  13266. this._worldMatrix = BABYLON.Matrix.Identity();
  13267. }
  13268. var viewMatrix = this.getViewMatrix();
  13269. viewMatrix.invertToRef(this._worldMatrix);
  13270. return this._worldMatrix;
  13271. };
  13272. Camera.prototype._getViewMatrix = function () {
  13273. return BABYLON.Matrix.Identity();
  13274. };
  13275. Camera.prototype.getViewMatrix = function (force) {
  13276. this._computedViewMatrix = this._computeViewMatrix(force);
  13277. if (!force && this._isSynchronizedViewMatrix()) {
  13278. return this._computedViewMatrix;
  13279. }
  13280. this._refreshFrustumPlanes = true;
  13281. if (!this.parent || !this.parent.getWorldMatrix) {
  13282. this._globalPosition.copyFrom(this.position);
  13283. }
  13284. else {
  13285. if (!this._worldMatrix) {
  13286. this._worldMatrix = BABYLON.Matrix.Identity();
  13287. }
  13288. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13289. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13290. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13291. this._computedViewMatrix.invert();
  13292. this._markSyncedWithParent();
  13293. }
  13294. this._currentRenderId = this.getScene().getRenderId();
  13295. return this._computedViewMatrix;
  13296. };
  13297. Camera.prototype._computeViewMatrix = function (force) {
  13298. if (!force && this._isSynchronizedViewMatrix()) {
  13299. return this._computedViewMatrix;
  13300. }
  13301. this._computedViewMatrix = this._getViewMatrix();
  13302. this._currentRenderId = this.getScene().getRenderId();
  13303. return this._computedViewMatrix;
  13304. };
  13305. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13306. this._doNotComputeProjectionMatrix = true;
  13307. if (projection !== undefined) {
  13308. this._projectionMatrix = projection;
  13309. }
  13310. };
  13311. ;
  13312. Camera.prototype.unfreezeProjectionMatrix = function () {
  13313. this._doNotComputeProjectionMatrix = false;
  13314. };
  13315. ;
  13316. Camera.prototype.getProjectionMatrix = function (force) {
  13317. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13318. return this._projectionMatrix;
  13319. }
  13320. this._refreshFrustumPlanes = true;
  13321. var engine = this.getEngine();
  13322. var scene = this.getScene();
  13323. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13324. if (this.minZ <= 0) {
  13325. this.minZ = 0.1;
  13326. }
  13327. if (scene.useRightHandedSystem) {
  13328. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13329. }
  13330. else {
  13331. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13332. }
  13333. return this._projectionMatrix;
  13334. }
  13335. var halfWidth = engine.getRenderWidth() / 2.0;
  13336. var halfHeight = engine.getRenderHeight() / 2.0;
  13337. if (scene.useRightHandedSystem) {
  13338. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13339. }
  13340. else {
  13341. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13342. }
  13343. return this._projectionMatrix;
  13344. };
  13345. Camera.prototype.getTranformationMatrix = function () {
  13346. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13347. return this._transformMatrix;
  13348. };
  13349. Camera.prototype.updateFrustumPlanes = function () {
  13350. if (!this._refreshFrustumPlanes) {
  13351. return;
  13352. }
  13353. this.getTranformationMatrix();
  13354. if (!this._frustumPlanes) {
  13355. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13356. }
  13357. else {
  13358. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13359. }
  13360. this._refreshFrustumPlanes = false;
  13361. };
  13362. Camera.prototype.isInFrustum = function (target) {
  13363. this.updateFrustumPlanes();
  13364. return target.isInFrustum(this._frustumPlanes);
  13365. };
  13366. Camera.prototype.isCompletelyInFrustum = function (target) {
  13367. this.updateFrustumPlanes();
  13368. return target.isCompletelyInFrustum(this._frustumPlanes);
  13369. };
  13370. Camera.prototype.dispose = function () {
  13371. // Animations
  13372. this.getScene().stopAnimation(this);
  13373. // Remove from scene
  13374. this.getScene().removeCamera(this);
  13375. while (this._rigCameras.length > 0) {
  13376. this._rigCameras.pop().dispose();
  13377. }
  13378. // Postprocesses
  13379. for (var i = 0; i < this._postProcesses.length; ++i) {
  13380. this._postProcesses[i].dispose(this);
  13381. }
  13382. _super.prototype.dispose.call(this);
  13383. };
  13384. // ---- Camera rigs section ----
  13385. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13386. while (this._rigCameras.length > 0) {
  13387. this._rigCameras.pop().dispose();
  13388. }
  13389. this.cameraRigMode = mode;
  13390. this._cameraRigParams = {};
  13391. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13392. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13393. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13394. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13395. // create the rig cameras, unless none
  13396. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13397. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13398. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13399. }
  13400. switch (this.cameraRigMode) {
  13401. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13402. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13403. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13404. break;
  13405. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13406. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13407. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13408. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13409. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13410. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13411. break;
  13412. case Camera.RIG_MODE_VR:
  13413. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13414. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13415. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13416. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13417. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13418. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13419. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13420. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13421. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13422. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13423. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13424. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13425. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13426. if (metrics.compensateDistortion) {
  13427. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13428. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13429. }
  13430. break;
  13431. case Camera.RIG_MODE_WEBVR:
  13432. if (rigParams.vrDisplay) {
  13433. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13434. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13435. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13436. this._rigCameras[0].setCameraRigParameter("left", true);
  13437. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13438. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13439. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13440. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13441. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13442. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13443. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13444. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13445. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13446. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13447. }
  13448. break;
  13449. }
  13450. this._cascadePostProcessesToRigCams();
  13451. this.
  13452. update();
  13453. };
  13454. Camera.prototype._getVRProjectionMatrix = function () {
  13455. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13456. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13457. return this._projectionMatrix;
  13458. };
  13459. Camera.prototype._getWebVRProjectionMatrix = function () {
  13460. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13461. //babylon compatible matrix
  13462. [8, 9, 10, 11].forEach(function (num) {
  13463. projectionArray[num] *= -1;
  13464. });
  13465. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13466. return this._projectionMatrix;
  13467. };
  13468. //Can be used, but we'll use the free camera's view matrix calculation
  13469. Camera.prototype._getWebVRViewMatrix = function () {
  13470. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13471. //babylon compatible matrix
  13472. [8, 9, 10, 11].forEach(function (num) {
  13473. projectionArray[num] *= -1;
  13474. });
  13475. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13476. return this._webvrViewMatrix;
  13477. };
  13478. Camera.prototype.setCameraRigParameter = function (name, value) {
  13479. if (!this._cameraRigParams) {
  13480. this._cameraRigParams = {};
  13481. }
  13482. this._cameraRigParams[name] = value;
  13483. //provisionnally:
  13484. if (name === "interaxialDistance") {
  13485. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13486. }
  13487. };
  13488. /**
  13489. * needs to be overridden by children so sub has required properties to be copied
  13490. */
  13491. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13492. return null;
  13493. };
  13494. /**
  13495. * May need to be overridden by children
  13496. */
  13497. Camera.prototype._updateRigCameras = function () {
  13498. for (var i = 0; i < this._rigCameras.length; i++) {
  13499. this._rigCameras[i].minZ = this.minZ;
  13500. this._rigCameras[i].maxZ = this.maxZ;
  13501. this._rigCameras[i].fov = this.fov;
  13502. }
  13503. // only update viewport when ANAGLYPH
  13504. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13505. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13506. }
  13507. };
  13508. Camera.prototype._setupInputs = function () {
  13509. };
  13510. Camera.prototype.serialize = function () {
  13511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13512. // Type
  13513. serializationObject.type = this.getClassName();
  13514. // Parent
  13515. if (this.parent) {
  13516. serializationObject.parentId = this.parent.id;
  13517. }
  13518. if (this.inputs) {
  13519. this.inputs.serialize(serializationObject);
  13520. }
  13521. // Animations
  13522. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13523. serializationObject.ranges = this.serializeAnimationRanges();
  13524. return serializationObject;
  13525. };
  13526. Camera.prototype.clone = function (name) {
  13527. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13528. };
  13529. Camera.prototype.getDirection = function (localAxis) {
  13530. var result = BABYLON.Vector3.Zero();
  13531. this.getDirectionToRef(localAxis, result);
  13532. return result;
  13533. };
  13534. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13535. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13536. };
  13537. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13538. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13539. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13540. switch (type) {
  13541. case "ArcRotateCamera":
  13542. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13543. case "DeviceOrientationCamera":
  13544. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13545. case "FollowCamera":
  13546. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13547. case "ArcFollowCamera":
  13548. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13549. case "GamepadCamera":
  13550. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13551. case "TouchCamera":
  13552. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13553. case "VirtualJoysticksCamera":
  13554. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13555. case "WebVRFreeCamera":
  13556. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13557. case "VRDeviceOrientationFreeCamera":
  13558. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13559. case "AnaglyphArcRotateCamera":
  13560. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13561. case "AnaglyphFreeCamera":
  13562. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13563. case "AnaglyphGamepadCamera":
  13564. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13565. case "AnaglyphUniversalCamera":
  13566. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13567. case "StereoscopicArcRotateCamera":
  13568. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13569. case "StereoscopicFreeCamera":
  13570. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13571. case "StereoscopicGamepadCamera":
  13572. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13573. case "StereoscopicUniversalCamera":
  13574. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13575. case "FreeCamera":
  13576. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13577. default:
  13578. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13579. }
  13580. };
  13581. Camera.Parse = function (parsedCamera, scene) {
  13582. var type = parsedCamera.type;
  13583. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13584. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13585. // Parent
  13586. if (parsedCamera.parentId) {
  13587. camera._waitingParentId = parsedCamera.parentId;
  13588. }
  13589. //If camera has an input manager, let it parse inputs settings
  13590. if (camera.inputs) {
  13591. camera.inputs.parse(parsedCamera);
  13592. camera._setupInputs();
  13593. }
  13594. // Target
  13595. if (parsedCamera.target) {
  13596. if (camera.setTarget) {
  13597. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13598. }
  13599. }
  13600. // Apply 3d rig, when found
  13601. if (parsedCamera.cameraRigMode) {
  13602. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13603. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13604. }
  13605. // Animations
  13606. if (parsedCamera.animations) {
  13607. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13608. var parsedAnimation = parsedCamera.animations[animationIndex];
  13609. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13610. }
  13611. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13612. }
  13613. if (parsedCamera.autoAnimate) {
  13614. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13615. }
  13616. return camera;
  13617. };
  13618. return Camera;
  13619. }(BABYLON.Node));
  13620. // Statics
  13621. Camera._PERSPECTIVE_CAMERA = 0;
  13622. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13623. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13624. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13625. Camera._RIG_MODE_NONE = 0;
  13626. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13627. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13628. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13629. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13630. Camera._RIG_MODE_VR = 20;
  13631. Camera._RIG_MODE_WEBVR = 21;
  13632. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13633. __decorate([
  13634. BABYLON.serializeAsVector3()
  13635. ], Camera.prototype, "position", void 0);
  13636. __decorate([
  13637. BABYLON.serializeAsVector3()
  13638. ], Camera.prototype, "upVector", void 0);
  13639. __decorate([
  13640. BABYLON.serialize()
  13641. ], Camera.prototype, "orthoLeft", void 0);
  13642. __decorate([
  13643. BABYLON.serialize()
  13644. ], Camera.prototype, "orthoRight", void 0);
  13645. __decorate([
  13646. BABYLON.serialize()
  13647. ], Camera.prototype, "orthoBottom", void 0);
  13648. __decorate([
  13649. BABYLON.serialize()
  13650. ], Camera.prototype, "orthoTop", void 0);
  13651. __decorate([
  13652. BABYLON.serialize()
  13653. ], Camera.prototype, "fov", void 0);
  13654. __decorate([
  13655. BABYLON.serialize()
  13656. ], Camera.prototype, "minZ", void 0);
  13657. __decorate([
  13658. BABYLON.serialize()
  13659. ], Camera.prototype, "maxZ", void 0);
  13660. __decorate([
  13661. BABYLON.serialize()
  13662. ], Camera.prototype, "inertia", void 0);
  13663. __decorate([
  13664. BABYLON.serialize()
  13665. ], Camera.prototype, "mode", void 0);
  13666. __decorate([
  13667. BABYLON.serialize()
  13668. ], Camera.prototype, "layerMask", void 0);
  13669. __decorate([
  13670. BABYLON.serialize()
  13671. ], Camera.prototype, "fovMode", void 0);
  13672. __decorate([
  13673. BABYLON.serialize()
  13674. ], Camera.prototype, "cameraRigMode", void 0);
  13675. __decorate([
  13676. BABYLON.serialize()
  13677. ], Camera.prototype, "interaxialDistance", void 0);
  13678. __decorate([
  13679. BABYLON.serialize()
  13680. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13681. BABYLON.Camera = Camera;
  13682. })(BABYLON || (BABYLON = {}));
  13683. //# sourceMappingURL=babylon.camera.js.map
  13684. var BABYLON;
  13685. (function (BABYLON) {
  13686. BABYLON.CameraInputTypes = {};
  13687. var CameraInputsManager = (function () {
  13688. function CameraInputsManager(camera) {
  13689. this.attached = {};
  13690. this.camera = camera;
  13691. this.checkInputs = function () { };
  13692. }
  13693. CameraInputsManager.prototype.add = function (input) {
  13694. var type = input.getSimpleName();
  13695. if (this.attached[type]) {
  13696. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13697. return;
  13698. }
  13699. this.attached[type] = input;
  13700. input.camera = this.camera;
  13701. //for checkInputs, we are dynamically creating a function
  13702. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13703. if (input.checkInputs) {
  13704. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13705. }
  13706. if (this.attachedElement) {
  13707. input.attachControl(this.attachedElement);
  13708. }
  13709. };
  13710. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13711. for (var cam in this.attached) {
  13712. var input = this.attached[cam];
  13713. if (input === inputToRemove) {
  13714. input.detachControl(this.attachedElement);
  13715. delete this.attached[cam];
  13716. this.rebuildInputCheck();
  13717. }
  13718. }
  13719. };
  13720. CameraInputsManager.prototype.removeByType = function (inputType) {
  13721. for (var cam in this.attached) {
  13722. var input = this.attached[cam];
  13723. if (input.getTypeName() === inputType) {
  13724. input.detachControl(this.attachedElement);
  13725. delete this.attached[cam];
  13726. this.rebuildInputCheck();
  13727. }
  13728. }
  13729. };
  13730. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13731. var current = this.checkInputs;
  13732. return function () {
  13733. current();
  13734. fn();
  13735. };
  13736. };
  13737. CameraInputsManager.prototype.attachInput = function (input) {
  13738. input.attachControl(this.attachedElement, this.noPreventDefault);
  13739. };
  13740. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13741. if (this.attachedElement) {
  13742. return;
  13743. }
  13744. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13745. this.attachedElement = element;
  13746. this.noPreventDefault = noPreventDefault;
  13747. for (var cam in this.attached) {
  13748. var input = this.attached[cam];
  13749. this.attached[cam].attachControl(element, noPreventDefault);
  13750. }
  13751. };
  13752. CameraInputsManager.prototype.detachElement = function (element) {
  13753. if (this.attachedElement !== element) {
  13754. return;
  13755. }
  13756. for (var cam in this.attached) {
  13757. var input = this.attached[cam];
  13758. this.attached[cam].detachControl(element);
  13759. }
  13760. this.attachedElement = null;
  13761. };
  13762. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13763. this.checkInputs = function () { };
  13764. for (var cam in this.attached) {
  13765. var input = this.attached[cam];
  13766. if (input.checkInputs) {
  13767. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13768. }
  13769. }
  13770. };
  13771. CameraInputsManager.prototype.clear = function () {
  13772. if (this.attachedElement) {
  13773. this.detachElement(this.attachedElement);
  13774. }
  13775. this.attached = {};
  13776. this.attachedElement = null;
  13777. this.checkInputs = function () { };
  13778. };
  13779. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13780. var inputs = {};
  13781. for (var cam in this.attached) {
  13782. var input = this.attached[cam];
  13783. var res = BABYLON.SerializationHelper.Serialize(input);
  13784. inputs[input.getTypeName()] = res;
  13785. }
  13786. serializedCamera.inputsmgr = inputs;
  13787. };
  13788. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13789. var parsedInputs = parsedCamera.inputsmgr;
  13790. if (parsedInputs) {
  13791. this.clear();
  13792. for (var n in parsedInputs) {
  13793. var construct = BABYLON.CameraInputTypes[n];
  13794. if (construct) {
  13795. var parsedinput = parsedInputs[n];
  13796. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13797. this.add(input);
  13798. }
  13799. }
  13800. }
  13801. else {
  13802. //2016-03-08 this part is for managing backward compatibility
  13803. for (var n in this.attached) {
  13804. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13805. if (construct) {
  13806. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13807. this.remove(this.attached[n]);
  13808. this.add(input);
  13809. }
  13810. }
  13811. }
  13812. };
  13813. return CameraInputsManager;
  13814. }());
  13815. BABYLON.CameraInputsManager = CameraInputsManager;
  13816. })(BABYLON || (BABYLON = {}));
  13817. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13818. var BABYLON;
  13819. (function (BABYLON) {
  13820. var FreeCameraMouseInput = (function () {
  13821. function FreeCameraMouseInput(touchEnabled) {
  13822. if (touchEnabled === void 0) { touchEnabled = true; }
  13823. this.touchEnabled = touchEnabled;
  13824. this.buttons = [0, 1, 2];
  13825. this.angularSensibility = 2000.0;
  13826. }
  13827. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13828. var _this = this;
  13829. var engine = this.camera.getEngine();
  13830. if (!this._pointerInput) {
  13831. this._pointerInput = function (p, s) {
  13832. var evt = p.event;
  13833. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13834. return;
  13835. }
  13836. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13837. return;
  13838. }
  13839. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13840. try {
  13841. evt.srcElement.setPointerCapture(evt.pointerId);
  13842. }
  13843. catch (e) {
  13844. }
  13845. _this.previousPosition = {
  13846. x: evt.clientX,
  13847. y: evt.clientY
  13848. };
  13849. if (!noPreventDefault) {
  13850. evt.preventDefault();
  13851. element.focus();
  13852. }
  13853. }
  13854. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13855. try {
  13856. evt.srcElement.releasePointerCapture(evt.pointerId);
  13857. }
  13858. catch (e) {
  13859. }
  13860. _this.previousPosition = null;
  13861. if (!noPreventDefault) {
  13862. evt.preventDefault();
  13863. }
  13864. }
  13865. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13866. if (!_this.previousPosition || engine.isPointerLock) {
  13867. return;
  13868. }
  13869. var offsetX = evt.clientX - _this.previousPosition.x;
  13870. var offsetY = evt.clientY - _this.previousPosition.y;
  13871. if (_this.camera.getScene().useRightHandedSystem) {
  13872. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13873. }
  13874. else {
  13875. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13876. }
  13877. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13878. _this.previousPosition = {
  13879. x: evt.clientX,
  13880. y: evt.clientY
  13881. };
  13882. if (!noPreventDefault) {
  13883. evt.preventDefault();
  13884. }
  13885. }
  13886. };
  13887. }
  13888. this._onMouseMove = function (evt) {
  13889. if (!engine.isPointerLock) {
  13890. return;
  13891. }
  13892. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13893. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13894. if (_this.camera.getScene().useRightHandedSystem) {
  13895. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13896. }
  13897. else {
  13898. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13899. }
  13900. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13901. _this.previousPosition = null;
  13902. if (!noPreventDefault) {
  13903. evt.preventDefault();
  13904. }
  13905. };
  13906. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13907. element.addEventListener("mousemove", this._onMouseMove, false);
  13908. };
  13909. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13910. if (this._observer && element) {
  13911. this.camera.getScene().onPointerObservable.remove(this._observer);
  13912. element.removeEventListener("mousemove", this._onMouseMove);
  13913. this._observer = null;
  13914. this._onMouseMove = null;
  13915. this.previousPosition = null;
  13916. }
  13917. };
  13918. FreeCameraMouseInput.prototype.getTypeName = function () {
  13919. return "FreeCameraMouseInput";
  13920. };
  13921. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13922. return "mouse";
  13923. };
  13924. return FreeCameraMouseInput;
  13925. }());
  13926. __decorate([
  13927. BABYLON.serialize()
  13928. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13929. __decorate([
  13930. BABYLON.serialize()
  13931. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13932. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13933. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13934. })(BABYLON || (BABYLON = {}));
  13935. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  13936. var BABYLON;
  13937. (function (BABYLON) {
  13938. var FreeCameraKeyboardMoveInput = (function () {
  13939. function FreeCameraKeyboardMoveInput() {
  13940. this._keys = [];
  13941. this.keysUp = [38];
  13942. this.keysDown = [40];
  13943. this.keysLeft = [37];
  13944. this.keysRight = [39];
  13945. }
  13946. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13947. var _this = this;
  13948. if (!this._onKeyDown) {
  13949. element.tabIndex = 1;
  13950. this._onKeyDown = function (evt) {
  13951. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13952. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13953. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13954. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13955. var index = _this._keys.indexOf(evt.keyCode);
  13956. if (index === -1) {
  13957. _this._keys.push(evt.keyCode);
  13958. }
  13959. if (!noPreventDefault) {
  13960. evt.preventDefault();
  13961. }
  13962. }
  13963. };
  13964. this._onKeyUp = function (evt) {
  13965. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13966. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13967. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13968. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13969. var index = _this._keys.indexOf(evt.keyCode);
  13970. if (index >= 0) {
  13971. _this._keys.splice(index, 1);
  13972. }
  13973. if (!noPreventDefault) {
  13974. evt.preventDefault();
  13975. }
  13976. }
  13977. };
  13978. element.addEventListener("keydown", this._onKeyDown, false);
  13979. element.addEventListener("keyup", this._onKeyUp, false);
  13980. BABYLON.Tools.RegisterTopRootEvents([
  13981. { name: "blur", handler: this._onLostFocus }
  13982. ]);
  13983. }
  13984. };
  13985. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13986. if (this._onKeyDown) {
  13987. element.removeEventListener("keydown", this._onKeyDown);
  13988. element.removeEventListener("keyup", this._onKeyUp);
  13989. BABYLON.Tools.UnregisterTopRootEvents([
  13990. { name: "blur", handler: this._onLostFocus }
  13991. ]);
  13992. this._keys = [];
  13993. this._onKeyDown = null;
  13994. this._onKeyUp = null;
  13995. }
  13996. };
  13997. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13998. if (this._onKeyDown) {
  13999. var camera = this.camera;
  14000. // Keyboard
  14001. for (var index = 0; index < this._keys.length; index++) {
  14002. var keyCode = this._keys[index];
  14003. var speed = camera._computeLocalCameraSpeed();
  14004. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14005. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14006. }
  14007. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14008. camera._localDirection.copyFromFloats(0, 0, speed);
  14009. }
  14010. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14011. camera._localDirection.copyFromFloats(speed, 0, 0);
  14012. }
  14013. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14014. camera._localDirection.copyFromFloats(0, 0, -speed);
  14015. }
  14016. if (camera.getScene().useRightHandedSystem) {
  14017. camera._localDirection.z *= -1;
  14018. }
  14019. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14020. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14021. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14022. }
  14023. }
  14024. };
  14025. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14026. return "FreeCameraKeyboardMoveInput";
  14027. };
  14028. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14029. this._keys = [];
  14030. };
  14031. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14032. return "keyboard";
  14033. };
  14034. return FreeCameraKeyboardMoveInput;
  14035. }());
  14036. __decorate([
  14037. BABYLON.serialize()
  14038. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14039. __decorate([
  14040. BABYLON.serialize()
  14041. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14042. __decorate([
  14043. BABYLON.serialize()
  14044. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14045. __decorate([
  14046. BABYLON.serialize()
  14047. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14048. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14049. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14050. })(BABYLON || (BABYLON = {}));
  14051. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14052. var BABYLON;
  14053. (function (BABYLON) {
  14054. var FreeCameraTouchInput = (function () {
  14055. function FreeCameraTouchInput() {
  14056. this._offsetX = null;
  14057. this._offsetY = null;
  14058. this._pointerCount = 0;
  14059. this._pointerPressed = [];
  14060. this.touchAngularSensibility = 200000.0;
  14061. this.touchMoveSensibility = 250.0;
  14062. }
  14063. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14064. var _this = this;
  14065. var previousPosition;
  14066. if (this._pointerInput === undefined) {
  14067. this._onLostFocus = function (evt) {
  14068. _this._offsetX = null;
  14069. _this._offsetY = null;
  14070. };
  14071. this._pointerInput = function (p, s) {
  14072. var evt = p.event;
  14073. if (evt.pointerType === "mouse") {
  14074. return;
  14075. }
  14076. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14077. if (!noPreventDefault) {
  14078. evt.preventDefault();
  14079. }
  14080. _this._pointerPressed.push(evt.pointerId);
  14081. if (_this._pointerPressed.length !== 1) {
  14082. return;
  14083. }
  14084. previousPosition = {
  14085. x: evt.clientX,
  14086. y: evt.clientY
  14087. };
  14088. }
  14089. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14090. if (!noPreventDefault) {
  14091. evt.preventDefault();
  14092. }
  14093. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14094. if (index === -1) {
  14095. return;
  14096. }
  14097. _this._pointerPressed.splice(index, 1);
  14098. if (index != 0) {
  14099. return;
  14100. }
  14101. previousPosition = null;
  14102. _this._offsetX = null;
  14103. _this._offsetY = null;
  14104. }
  14105. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14106. if (!noPreventDefault) {
  14107. evt.preventDefault();
  14108. }
  14109. if (!previousPosition) {
  14110. return;
  14111. }
  14112. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14113. if (index != 0) {
  14114. return;
  14115. }
  14116. _this._offsetX = evt.clientX - previousPosition.x;
  14117. _this._offsetY = -(evt.clientY - previousPosition.y);
  14118. }
  14119. };
  14120. }
  14121. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14122. element.addEventListener("blur", this._onLostFocus);
  14123. };
  14124. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14125. if (this._pointerInput && element) {
  14126. this.camera.getScene().onPointerObservable.remove(this._observer);
  14127. this._observer = null;
  14128. element.removeEventListener("blur", this._onLostFocus);
  14129. this._onLostFocus = null;
  14130. this._pointerPressed = [];
  14131. this._offsetX = null;
  14132. this._offsetY = null;
  14133. this._pointerCount = 0;
  14134. }
  14135. };
  14136. FreeCameraTouchInput.prototype.checkInputs = function () {
  14137. if (this._offsetX) {
  14138. var camera = this.camera;
  14139. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14140. if (this._pointerPressed.length > 1) {
  14141. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14142. }
  14143. else {
  14144. var speed = camera._computeLocalCameraSpeed();
  14145. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14146. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14147. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14148. }
  14149. }
  14150. };
  14151. FreeCameraTouchInput.prototype.getTypeName = function () {
  14152. return "FreeCameraTouchInput";
  14153. };
  14154. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14155. return "touch";
  14156. };
  14157. return FreeCameraTouchInput;
  14158. }());
  14159. __decorate([
  14160. BABYLON.serialize()
  14161. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14162. __decorate([
  14163. BABYLON.serialize()
  14164. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14165. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14166. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14167. })(BABYLON || (BABYLON = {}));
  14168. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14169. var BABYLON;
  14170. (function (BABYLON) {
  14171. var FreeCameraDeviceOrientationInput = (function () {
  14172. function FreeCameraDeviceOrientationInput() {
  14173. var _this = this;
  14174. this._screenOrientationAngle = 0;
  14175. this._screenQuaternion = new BABYLON.Quaternion();
  14176. this._alpha = 0;
  14177. this._beta = 0;
  14178. this._gamma = 0;
  14179. this._orientationChanged = function () {
  14180. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14181. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14182. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14183. };
  14184. this._deviceOrientation = function (evt) {
  14185. _this._alpha = evt.alpha;
  14186. _this._beta = evt.beta;
  14187. _this._gamma = evt.gamma;
  14188. };
  14189. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14190. this._orientationChanged();
  14191. }
  14192. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14193. get: function () {
  14194. return this._camera;
  14195. },
  14196. set: function (camera) {
  14197. this._camera = camera;
  14198. if (!this._camera.rotationQuaternion)
  14199. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14200. },
  14201. enumerable: true,
  14202. configurable: true
  14203. });
  14204. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14205. window.addEventListener("orientationchange", this._orientationChanged);
  14206. window.addEventListener("deviceorientation", this._deviceOrientation);
  14207. //In certain cases, the attach control is called AFTER orientation was changed,
  14208. //So this is needed.
  14209. this._orientationChanged();
  14210. };
  14211. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14212. window.removeEventListener("orientationchange", this._orientationChanged);
  14213. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14214. };
  14215. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14216. //if no device orientation provided, don't update the rotation.
  14217. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14218. if (!this._alpha)
  14219. return;
  14220. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14221. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14222. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14223. //Mirror on XY Plane
  14224. this._camera.rotationQuaternion.z *= -1;
  14225. this._camera.rotationQuaternion.w *= -1;
  14226. };
  14227. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14228. return "FreeCameraDeviceOrientationInput";
  14229. };
  14230. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14231. return "deviceOrientation";
  14232. };
  14233. return FreeCameraDeviceOrientationInput;
  14234. }());
  14235. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14236. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14237. })(BABYLON || (BABYLON = {}));
  14238. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14239. var BABYLON;
  14240. (function (BABYLON) {
  14241. var FreeCameraGamepadInput = (function () {
  14242. function FreeCameraGamepadInput() {
  14243. this.gamepadAngularSensibility = 200;
  14244. this.gamepadMoveSensibility = 40;
  14245. }
  14246. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14247. var _this = this;
  14248. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14249. };
  14250. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14251. if (this._gamepads) {
  14252. this._gamepads.dispose();
  14253. }
  14254. this.gamepad = null;
  14255. };
  14256. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14257. if (this.gamepad) {
  14258. var camera = this.camera;
  14259. var LSValues = this.gamepad.leftStick;
  14260. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14261. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14262. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14263. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14264. var RSValues = this.gamepad.rightStick;
  14265. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14266. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14267. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14268. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14269. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14270. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14271. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14272. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14273. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14274. }
  14275. };
  14276. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14277. // Only the first gamepad can control the camera
  14278. if (gamepad.index === 0) {
  14279. this.gamepad = gamepad;
  14280. }
  14281. };
  14282. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14283. return "FreeCameraGamepadInput";
  14284. };
  14285. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14286. return "gamepad";
  14287. };
  14288. return FreeCameraGamepadInput;
  14289. }());
  14290. __decorate([
  14291. BABYLON.serialize()
  14292. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14293. __decorate([
  14294. BABYLON.serialize()
  14295. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14296. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14297. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14298. })(BABYLON || (BABYLON = {}));
  14299. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14300. var BABYLON;
  14301. (function (BABYLON) {
  14302. var ArcRotateCameraKeyboardMoveInput = (function () {
  14303. function ArcRotateCameraKeyboardMoveInput() {
  14304. this._keys = [];
  14305. this.keysUp = [38];
  14306. this.keysDown = [40];
  14307. this.keysLeft = [37];
  14308. this.keysRight = [39];
  14309. }
  14310. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14311. var _this = this;
  14312. element.tabIndex = 1;
  14313. this._onKeyDown = function (evt) {
  14314. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14315. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14316. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14317. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14318. var index = _this._keys.indexOf(evt.keyCode);
  14319. if (index === -1) {
  14320. _this._keys.push(evt.keyCode);
  14321. }
  14322. if (evt.preventDefault) {
  14323. if (!noPreventDefault) {
  14324. evt.preventDefault();
  14325. }
  14326. }
  14327. }
  14328. };
  14329. this._onKeyUp = function (evt) {
  14330. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14331. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14332. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14333. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14334. var index = _this._keys.indexOf(evt.keyCode);
  14335. if (index >= 0) {
  14336. _this._keys.splice(index, 1);
  14337. }
  14338. if (evt.preventDefault) {
  14339. if (!noPreventDefault) {
  14340. evt.preventDefault();
  14341. }
  14342. }
  14343. }
  14344. };
  14345. this._onLostFocus = function () {
  14346. _this._keys = [];
  14347. };
  14348. element.addEventListener("keydown", this._onKeyDown, false);
  14349. element.addEventListener("keyup", this._onKeyUp, false);
  14350. BABYLON.Tools.RegisterTopRootEvents([
  14351. { name: "blur", handler: this._onLostFocus }
  14352. ]);
  14353. };
  14354. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14355. if (element) {
  14356. element.removeEventListener("keydown", this._onKeyDown);
  14357. element.removeEventListener("keyup", this._onKeyUp);
  14358. }
  14359. BABYLON.Tools.UnregisterTopRootEvents([
  14360. { name: "blur", handler: this._onLostFocus }
  14361. ]);
  14362. this._keys = [];
  14363. this._onKeyDown = null;
  14364. this._onKeyUp = null;
  14365. this._onLostFocus = null;
  14366. };
  14367. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14368. if (this._onKeyDown) {
  14369. var camera = this.camera;
  14370. for (var index = 0; index < this._keys.length; index++) {
  14371. var keyCode = this._keys[index];
  14372. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14373. camera.inertialAlphaOffset -= 0.01;
  14374. }
  14375. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14376. camera.inertialBetaOffset -= 0.01;
  14377. }
  14378. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14379. camera.inertialAlphaOffset += 0.01;
  14380. }
  14381. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14382. camera.inertialBetaOffset += 0.01;
  14383. }
  14384. }
  14385. }
  14386. };
  14387. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14388. return "ArcRotateCameraKeyboardMoveInput";
  14389. };
  14390. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14391. return "keyboard";
  14392. };
  14393. return ArcRotateCameraKeyboardMoveInput;
  14394. }());
  14395. __decorate([
  14396. BABYLON.serialize()
  14397. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14398. __decorate([
  14399. BABYLON.serialize()
  14400. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14401. __decorate([
  14402. BABYLON.serialize()
  14403. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14404. __decorate([
  14405. BABYLON.serialize()
  14406. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14407. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14408. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14409. })(BABYLON || (BABYLON = {}));
  14410. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14411. var BABYLON;
  14412. (function (BABYLON) {
  14413. var ArcRotateCameraMouseWheelInput = (function () {
  14414. function ArcRotateCameraMouseWheelInput() {
  14415. this.wheelPrecision = 3.0;
  14416. }
  14417. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14418. var _this = this;
  14419. this._wheel = function (p, s) {
  14420. //sanity check - this should be a PointerWheel event.
  14421. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14422. return;
  14423. var event = p.event;
  14424. var delta = 0;
  14425. if (event.wheelDelta) {
  14426. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14427. }
  14428. else if (event.detail) {
  14429. delta = -event.detail / _this.wheelPrecision;
  14430. }
  14431. if (delta)
  14432. _this.camera.inertialRadiusOffset += delta;
  14433. if (event.preventDefault) {
  14434. if (!noPreventDefault) {
  14435. event.preventDefault();
  14436. }
  14437. }
  14438. };
  14439. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14440. };
  14441. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14442. if (this._observer && element) {
  14443. this.camera.getScene().onPointerObservable.remove(this._observer);
  14444. this._observer = null;
  14445. this._wheel = null;
  14446. }
  14447. };
  14448. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14449. return "ArcRotateCameraMouseWheelInput";
  14450. };
  14451. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14452. return "mousewheel";
  14453. };
  14454. return ArcRotateCameraMouseWheelInput;
  14455. }());
  14456. __decorate([
  14457. BABYLON.serialize()
  14458. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14459. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14460. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14461. })(BABYLON || (BABYLON = {}));
  14462. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14463. var BABYLON;
  14464. (function (BABYLON) {
  14465. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14466. var ArcRotateCameraPointersInput = (function () {
  14467. function ArcRotateCameraPointersInput() {
  14468. this.buttons = [0, 1, 2];
  14469. this.angularSensibilityX = 1000.0;
  14470. this.angularSensibilityY = 1000.0;
  14471. this.pinchPrecision = 6.0;
  14472. this.panningSensibility = 50.0;
  14473. this._isPanClick = false;
  14474. this.pinchInwards = true;
  14475. }
  14476. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14477. var _this = this;
  14478. var engine = this.camera.getEngine();
  14479. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14480. var pointA, pointB;
  14481. var previousPinchDistance = 0;
  14482. this._pointerInput = function (p, s) {
  14483. var evt = p.event;
  14484. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14485. return;
  14486. }
  14487. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14488. try {
  14489. evt.srcElement.setPointerCapture(evt.pointerId);
  14490. }
  14491. catch (e) {
  14492. }
  14493. // Manage panning with pan button click
  14494. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14495. // manage pointers
  14496. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14497. if (pointA === undefined) {
  14498. pointA = cacheSoloPointer;
  14499. }
  14500. else if (pointB === undefined) {
  14501. pointB = cacheSoloPointer;
  14502. }
  14503. if (!noPreventDefault) {
  14504. evt.preventDefault();
  14505. element.focus();
  14506. }
  14507. }
  14508. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14509. try {
  14510. evt.srcElement.releasePointerCapture(evt.pointerId);
  14511. }
  14512. catch (e) {
  14513. }
  14514. cacheSoloPointer = null;
  14515. previousPinchDistance = 0;
  14516. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14517. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14518. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14519. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14520. pointA = pointB = undefined;
  14521. if (!noPreventDefault) {
  14522. evt.preventDefault();
  14523. }
  14524. }
  14525. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14526. if (!noPreventDefault) {
  14527. evt.preventDefault();
  14528. }
  14529. // One button down
  14530. if (pointA && pointB === undefined) {
  14531. if (_this.panningSensibility !== 0 &&
  14532. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14533. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14534. _this.camera
  14535. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14536. _this.camera
  14537. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14538. }
  14539. else {
  14540. var offsetX = evt.clientX - cacheSoloPointer.x;
  14541. var offsetY = evt.clientY - cacheSoloPointer.y;
  14542. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14543. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14544. }
  14545. cacheSoloPointer.x = evt.clientX;
  14546. cacheSoloPointer.y = evt.clientY;
  14547. }
  14548. else if (pointA && pointB) {
  14549. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14550. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14551. ed.x = evt.clientX;
  14552. ed.y = evt.clientY;
  14553. var direction = _this.pinchInwards ? 1 : -1;
  14554. var distX = pointA.x - pointB.x;
  14555. var distY = pointA.y - pointB.y;
  14556. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14557. if (previousPinchDistance === 0) {
  14558. previousPinchDistance = pinchSquaredDistance;
  14559. return;
  14560. }
  14561. if (pinchSquaredDistance !== previousPinchDistance) {
  14562. _this.camera
  14563. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14564. (_this.pinchPrecision *
  14565. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14566. direction);
  14567. previousPinchDistance = pinchSquaredDistance;
  14568. }
  14569. }
  14570. }
  14571. };
  14572. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14573. this._onContextMenu = function (evt) {
  14574. evt.preventDefault();
  14575. };
  14576. if (!this.camera._useCtrlForPanning) {
  14577. element.addEventListener("contextmenu", this._onContextMenu, false);
  14578. }
  14579. this._onLostFocus = function () {
  14580. //this._keys = [];
  14581. pointA = pointB = undefined;
  14582. previousPinchDistance = 0;
  14583. cacheSoloPointer = null;
  14584. };
  14585. this._onMouseMove = function (evt) {
  14586. if (!engine.isPointerLock) {
  14587. return;
  14588. }
  14589. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14590. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14591. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14592. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14593. if (!noPreventDefault) {
  14594. evt.preventDefault();
  14595. }
  14596. };
  14597. this._onGestureStart = function (e) {
  14598. if (window.MSGesture === undefined) {
  14599. return;
  14600. }
  14601. if (!_this._MSGestureHandler) {
  14602. _this._MSGestureHandler = new MSGesture();
  14603. _this._MSGestureHandler.target = element;
  14604. }
  14605. _this._MSGestureHandler.addPointer(e.pointerId);
  14606. };
  14607. this._onGesture = function (e) {
  14608. _this.camera.radius *= e.scale;
  14609. if (e.preventDefault) {
  14610. if (!noPreventDefault) {
  14611. e.stopPropagation();
  14612. e.preventDefault();
  14613. }
  14614. }
  14615. };
  14616. element.addEventListener("mousemove", this._onMouseMove, false);
  14617. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14618. element.addEventListener("MSGestureChange", this._onGesture, false);
  14619. element.addEventListener("keydown", this._onKeyDown, false);
  14620. element.addEventListener("keyup", this._onKeyUp, false);
  14621. BABYLON.Tools.RegisterTopRootEvents([
  14622. { name: "blur", handler: this._onLostFocus }
  14623. ]);
  14624. };
  14625. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14626. if (element && this._observer) {
  14627. this.camera.getScene().onPointerObservable.remove(this._observer);
  14628. this._observer = null;
  14629. element.removeEventListener("contextmenu", this._onContextMenu);
  14630. element.removeEventListener("mousemove", this._onMouseMove);
  14631. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14632. element.removeEventListener("MSGestureChange", this._onGesture);
  14633. element.removeEventListener("keydown", this._onKeyDown);
  14634. element.removeEventListener("keyup", this._onKeyUp);
  14635. this._isPanClick = false;
  14636. this.pinchInwards = true;
  14637. this._onKeyDown = null;
  14638. this._onKeyUp = null;
  14639. this._onMouseMove = null;
  14640. this._onGestureStart = null;
  14641. this._onGesture = null;
  14642. this._MSGestureHandler = null;
  14643. this._onLostFocus = null;
  14644. this._onContextMenu = null;
  14645. }
  14646. BABYLON.Tools.UnregisterTopRootEvents([
  14647. { name: "blur", handler: this._onLostFocus }
  14648. ]);
  14649. };
  14650. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14651. return "ArcRotateCameraPointersInput";
  14652. };
  14653. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14654. return "pointers";
  14655. };
  14656. return ArcRotateCameraPointersInput;
  14657. }());
  14658. __decorate([
  14659. BABYLON.serialize()
  14660. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14661. __decorate([
  14662. BABYLON.serialize()
  14663. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14670. __decorate([
  14671. BABYLON.serialize()
  14672. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14673. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14674. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14675. })(BABYLON || (BABYLON = {}));
  14676. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14677. var BABYLON;
  14678. (function (BABYLON) {
  14679. var ArcRotateCameraGamepadInput = (function () {
  14680. function ArcRotateCameraGamepadInput() {
  14681. this.gamepadRotationSensibility = 80;
  14682. this.gamepadMoveSensibility = 40;
  14683. }
  14684. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14685. var _this = this;
  14686. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14687. };
  14688. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14689. if (this._gamepads) {
  14690. this._gamepads.dispose();
  14691. }
  14692. this.gamepad = null;
  14693. };
  14694. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14695. if (this.gamepad) {
  14696. var camera = this.camera;
  14697. var RSValues = this.gamepad.rightStick;
  14698. if (RSValues.x != 0) {
  14699. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14700. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14701. camera.inertialAlphaOffset += normalizedRX;
  14702. }
  14703. }
  14704. if (RSValues.y != 0) {
  14705. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14706. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14707. camera.inertialBetaOffset += normalizedRY;
  14708. }
  14709. }
  14710. var LSValues = this.gamepad.leftStick;
  14711. if (LSValues.y != 0) {
  14712. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14713. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14714. this.camera.inertialRadiusOffset -= normalizedLY;
  14715. }
  14716. }
  14717. }
  14718. };
  14719. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14720. // Only the first gamepad can control the camera
  14721. if (gamepad.index === 0) {
  14722. this.gamepad = gamepad;
  14723. }
  14724. };
  14725. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14726. return "ArcRotateCameraGamepadInput";
  14727. };
  14728. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14729. return "gamepad";
  14730. };
  14731. return ArcRotateCameraGamepadInput;
  14732. }());
  14733. __decorate([
  14734. BABYLON.serialize()
  14735. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14736. __decorate([
  14737. BABYLON.serialize()
  14738. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14739. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14740. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14741. })(BABYLON || (BABYLON = {}));
  14742. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14743. var BABYLON;
  14744. (function (BABYLON) {
  14745. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14746. function ArcRotateCameraVRDeviceOrientationInput() {
  14747. this.alphaCorrection = 1;
  14748. this.betaCorrection = 1;
  14749. this.gammaCorrection = 1;
  14750. this._alpha = 0;
  14751. this._beta = 0;
  14752. this._gamma = 0;
  14753. this._dirty = false;
  14754. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14755. }
  14756. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14757. this.camera.attachControl(element, noPreventDefault);
  14758. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14759. };
  14760. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14761. var camera = this.camera;
  14762. this._alpha = +evt.alpha | 0;
  14763. this._beta = +evt.beta | 0;
  14764. this._gamma = +evt.gamma | 0;
  14765. this._dirty = true;
  14766. };
  14767. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14768. if (this._dirty) {
  14769. this._dirty = false;
  14770. if (this._gamma < 0) {
  14771. this._gamma = 180 + this._gamma;
  14772. }
  14773. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14774. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14775. }
  14776. };
  14777. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14778. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14779. };
  14780. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14781. return "ArcRotateCameraVRDeviceOrientationInput";
  14782. };
  14783. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14784. return "VRDeviceOrientation";
  14785. };
  14786. return ArcRotateCameraVRDeviceOrientationInput;
  14787. }());
  14788. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14789. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14790. })(BABYLON || (BABYLON = {}));
  14791. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14792. var BABYLON;
  14793. (function (BABYLON) {
  14794. var TargetCamera = (function (_super) {
  14795. __extends(TargetCamera, _super);
  14796. function TargetCamera(name, position, scene) {
  14797. var _this = _super.call(this, name, position, scene) || this;
  14798. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14799. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  14800. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  14801. _this.speed = 2.0;
  14802. _this.noRotationConstraint = false;
  14803. _this.lockedTarget = null;
  14804. _this._currentTarget = BABYLON.Vector3.Zero();
  14805. _this._viewMatrix = BABYLON.Matrix.Zero();
  14806. _this._camMatrix = BABYLON.Matrix.Zero();
  14807. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14808. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14809. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14810. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14811. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14812. _this._lookAtTemp = BABYLON.Matrix.Zero();
  14813. _this._tempMatrix = BABYLON.Matrix.Zero();
  14814. return _this;
  14815. }
  14816. TargetCamera.prototype.getFrontPosition = function (distance) {
  14817. var direction = this.getTarget().subtract(this.position);
  14818. direction.normalize();
  14819. direction.scaleInPlace(distance);
  14820. return this.globalPosition.add(direction);
  14821. };
  14822. TargetCamera.prototype._getLockedTargetPosition = function () {
  14823. if (!this.lockedTarget) {
  14824. return null;
  14825. }
  14826. if (this.lockedTarget.absolutePosition) {
  14827. this.lockedTarget.computeWorldMatrix();
  14828. }
  14829. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14830. };
  14831. // Cache
  14832. TargetCamera.prototype._initCache = function () {
  14833. _super.prototype._initCache.call(this);
  14834. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14835. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14836. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14837. };
  14838. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14839. if (!ignoreParentClass) {
  14840. _super.prototype._updateCache.call(this);
  14841. }
  14842. var lockedTargetPosition = this._getLockedTargetPosition();
  14843. if (!lockedTargetPosition) {
  14844. this._cache.lockedTarget = null;
  14845. }
  14846. else {
  14847. if (!this._cache.lockedTarget) {
  14848. this._cache.lockedTarget = lockedTargetPosition.clone();
  14849. }
  14850. else {
  14851. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14852. }
  14853. }
  14854. this._cache.rotation.copyFrom(this.rotation);
  14855. if (this.rotationQuaternion)
  14856. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14857. };
  14858. // Synchronized
  14859. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14860. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14861. return false;
  14862. }
  14863. var lockedTargetPosition = this._getLockedTargetPosition();
  14864. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14865. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14866. };
  14867. // Methods
  14868. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14869. var engine = this.getEngine();
  14870. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14871. };
  14872. // Target
  14873. TargetCamera.prototype.setTarget = function (target) {
  14874. this.upVector.normalize();
  14875. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14876. this._camMatrix.invert();
  14877. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14878. var vDir = target.subtract(this.position);
  14879. if (vDir.x >= 0.0) {
  14880. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14881. }
  14882. else {
  14883. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14884. }
  14885. this.rotation.z = 0;
  14886. if (isNaN(this.rotation.x)) {
  14887. this.rotation.x = 0;
  14888. }
  14889. if (isNaN(this.rotation.y)) {
  14890. this.rotation.y = 0;
  14891. }
  14892. if (isNaN(this.rotation.z)) {
  14893. this.rotation.z = 0;
  14894. }
  14895. if (this.rotationQuaternion) {
  14896. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14897. }
  14898. };
  14899. TargetCamera.prototype.getTarget = function () {
  14900. return this._currentTarget;
  14901. };
  14902. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14903. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14904. };
  14905. TargetCamera.prototype._updatePosition = function () {
  14906. this.position.addInPlace(this.cameraDirection);
  14907. };
  14908. TargetCamera.prototype._checkInputs = function () {
  14909. var needToMove = this._decideIfNeedsToMove();
  14910. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14911. // Move
  14912. if (needToMove) {
  14913. this._updatePosition();
  14914. }
  14915. // Rotate
  14916. if (needToRotate) {
  14917. this.rotation.x += this.cameraRotation.x;
  14918. this.rotation.y += this.cameraRotation.y;
  14919. if (!this.noRotationConstraint) {
  14920. var limit = (Math.PI / 2) * 0.95;
  14921. if (this.rotation.x > limit)
  14922. this.rotation.x = limit;
  14923. if (this.rotation.x < -limit)
  14924. this.rotation.x = -limit;
  14925. }
  14926. }
  14927. // Inertia
  14928. if (needToMove) {
  14929. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14930. this.cameraDirection.x = 0;
  14931. }
  14932. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14933. this.cameraDirection.y = 0;
  14934. }
  14935. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14936. this.cameraDirection.z = 0;
  14937. }
  14938. this.cameraDirection.scaleInPlace(this.inertia);
  14939. }
  14940. if (needToRotate) {
  14941. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14942. this.cameraRotation.x = 0;
  14943. }
  14944. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14945. this.cameraRotation.y = 0;
  14946. }
  14947. this.cameraRotation.scaleInPlace(this.inertia);
  14948. }
  14949. _super.prototype._checkInputs.call(this);
  14950. };
  14951. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14952. if (this.rotationQuaternion) {
  14953. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14954. //update the up vector!
  14955. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14956. }
  14957. else {
  14958. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14959. }
  14960. };
  14961. TargetCamera.prototype._getViewMatrix = function () {
  14962. if (!this.lockedTarget) {
  14963. // Compute
  14964. this._updateCameraRotationMatrix();
  14965. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14966. // Computing target and final matrix
  14967. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14968. }
  14969. else {
  14970. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14971. }
  14972. if (this.getScene().useRightHandedSystem) {
  14973. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14974. }
  14975. else {
  14976. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14977. }
  14978. return this._viewMatrix;
  14979. };
  14980. /**
  14981. * @override
  14982. * Override Camera.createRigCamera
  14983. */
  14984. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14985. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14986. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14987. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14988. if (!this.rotationQuaternion) {
  14989. this.rotationQuaternion = new BABYLON.Quaternion();
  14990. }
  14991. rigCamera._cameraRigParams = {};
  14992. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14993. }
  14994. return rigCamera;
  14995. }
  14996. return null;
  14997. };
  14998. /**
  14999. * @override
  15000. * Override Camera._updateRigCameras
  15001. */
  15002. TargetCamera.prototype._updateRigCameras = function () {
  15003. var camLeft = this._rigCameras[0];
  15004. var camRight = this._rigCameras[1];
  15005. switch (this.cameraRigMode) {
  15006. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15007. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15010. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15011. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15012. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15013. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15014. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15015. camLeft.setTarget(this.getTarget());
  15016. camRight.setTarget(this.getTarget());
  15017. break;
  15018. case BABYLON.Camera.RIG_MODE_VR:
  15019. case BABYLON.Camera.RIG_MODE_WEBVR:
  15020. if (camLeft.rotationQuaternion) {
  15021. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15022. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15023. }
  15024. else {
  15025. camLeft.rotation.copyFrom(this.rotation);
  15026. camRight.rotation.copyFrom(this.rotation);
  15027. }
  15028. camLeft.position.copyFrom(this.position);
  15029. camRight.position.copyFrom(this.position);
  15030. break;
  15031. }
  15032. _super.prototype._updateRigCameras.call(this);
  15033. };
  15034. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15035. if (!this._rigCamTransformMatrix) {
  15036. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15037. }
  15038. var target = this.getTarget();
  15039. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15040. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15041. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15042. };
  15043. TargetCamera.prototype.getClassName = function () {
  15044. return "TargetCamera";
  15045. };
  15046. return TargetCamera;
  15047. }(BABYLON.Camera));
  15048. __decorate([
  15049. BABYLON.serializeAsVector3()
  15050. ], TargetCamera.prototype, "rotation", void 0);
  15051. __decorate([
  15052. BABYLON.serialize()
  15053. ], TargetCamera.prototype, "speed", void 0);
  15054. __decorate([
  15055. BABYLON.serializeAsMeshReference("lockedTargetId")
  15056. ], TargetCamera.prototype, "lockedTarget", void 0);
  15057. BABYLON.TargetCamera = TargetCamera;
  15058. })(BABYLON || (BABYLON = {}));
  15059. //# sourceMappingURL=babylon.targetCamera.js.map
  15060. var BABYLON;
  15061. (function (BABYLON) {
  15062. var FreeCamera = (function (_super) {
  15063. __extends(FreeCamera, _super);
  15064. function FreeCamera(name, position, scene) {
  15065. var _this = _super.call(this, name, position, scene) || this;
  15066. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15067. _this.checkCollisions = false;
  15068. _this.applyGravity = false;
  15069. _this._collider = new BABYLON.Collider();
  15070. _this._needMoveForGravity = false;
  15071. _this._oldPosition = BABYLON.Vector3.Zero();
  15072. _this._diffPosition = BABYLON.Vector3.Zero();
  15073. _this._newPosition = BABYLON.Vector3.Zero();
  15074. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15075. if (collidedMesh === void 0) { collidedMesh = null; }
  15076. //TODO move this to the collision coordinator!
  15077. if (_this.getScene().workerCollisions)
  15078. newPosition.multiplyInPlace(_this._collider.radius);
  15079. var updatePosition = function (newPos) {
  15080. _this._newPosition.copyFrom(newPos);
  15081. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15082. var oldPosition = _this.position.clone();
  15083. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15084. _this.position.addInPlace(_this._diffPosition);
  15085. if (_this.onCollide && collidedMesh) {
  15086. _this.onCollide(collidedMesh);
  15087. }
  15088. }
  15089. };
  15090. updatePosition(newPosition);
  15091. };
  15092. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15093. _this.inputs.addKeyboard().addMouse();
  15094. return _this;
  15095. }
  15096. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15097. //-- begin properties for backward compatibility for inputs
  15098. get: function () {
  15099. var mouse = this.inputs.attached["mouse"];
  15100. if (mouse)
  15101. return mouse.angularSensibility;
  15102. },
  15103. set: function (value) {
  15104. var mouse = this.inputs.attached["mouse"];
  15105. if (mouse)
  15106. mouse.angularSensibility = value;
  15107. },
  15108. enumerable: true,
  15109. configurable: true
  15110. });
  15111. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15112. get: function () {
  15113. var keyboard = this.inputs.attached["keyboard"];
  15114. if (keyboard)
  15115. return keyboard.keysUp;
  15116. },
  15117. set: function (value) {
  15118. var keyboard = this.inputs.attached["keyboard"];
  15119. if (keyboard)
  15120. keyboard.keysUp = value;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15126. get: function () {
  15127. var keyboard = this.inputs.attached["keyboard"];
  15128. if (keyboard)
  15129. return keyboard.keysDown;
  15130. },
  15131. set: function (value) {
  15132. var keyboard = this.inputs.attached["keyboard"];
  15133. if (keyboard)
  15134. keyboard.keysDown = value;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15140. get: function () {
  15141. var keyboard = this.inputs.attached["keyboard"];
  15142. if (keyboard)
  15143. return keyboard.keysLeft;
  15144. },
  15145. set: function (value) {
  15146. var keyboard = this.inputs.attached["keyboard"];
  15147. if (keyboard)
  15148. keyboard.keysLeft = value;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15154. get: function () {
  15155. var keyboard = this.inputs.attached["keyboard"];
  15156. if (keyboard)
  15157. return keyboard.keysRight;
  15158. },
  15159. set: function (value) {
  15160. var keyboard = this.inputs.attached["keyboard"];
  15161. if (keyboard)
  15162. keyboard.keysRight = value;
  15163. },
  15164. enumerable: true,
  15165. configurable: true
  15166. });
  15167. // Controls
  15168. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15169. this.inputs.attachElement(element, noPreventDefault);
  15170. };
  15171. FreeCamera.prototype.detachControl = function (element) {
  15172. this.inputs.detachElement(element);
  15173. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15174. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15175. };
  15176. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15177. var globalPosition;
  15178. if (this.parent) {
  15179. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15180. }
  15181. else {
  15182. globalPosition = this.position;
  15183. }
  15184. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15185. this._collider.radius = this.ellipsoid;
  15186. //no need for clone, as long as gravity is not on.
  15187. var actualVelocity = velocity;
  15188. //add gravity to the velocity to prevent the dual-collision checking
  15189. if (this.applyGravity) {
  15190. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15191. actualVelocity = velocity.add(this.getScene().gravity);
  15192. }
  15193. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15194. };
  15195. FreeCamera.prototype._checkInputs = function () {
  15196. if (!this._localDirection) {
  15197. this._localDirection = BABYLON.Vector3.Zero();
  15198. this._transformedDirection = BABYLON.Vector3.Zero();
  15199. }
  15200. this.inputs.checkInputs();
  15201. _super.prototype._checkInputs.call(this);
  15202. };
  15203. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15204. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15205. };
  15206. FreeCamera.prototype._updatePosition = function () {
  15207. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15208. this._collideWithWorld(this.cameraDirection);
  15209. }
  15210. else {
  15211. this.position.addInPlace(this.cameraDirection);
  15212. }
  15213. };
  15214. FreeCamera.prototype.dispose = function () {
  15215. this.inputs.clear();
  15216. _super.prototype.dispose.call(this);
  15217. };
  15218. FreeCamera.prototype.getClassName = function () {
  15219. return "FreeCamera";
  15220. };
  15221. return FreeCamera;
  15222. }(BABYLON.TargetCamera));
  15223. __decorate([
  15224. BABYLON.serializeAsVector3()
  15225. ], FreeCamera.prototype, "ellipsoid", void 0);
  15226. __decorate([
  15227. BABYLON.serialize()
  15228. ], FreeCamera.prototype, "checkCollisions", void 0);
  15229. __decorate([
  15230. BABYLON.serialize()
  15231. ], FreeCamera.prototype, "applyGravity", void 0);
  15232. BABYLON.FreeCamera = FreeCamera;
  15233. })(BABYLON || (BABYLON = {}));
  15234. //# sourceMappingURL=babylon.freeCamera.js.map
  15235. var BABYLON;
  15236. (function (BABYLON) {
  15237. var FreeCameraInputsManager = (function (_super) {
  15238. __extends(FreeCameraInputsManager, _super);
  15239. function FreeCameraInputsManager(camera) {
  15240. return _super.call(this, camera) || this;
  15241. }
  15242. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15243. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15244. return this;
  15245. };
  15246. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15247. if (touchEnabled === void 0) { touchEnabled = true; }
  15248. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15249. return this;
  15250. };
  15251. FreeCameraInputsManager.prototype.addGamepad = function () {
  15252. this.add(new BABYLON.FreeCameraGamepadInput());
  15253. return this;
  15254. };
  15255. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15256. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15257. return this;
  15258. };
  15259. FreeCameraInputsManager.prototype.addTouch = function () {
  15260. this.add(new BABYLON.FreeCameraTouchInput());
  15261. return this;
  15262. };
  15263. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15264. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15265. return this;
  15266. };
  15267. return FreeCameraInputsManager;
  15268. }(BABYLON.CameraInputsManager));
  15269. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15270. })(BABYLON || (BABYLON = {}));
  15271. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15272. var BABYLON;
  15273. (function (BABYLON) {
  15274. var FollowCamera = (function (_super) {
  15275. __extends(FollowCamera, _super);
  15276. function FollowCamera(name, position, scene, lockedTarget) {
  15277. var _this = _super.call(this, name, position, scene) || this;
  15278. _this.radius = 12;
  15279. _this.rotationOffset = 0;
  15280. _this.heightOffset = 4;
  15281. _this.cameraAcceleration = 0.05;
  15282. _this.maxCameraSpeed = 20;
  15283. _this.lockedTarget = lockedTarget;
  15284. return _this;
  15285. }
  15286. FollowCamera.prototype.getRadians = function (degrees) {
  15287. return degrees * Math.PI / 180;
  15288. };
  15289. FollowCamera.prototype.follow = function (cameraTarget) {
  15290. if (!cameraTarget)
  15291. return;
  15292. var yRotation;
  15293. if (cameraTarget.rotationQuaternion) {
  15294. var rotMatrix = new BABYLON.Matrix();
  15295. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15296. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15297. }
  15298. else {
  15299. yRotation = cameraTarget.rotation.y;
  15300. }
  15301. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15302. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15303. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15304. var dx = targetX - this.position.x;
  15305. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15306. var dz = (targetZ) - this.position.z;
  15307. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15308. var vy = dy * this.cameraAcceleration;
  15309. var vz = dz * this.cameraAcceleration * 2;
  15310. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15311. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15312. }
  15313. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15314. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15315. }
  15316. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15317. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15318. }
  15319. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15320. this.setTarget(cameraTarget.position);
  15321. };
  15322. FollowCamera.prototype._checkInputs = function () {
  15323. _super.prototype._checkInputs.call(this);
  15324. this.follow(this.lockedTarget);
  15325. };
  15326. FollowCamera.prototype.getClassName = function () {
  15327. return "FollowCamera";
  15328. };
  15329. return FollowCamera;
  15330. }(BABYLON.TargetCamera));
  15331. __decorate([
  15332. BABYLON.serialize()
  15333. ], FollowCamera.prototype, "radius", void 0);
  15334. __decorate([
  15335. BABYLON.serialize()
  15336. ], FollowCamera.prototype, "rotationOffset", void 0);
  15337. __decorate([
  15338. BABYLON.serialize()
  15339. ], FollowCamera.prototype, "heightOffset", void 0);
  15340. __decorate([
  15341. BABYLON.serialize()
  15342. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15343. __decorate([
  15344. BABYLON.serialize()
  15345. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15346. __decorate([
  15347. BABYLON.serializeAsMeshReference("lockedTargetId")
  15348. ], FollowCamera.prototype, "lockedTarget", void 0);
  15349. BABYLON.FollowCamera = FollowCamera;
  15350. var ArcFollowCamera = (function (_super) {
  15351. __extends(ArcFollowCamera, _super);
  15352. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15353. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15354. _this.alpha = alpha;
  15355. _this.beta = beta;
  15356. _this.radius = radius;
  15357. _this.target = target;
  15358. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15359. _this.follow();
  15360. return _this;
  15361. }
  15362. ArcFollowCamera.prototype.follow = function () {
  15363. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15364. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15365. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15366. this.position = this.target.position.add(this._cartesianCoordinates);
  15367. this.setTarget(this.target.position);
  15368. };
  15369. ArcFollowCamera.prototype._checkInputs = function () {
  15370. _super.prototype._checkInputs.call(this);
  15371. this.follow();
  15372. };
  15373. ArcFollowCamera.prototype.getClassName = function () {
  15374. return "ArcFollowCamera";
  15375. };
  15376. return ArcFollowCamera;
  15377. }(BABYLON.TargetCamera));
  15378. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15379. })(BABYLON || (BABYLON = {}));
  15380. //# sourceMappingURL=babylon.followCamera.js.map
  15381. var BABYLON;
  15382. (function (BABYLON) {
  15383. // We're mainly based on the logic defined into the FreeCamera code
  15384. var TouchCamera = (function (_super) {
  15385. __extends(TouchCamera, _super);
  15386. //-- end properties for backward compatibility for inputs
  15387. function TouchCamera(name, position, scene) {
  15388. var _this = _super.call(this, name, position, scene) || this;
  15389. _this.inputs.addTouch();
  15390. _this._setupInputs();
  15391. return _this;
  15392. }
  15393. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15394. //-- Begin properties for backward compatibility for inputs
  15395. get: function () {
  15396. var touch = this.inputs.attached["touch"];
  15397. if (touch)
  15398. return touch.touchAngularSensibility;
  15399. },
  15400. set: function (value) {
  15401. var touch = this.inputs.attached["touch"];
  15402. if (touch)
  15403. touch.touchAngularSensibility = value;
  15404. },
  15405. enumerable: true,
  15406. configurable: true
  15407. });
  15408. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15409. get: function () {
  15410. var touch = this.inputs.attached["touch"];
  15411. if (touch)
  15412. return touch.touchMoveSensibility;
  15413. },
  15414. set: function (value) {
  15415. var touch = this.inputs.attached["touch"];
  15416. if (touch)
  15417. touch.touchMoveSensibility = value;
  15418. },
  15419. enumerable: true,
  15420. configurable: true
  15421. });
  15422. TouchCamera.prototype.getClassName = function () {
  15423. return "TouchCamera";
  15424. };
  15425. TouchCamera.prototype._setupInputs = function () {
  15426. var mouse = this.inputs.attached["mouse"];
  15427. if (mouse) {
  15428. mouse.touchEnabled = false;
  15429. }
  15430. };
  15431. return TouchCamera;
  15432. }(BABYLON.FreeCamera));
  15433. BABYLON.TouchCamera = TouchCamera;
  15434. })(BABYLON || (BABYLON = {}));
  15435. //# sourceMappingURL=babylon.touchCamera.js.map
  15436. var BABYLON;
  15437. (function (BABYLON) {
  15438. var ArcRotateCamera = (function (_super) {
  15439. __extends(ArcRotateCamera, _super);
  15440. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15441. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15442. _this.inertialAlphaOffset = 0;
  15443. _this.inertialBetaOffset = 0;
  15444. _this.inertialRadiusOffset = 0;
  15445. _this.lowerAlphaLimit = null;
  15446. _this.upperAlphaLimit = null;
  15447. _this.lowerBetaLimit = 0.01;
  15448. _this.upperBetaLimit = Math.PI;
  15449. _this.lowerRadiusLimit = null;
  15450. _this.upperRadiusLimit = null;
  15451. _this.inertialPanningX = 0;
  15452. _this.inertialPanningY = 0;
  15453. //-- end properties for backward compatibility for inputs
  15454. _this.zoomOnFactor = 1;
  15455. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  15456. _this.allowUpsideDown = true;
  15457. _this._viewMatrix = new BABYLON.Matrix();
  15458. // Panning
  15459. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15460. _this.checkCollisions = false;
  15461. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15462. _this._collider = new BABYLON.Collider();
  15463. _this._previousPosition = BABYLON.Vector3.Zero();
  15464. _this._collisionVelocity = BABYLON.Vector3.Zero();
  15465. _this._newPosition = BABYLON.Vector3.Zero();
  15466. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15467. if (collidedMesh === void 0) { collidedMesh = null; }
  15468. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15469. newPosition.multiplyInPlace(_this._collider.radius);
  15470. }
  15471. if (!collidedMesh) {
  15472. _this._previousPosition.copyFrom(_this.position);
  15473. }
  15474. else {
  15475. _this.setPosition(newPosition);
  15476. if (_this.onCollide) {
  15477. _this.onCollide(collidedMesh);
  15478. }
  15479. }
  15480. // Recompute because of constraints
  15481. var cosa = Math.cos(_this.alpha);
  15482. var sina = Math.sin(_this.alpha);
  15483. var cosb = Math.cos(_this.beta);
  15484. var sinb = Math.sin(_this.beta);
  15485. if (sinb === 0) {
  15486. sinb = 0.0001;
  15487. }
  15488. var target = _this._getTargetPosition();
  15489. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15490. _this.position.copyFrom(_this._newPosition);
  15491. var up = _this.upVector;
  15492. if (_this.allowUpsideDown && _this.beta < 0) {
  15493. up = up.clone();
  15494. up = up.negate();
  15495. }
  15496. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15497. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15498. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15499. _this._collisionTriggered = false;
  15500. };
  15501. if (!target) {
  15502. _this.target = BABYLON.Vector3.Zero();
  15503. }
  15504. else {
  15505. _this.target = target;
  15506. }
  15507. _this.alpha = alpha;
  15508. _this.beta = beta;
  15509. _this.radius = radius;
  15510. _this.getViewMatrix();
  15511. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  15512. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15513. return _this;
  15514. }
  15515. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15516. //-- begin properties for backward compatibility for inputs
  15517. get: function () {
  15518. var pointers = this.inputs.attached["pointers"];
  15519. if (pointers)
  15520. return pointers.angularSensibilityX;
  15521. },
  15522. set: function (value) {
  15523. var pointers = this.inputs.attached["pointers"];
  15524. if (pointers) {
  15525. pointers.angularSensibilityX = value;
  15526. }
  15527. },
  15528. enumerable: true,
  15529. configurable: true
  15530. });
  15531. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15532. get: function () {
  15533. var pointers = this.inputs.attached["pointers"];
  15534. if (pointers)
  15535. return pointers.angularSensibilityY;
  15536. },
  15537. set: function (value) {
  15538. var pointers = this.inputs.attached["pointers"];
  15539. if (pointers) {
  15540. pointers.angularSensibilityY = value;
  15541. }
  15542. },
  15543. enumerable: true,
  15544. configurable: true
  15545. });
  15546. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15547. get: function () {
  15548. var pointers = this.inputs.attached["pointers"];
  15549. if (pointers)
  15550. return pointers.pinchPrecision;
  15551. },
  15552. set: function (value) {
  15553. var pointers = this.inputs.attached["pointers"];
  15554. if (pointers) {
  15555. pointers.pinchPrecision = value;
  15556. }
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15562. get: function () {
  15563. var pointers = this.inputs.attached["pointers"];
  15564. if (pointers)
  15565. return pointers.panningSensibility;
  15566. },
  15567. set: function (value) {
  15568. var pointers = this.inputs.attached["pointers"];
  15569. if (pointers) {
  15570. pointers.panningSensibility = value;
  15571. }
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15577. get: function () {
  15578. var keyboard = this.inputs.attached["keyboard"];
  15579. if (keyboard)
  15580. return keyboard.keysUp;
  15581. },
  15582. set: function (value) {
  15583. var keyboard = this.inputs.attached["keyboard"];
  15584. if (keyboard)
  15585. keyboard.keysUp = value;
  15586. },
  15587. enumerable: true,
  15588. configurable: true
  15589. });
  15590. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15591. get: function () {
  15592. var keyboard = this.inputs.attached["keyboard"];
  15593. if (keyboard)
  15594. return keyboard.keysDown;
  15595. },
  15596. set: function (value) {
  15597. var keyboard = this.inputs.attached["keyboard"];
  15598. if (keyboard)
  15599. keyboard.keysDown = value;
  15600. },
  15601. enumerable: true,
  15602. configurable: true
  15603. });
  15604. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15605. get: function () {
  15606. var keyboard = this.inputs.attached["keyboard"];
  15607. if (keyboard)
  15608. return keyboard.keysLeft;
  15609. },
  15610. set: function (value) {
  15611. var keyboard = this.inputs.attached["keyboard"];
  15612. if (keyboard)
  15613. keyboard.keysLeft = value;
  15614. },
  15615. enumerable: true,
  15616. configurable: true
  15617. });
  15618. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15619. get: function () {
  15620. var keyboard = this.inputs.attached["keyboard"];
  15621. if (keyboard)
  15622. return keyboard.keysRight;
  15623. },
  15624. set: function (value) {
  15625. var keyboard = this.inputs.attached["keyboard"];
  15626. if (keyboard)
  15627. keyboard.keysRight = value;
  15628. },
  15629. enumerable: true,
  15630. configurable: true
  15631. });
  15632. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15633. get: function () {
  15634. var mousewheel = this.inputs.attached["mousewheel"];
  15635. if (mousewheel)
  15636. return mousewheel.wheelPrecision;
  15637. },
  15638. set: function (value) {
  15639. var mousewheel = this.inputs.attached["mousewheel"];
  15640. if (mousewheel)
  15641. mousewheel.wheelPrecision = value;
  15642. },
  15643. enumerable: true,
  15644. configurable: true
  15645. });
  15646. // Cache
  15647. ArcRotateCamera.prototype._initCache = function () {
  15648. _super.prototype._initCache.call(this);
  15649. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15650. this._cache.alpha = undefined;
  15651. this._cache.beta = undefined;
  15652. this._cache.radius = undefined;
  15653. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15654. };
  15655. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15656. if (!ignoreParentClass) {
  15657. _super.prototype._updateCache.call(this);
  15658. }
  15659. this._cache.target.copyFrom(this._getTargetPosition());
  15660. this._cache.alpha = this.alpha;
  15661. this._cache.beta = this.beta;
  15662. this._cache.radius = this.radius;
  15663. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15664. };
  15665. ArcRotateCamera.prototype._getTargetPosition = function () {
  15666. if (this.target.getAbsolutePosition) {
  15667. var pos = this.target.getAbsolutePosition();
  15668. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15669. }
  15670. return this.target;
  15671. };
  15672. // Synchronized
  15673. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15674. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15675. return false;
  15676. return this._cache.target.equals(this.target)
  15677. && this._cache.alpha === this.alpha
  15678. && this._cache.beta === this.beta
  15679. && this._cache.radius === this.radius
  15680. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15681. };
  15682. // Methods
  15683. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15684. var _this = this;
  15685. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15686. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15687. this._useCtrlForPanning = useCtrlForPanning;
  15688. this._panningMouseButton = panningMouseButton;
  15689. this.inputs.attachElement(element, noPreventDefault);
  15690. this._reset = function () {
  15691. _this.inertialAlphaOffset = 0;
  15692. _this.inertialBetaOffset = 0;
  15693. _this.inertialRadiusOffset = 0;
  15694. };
  15695. };
  15696. ArcRotateCamera.prototype.detachControl = function (element) {
  15697. this.inputs.detachElement(element);
  15698. if (this._reset) {
  15699. this._reset();
  15700. }
  15701. };
  15702. ArcRotateCamera.prototype._checkInputs = function () {
  15703. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15704. if (this._collisionTriggered) {
  15705. return;
  15706. }
  15707. this.inputs.checkInputs();
  15708. // Inertia
  15709. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15710. if (this.getScene().useRightHandedSystem) {
  15711. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15712. }
  15713. else {
  15714. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15715. }
  15716. this.beta += this.inertialBetaOffset;
  15717. this.radius -= this.inertialRadiusOffset;
  15718. this.inertialAlphaOffset *= this.inertia;
  15719. this.inertialBetaOffset *= this.inertia;
  15720. this.inertialRadiusOffset *= this.inertia;
  15721. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15722. this.inertialAlphaOffset = 0;
  15723. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15724. this.inertialBetaOffset = 0;
  15725. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15726. this.inertialRadiusOffset = 0;
  15727. }
  15728. // Panning inertia
  15729. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15730. if (!this._localDirection) {
  15731. this._localDirection = BABYLON.Vector3.Zero();
  15732. this._transformedDirection = BABYLON.Vector3.Zero();
  15733. }
  15734. this.inertialPanningX *= this.inertia;
  15735. this.inertialPanningY *= this.inertia;
  15736. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15737. this.inertialPanningX = 0;
  15738. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15739. this.inertialPanningY = 0;
  15740. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15741. this._localDirection.multiplyInPlace(this.panningAxis);
  15742. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15743. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15744. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15745. if (!this.panningAxis.y) {
  15746. this._transformedDirection.y = 0;
  15747. }
  15748. if (!this.target.getAbsolutePosition) {
  15749. this.target.addInPlace(this._transformedDirection);
  15750. }
  15751. }
  15752. // Limits
  15753. this._checkLimits();
  15754. _super.prototype._checkInputs.call(this);
  15755. };
  15756. ArcRotateCamera.prototype._checkLimits = function () {
  15757. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15758. if (this.allowUpsideDown && this.beta > Math.PI) {
  15759. this.beta = this.beta - (2 * Math.PI);
  15760. }
  15761. }
  15762. else {
  15763. if (this.beta < this.lowerBetaLimit) {
  15764. this.beta = this.lowerBetaLimit;
  15765. }
  15766. }
  15767. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15768. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15769. this.beta = this.beta + (2 * Math.PI);
  15770. }
  15771. }
  15772. else {
  15773. if (this.beta > this.upperBetaLimit) {
  15774. this.beta = this.upperBetaLimit;
  15775. }
  15776. }
  15777. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15778. this.alpha = this.lowerAlphaLimit;
  15779. }
  15780. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15781. this.alpha = this.upperAlphaLimit;
  15782. }
  15783. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15784. this.radius = this.lowerRadiusLimit;
  15785. }
  15786. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15787. this.radius = this.upperRadiusLimit;
  15788. }
  15789. };
  15790. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15791. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15792. this.radius = radiusv3.length();
  15793. // Alpha
  15794. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15795. if (radiusv3.z < 0) {
  15796. this.alpha = 2 * Math.PI - this.alpha;
  15797. }
  15798. // Beta
  15799. this.beta = Math.acos(radiusv3.y / this.radius);
  15800. this._checkLimits();
  15801. };
  15802. ArcRotateCamera.prototype.setPosition = function (position) {
  15803. if (this.position.equals(position)) {
  15804. return;
  15805. }
  15806. this.position.copyFrom(position);
  15807. this.rebuildAnglesAndRadius();
  15808. };
  15809. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15810. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15811. if (this._getTargetPosition().equals(target)) {
  15812. return;
  15813. }
  15814. if (toBoundingCenter && target.getBoundingInfo) {
  15815. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15816. }
  15817. else {
  15818. this._targetBoundingCenter = null;
  15819. }
  15820. this.target = target;
  15821. this.rebuildAnglesAndRadius();
  15822. };
  15823. ArcRotateCamera.prototype._getViewMatrix = function () {
  15824. // Compute
  15825. var cosa = Math.cos(this.alpha);
  15826. var sina = Math.sin(this.alpha);
  15827. var cosb = Math.cos(this.beta);
  15828. var sinb = Math.sin(this.beta);
  15829. if (sinb === 0) {
  15830. sinb = 0.0001;
  15831. }
  15832. var target = this._getTargetPosition();
  15833. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15834. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15835. this._collider.radius = this.collisionRadius;
  15836. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15837. this._collisionTriggered = true;
  15838. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15839. }
  15840. else {
  15841. this.position.copyFrom(this._newPosition);
  15842. var up = this.upVector;
  15843. if (this.allowUpsideDown && this.beta < 0) {
  15844. up = up.clone();
  15845. up = up.negate();
  15846. }
  15847. if (this.getScene().useRightHandedSystem) {
  15848. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15849. }
  15850. else {
  15851. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15852. }
  15853. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15854. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15855. }
  15856. this._currentTarget = target;
  15857. return this._viewMatrix;
  15858. };
  15859. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15860. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15861. meshes = meshes || this.getScene().meshes;
  15862. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15863. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15864. this.radius = distance * this.zoomOnFactor;
  15865. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15866. };
  15867. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15868. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15869. var meshesOrMinMaxVector;
  15870. var distance;
  15871. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15872. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15873. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15874. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15875. }
  15876. else {
  15877. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15878. distance = meshesOrMinMaxVectorAndDistance.distance;
  15879. }
  15880. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15881. if (!doNotUpdateMaxZ) {
  15882. this.maxZ = distance * 2;
  15883. }
  15884. };
  15885. /**
  15886. * @override
  15887. * Override Camera.createRigCamera
  15888. */
  15889. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15890. var alphaShift;
  15891. switch (this.cameraRigMode) {
  15892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15895. case BABYLON.Camera.RIG_MODE_VR:
  15896. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15897. break;
  15898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15899. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15900. break;
  15901. }
  15902. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15903. rigCam._cameraRigParams = {};
  15904. return rigCam;
  15905. };
  15906. /**
  15907. * @override
  15908. * Override Camera._updateRigCameras
  15909. */
  15910. ArcRotateCamera.prototype._updateRigCameras = function () {
  15911. var camLeft = this._rigCameras[0];
  15912. var camRight = this._rigCameras[1];
  15913. camLeft.beta = camRight.beta = this.beta;
  15914. camLeft.radius = camRight.radius = this.radius;
  15915. switch (this.cameraRigMode) {
  15916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15919. case BABYLON.Camera.RIG_MODE_VR:
  15920. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15921. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15922. break;
  15923. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15924. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15925. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15926. break;
  15927. }
  15928. _super.prototype._updateRigCameras.call(this);
  15929. };
  15930. ArcRotateCamera.prototype.dispose = function () {
  15931. this.inputs.clear();
  15932. _super.prototype.dispose.call(this);
  15933. };
  15934. ArcRotateCamera.prototype.getClassName = function () {
  15935. return "ArcRotateCamera";
  15936. };
  15937. return ArcRotateCamera;
  15938. }(BABYLON.TargetCamera));
  15939. __decorate([
  15940. BABYLON.serialize()
  15941. ], ArcRotateCamera.prototype, "alpha", void 0);
  15942. __decorate([
  15943. BABYLON.serialize()
  15944. ], ArcRotateCamera.prototype, "beta", void 0);
  15945. __decorate([
  15946. BABYLON.serialize()
  15947. ], ArcRotateCamera.prototype, "radius", void 0);
  15948. __decorate([
  15949. BABYLON.serializeAsVector3()
  15950. ], ArcRotateCamera.prototype, "target", void 0);
  15951. __decorate([
  15952. BABYLON.serialize()
  15953. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15954. __decorate([
  15955. BABYLON.serialize()
  15956. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15957. __decorate([
  15958. BABYLON.serialize()
  15959. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15960. __decorate([
  15961. BABYLON.serialize()
  15962. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15963. __decorate([
  15964. BABYLON.serialize()
  15965. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15966. __decorate([
  15967. BABYLON.serialize()
  15968. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15969. __decorate([
  15970. BABYLON.serialize()
  15971. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15972. __decorate([
  15973. BABYLON.serialize()
  15974. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15975. __decorate([
  15976. BABYLON.serialize()
  15977. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15978. __decorate([
  15979. BABYLON.serialize()
  15980. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15981. __decorate([
  15982. BABYLON.serialize()
  15983. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15984. __decorate([
  15985. BABYLON.serialize()
  15986. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15987. __decorate([
  15988. BABYLON.serialize()
  15989. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15990. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15991. })(BABYLON || (BABYLON = {}));
  15992. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  15993. var BABYLON;
  15994. (function (BABYLON) {
  15995. var ArcRotateCameraInputsManager = (function (_super) {
  15996. __extends(ArcRotateCameraInputsManager, _super);
  15997. function ArcRotateCameraInputsManager(camera) {
  15998. return _super.call(this, camera) || this;
  15999. }
  16000. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16001. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16002. return this;
  16003. };
  16004. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16005. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16006. return this;
  16007. };
  16008. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16009. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16010. return this;
  16011. };
  16012. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16013. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16014. return this;
  16015. };
  16016. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16017. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16018. return this;
  16019. };
  16020. return ArcRotateCameraInputsManager;
  16021. }(BABYLON.CameraInputsManager));
  16022. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16023. })(BABYLON || (BABYLON = {}));
  16024. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16025. var BABYLON;
  16026. (function (BABYLON) {
  16027. var RenderingManager = (function () {
  16028. function RenderingManager(scene) {
  16029. this._renderingGroups = new Array();
  16030. this._autoClearDepthStencil = {};
  16031. this._customOpaqueSortCompareFn = {};
  16032. this._customAlphaTestSortCompareFn = {};
  16033. this._customTransparentSortCompareFn = {};
  16034. this._renderinGroupInfo = null;
  16035. this._scene = scene;
  16036. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16037. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16038. }
  16039. }
  16040. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  16041. if (this._scene._activeParticleSystems.length === 0) {
  16042. return;
  16043. }
  16044. // Particles
  16045. var activeCamera = this._scene.activeCamera;
  16046. this._scene._particlesDuration.beginMonitoring();
  16047. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16048. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16049. if (particleSystem.renderingGroupId !== index) {
  16050. continue;
  16051. }
  16052. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16053. continue;
  16054. }
  16055. this._clearDepthStencilBuffer();
  16056. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16057. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16058. }
  16059. }
  16060. this._scene._particlesDuration.endMonitoring(false);
  16061. };
  16062. RenderingManager.prototype._renderSprites = function (index) {
  16063. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  16064. return;
  16065. }
  16066. // Sprites
  16067. var activeCamera = this._scene.activeCamera;
  16068. this._scene._spritesDuration.beginMonitoring();
  16069. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  16070. var spriteManager = this._scene.spriteManagers[id];
  16071. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16072. this._clearDepthStencilBuffer();
  16073. spriteManager.render();
  16074. }
  16075. }
  16076. this._scene._spritesDuration.endMonitoring(false);
  16077. };
  16078. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16079. if (depth === void 0) { depth = true; }
  16080. if (stencil === void 0) { stencil = true; }
  16081. if (this._depthStencilBufferAlreadyCleaned) {
  16082. return;
  16083. }
  16084. this._scene.getEngine().clear(0, false, depth, stencil);
  16085. this._depthStencilBufferAlreadyCleaned = true;
  16086. };
  16087. RenderingManager.prototype._renderSpritesAndParticles = function () {
  16088. if (this._currentRenderSprites) {
  16089. this._renderSprites(this._currentIndex);
  16090. }
  16091. if (this._currentRenderParticles) {
  16092. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  16093. }
  16094. };
  16095. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16096. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16097. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16098. var info = null;
  16099. if (observable) {
  16100. if (!this._renderinGroupInfo) {
  16101. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16102. }
  16103. info = this._renderinGroupInfo;
  16104. info.scene = this._scene;
  16105. info.camera = this._scene.activeCamera;
  16106. }
  16107. this._currentActiveMeshes = activeMeshes;
  16108. this._currentRenderParticles = renderParticles;
  16109. this._currentRenderSprites = renderSprites;
  16110. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16111. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16112. var renderingGroup = this._renderingGroups[index];
  16113. this._currentIndex = index;
  16114. if (renderingGroup) {
  16115. var renderingGroupMask = 0;
  16116. // Fire PRECLEAR stage
  16117. if (observable) {
  16118. renderingGroupMask = Math.pow(2, index);
  16119. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16120. info.renderingGroupId = index;
  16121. observable.notifyObservers(info, renderingGroupMask);
  16122. }
  16123. // Clear depth/stencil if needed
  16124. var autoClear = this._autoClearDepthStencil[index];
  16125. if (autoClear && autoClear.autoClear) {
  16126. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16127. }
  16128. // Fire PREOPAQUE stage
  16129. if (observable) {
  16130. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16131. observable.notifyObservers(info, renderingGroupMask);
  16132. }
  16133. if (!renderingGroup.onBeforeTransparentRendering) {
  16134. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  16135. }
  16136. // Fire PRETRANSPARENT stage
  16137. if (observable) {
  16138. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16139. observable.notifyObservers(info, renderingGroupMask);
  16140. }
  16141. renderingGroup.render(customRenderFunction);
  16142. // Fire POSTTRANSPARENT stage
  16143. if (observable) {
  16144. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16145. observable.notifyObservers(info, renderingGroupMask);
  16146. }
  16147. }
  16148. else {
  16149. this._renderSpritesAndParticles();
  16150. if (observable) {
  16151. var renderingGroupMask = Math.pow(2, index);
  16152. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16153. info.renderingGroupId = index;
  16154. observable.notifyObservers(info, renderingGroupMask);
  16155. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16156. observable.notifyObservers(info, renderingGroupMask);
  16157. }
  16158. }
  16159. }
  16160. };
  16161. RenderingManager.prototype.reset = function () {
  16162. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16163. var renderingGroup = this._renderingGroups[index];
  16164. if (renderingGroup) {
  16165. renderingGroup.prepare();
  16166. }
  16167. }
  16168. };
  16169. RenderingManager.prototype.dispatch = function (subMesh) {
  16170. var mesh = subMesh.getMesh();
  16171. var renderingGroupId = mesh.renderingGroupId || 0;
  16172. if (!this._renderingGroups[renderingGroupId]) {
  16173. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16174. }
  16175. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16176. };
  16177. /**
  16178. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16179. * This allowed control for front to back rendering or reversly depending of the special needs.
  16180. *
  16181. * @param renderingGroupId The rendering group id corresponding to its index
  16182. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16183. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16184. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16185. */
  16186. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16187. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16188. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16189. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16190. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16191. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16192. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16193. if (this._renderingGroups[renderingGroupId]) {
  16194. var group = this._renderingGroups[renderingGroupId];
  16195. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16196. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16197. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16198. }
  16199. };
  16200. /**
  16201. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16202. *
  16203. * @param renderingGroupId The rendering group id corresponding to its index
  16204. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16205. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16206. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16207. */
  16208. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16209. if (depth === void 0) { depth = true; }
  16210. if (stencil === void 0) { stencil = true; }
  16211. this._autoClearDepthStencil[renderingGroupId] = {
  16212. autoClear: autoClearDepthStencil,
  16213. depth: depth,
  16214. stencil: stencil
  16215. };
  16216. };
  16217. return RenderingManager;
  16218. }());
  16219. /**
  16220. * The max id used for rendering groups (not included)
  16221. */
  16222. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16223. /**
  16224. * The min id used for rendering groups (included)
  16225. */
  16226. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16227. BABYLON.RenderingManager = RenderingManager;
  16228. })(BABYLON || (BABYLON = {}));
  16229. //# sourceMappingURL=babylon.renderingManager.js.map
  16230. var BABYLON;
  16231. (function (BABYLON) {
  16232. var RenderingGroup = (function () {
  16233. /**
  16234. * Creates a new rendering group.
  16235. * @param index The rendering group index
  16236. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16237. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16238. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16239. */
  16240. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16241. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16242. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16243. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16244. this.index = index;
  16245. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16246. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16247. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16248. this._scene = scene;
  16249. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16250. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16251. this.transparentSortCompareFn = transparentSortCompareFn;
  16252. }
  16253. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16254. /**
  16255. * Set the opaque sort comparison function.
  16256. * If null the sub meshes will be render in the order they were created
  16257. */
  16258. set: function (value) {
  16259. this._opaqueSortCompareFn = value;
  16260. if (value) {
  16261. this._renderOpaque = this.renderOpaqueSorted;
  16262. }
  16263. else {
  16264. this._renderOpaque = RenderingGroup.renderUnsorted;
  16265. }
  16266. },
  16267. enumerable: true,
  16268. configurable: true
  16269. });
  16270. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16271. /**
  16272. * Set the alpha test sort comparison function.
  16273. * If null the sub meshes will be render in the order they were created
  16274. */
  16275. set: function (value) {
  16276. this._alphaTestSortCompareFn = value;
  16277. if (value) {
  16278. this._renderAlphaTest = this.renderAlphaTestSorted;
  16279. }
  16280. else {
  16281. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16282. }
  16283. },
  16284. enumerable: true,
  16285. configurable: true
  16286. });
  16287. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16288. /**
  16289. * Set the transparent sort comparison function.
  16290. * If null the sub meshes will be render in the order they were created
  16291. */
  16292. set: function (value) {
  16293. if (value) {
  16294. this._transparentSortCompareFn = value;
  16295. }
  16296. else {
  16297. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16298. }
  16299. this._renderTransparent = this.renderTransparentSorted;
  16300. },
  16301. enumerable: true,
  16302. configurable: true
  16303. });
  16304. /**
  16305. * Render all the sub meshes contained in the group.
  16306. * @param customRenderFunction Used to override the default render behaviour of the group.
  16307. * @returns true if rendered some submeshes.
  16308. */
  16309. RenderingGroup.prototype.render = function (customRenderFunction) {
  16310. if (customRenderFunction) {
  16311. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16312. return;
  16313. }
  16314. var engine = this._scene.getEngine();
  16315. // Opaque
  16316. if (this._opaqueSubMeshes.length !== 0) {
  16317. this._renderOpaque(this._opaqueSubMeshes);
  16318. }
  16319. // Alpha test
  16320. if (this._alphaTestSubMeshes.length !== 0) {
  16321. engine.setAlphaTesting(true);
  16322. this._renderAlphaTest(this._alphaTestSubMeshes);
  16323. engine.setAlphaTesting(false);
  16324. }
  16325. if (this.onBeforeTransparentRendering) {
  16326. this.onBeforeTransparentRendering();
  16327. }
  16328. // Transparent
  16329. if (this._transparentSubMeshes.length !== 0) {
  16330. this._renderTransparent(this._transparentSubMeshes);
  16331. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16332. }
  16333. };
  16334. /**
  16335. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16336. * @param subMeshes The submeshes to render
  16337. */
  16338. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16339. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16340. };
  16341. /**
  16342. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16343. * @param subMeshes The submeshes to render
  16344. */
  16345. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16346. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16347. };
  16348. /**
  16349. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16350. * @param subMeshes The submeshes to render
  16351. */
  16352. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16353. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16354. };
  16355. /**
  16356. * Renders the submeshes in a specified order.
  16357. * @param subMeshes The submeshes to sort before render
  16358. * @param sortCompareFn The comparison function use to sort
  16359. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16360. * @param transparent Specifies to activate blending if true
  16361. */
  16362. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16363. var subIndex = 0;
  16364. var subMesh;
  16365. for (; subIndex < subMeshes.length; subIndex++) {
  16366. subMesh = subMeshes.data[subIndex];
  16367. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16368. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16369. }
  16370. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16371. sortedArray.sort(sortCompareFn);
  16372. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16373. subMesh = sortedArray[subIndex];
  16374. subMesh.render(transparent);
  16375. }
  16376. };
  16377. /**
  16378. * Renders the submeshes in the order they were dispatched (no sort applied).
  16379. * @param subMeshes The submeshes to render
  16380. */
  16381. RenderingGroup.renderUnsorted = function (subMeshes) {
  16382. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16383. var submesh = subMeshes.data[subIndex];
  16384. submesh.render(false);
  16385. }
  16386. };
  16387. /**
  16388. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16389. * are rendered back to front if in the same alpha index.
  16390. *
  16391. * @param a The first submesh
  16392. * @param b The second submesh
  16393. * @returns The result of the comparison
  16394. */
  16395. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16396. // Alpha index first
  16397. if (a._alphaIndex > b._alphaIndex) {
  16398. return 1;
  16399. }
  16400. if (a._alphaIndex < b._alphaIndex) {
  16401. return -1;
  16402. }
  16403. // Then distance to camera
  16404. return RenderingGroup.backToFrontSortCompare(a, b);
  16405. };
  16406. /**
  16407. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16408. * are rendered back to front.
  16409. *
  16410. * @param a The first submesh
  16411. * @param b The second submesh
  16412. * @returns The result of the comparison
  16413. */
  16414. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16415. // Then distance to camera
  16416. if (a._distanceToCamera < b._distanceToCamera) {
  16417. return 1;
  16418. }
  16419. if (a._distanceToCamera > b._distanceToCamera) {
  16420. return -1;
  16421. }
  16422. return 0;
  16423. };
  16424. /**
  16425. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16426. * are rendered front to back (prevent overdraw).
  16427. *
  16428. * @param a The first submesh
  16429. * @param b The second submesh
  16430. * @returns The result of the comparison
  16431. */
  16432. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16433. // Then distance to camera
  16434. if (a._distanceToCamera < b._distanceToCamera) {
  16435. return -1;
  16436. }
  16437. if (a._distanceToCamera > b._distanceToCamera) {
  16438. return 1;
  16439. }
  16440. return 0;
  16441. };
  16442. /**
  16443. * Resets the different lists of submeshes to prepare a new frame.
  16444. */
  16445. RenderingGroup.prototype.prepare = function () {
  16446. this._opaqueSubMeshes.reset();
  16447. this._transparentSubMeshes.reset();
  16448. this._alphaTestSubMeshes.reset();
  16449. };
  16450. /**
  16451. * Inserts the submesh in its correct queue depending on its material.
  16452. * @param subMesh The submesh to dispatch
  16453. */
  16454. RenderingGroup.prototype.dispatch = function (subMesh) {
  16455. var material = subMesh.getMaterial();
  16456. var mesh = subMesh.getMesh();
  16457. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16458. this._transparentSubMeshes.push(subMesh);
  16459. }
  16460. else if (material.needAlphaTesting()) {
  16461. this._alphaTestSubMeshes.push(subMesh);
  16462. }
  16463. else {
  16464. this._opaqueSubMeshes.push(subMesh); // Opaque
  16465. }
  16466. };
  16467. return RenderingGroup;
  16468. }());
  16469. BABYLON.RenderingGroup = RenderingGroup;
  16470. })(BABYLON || (BABYLON = {}));
  16471. //# sourceMappingURL=babylon.renderingGroup.js.map
  16472. var BABYLON;
  16473. (function (BABYLON) {
  16474. var PointerEventTypes = (function () {
  16475. function PointerEventTypes() {
  16476. }
  16477. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16478. get: function () {
  16479. return PointerEventTypes._POINTERDOWN;
  16480. },
  16481. enumerable: true,
  16482. configurable: true
  16483. });
  16484. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16485. get: function () {
  16486. return PointerEventTypes._POINTERUP;
  16487. },
  16488. enumerable: true,
  16489. configurable: true
  16490. });
  16491. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16492. get: function () {
  16493. return PointerEventTypes._POINTERMOVE;
  16494. },
  16495. enumerable: true,
  16496. configurable: true
  16497. });
  16498. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16499. get: function () {
  16500. return PointerEventTypes._POINTERWHEEL;
  16501. },
  16502. enumerable: true,
  16503. configurable: true
  16504. });
  16505. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16506. get: function () {
  16507. return PointerEventTypes._POINTERPICK;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. return PointerEventTypes;
  16513. }());
  16514. PointerEventTypes._POINTERDOWN = 0x01;
  16515. PointerEventTypes._POINTERUP = 0x02;
  16516. PointerEventTypes._POINTERMOVE = 0x04;
  16517. PointerEventTypes._POINTERWHEEL = 0x08;
  16518. PointerEventTypes._POINTERPICK = 0x10;
  16519. BABYLON.PointerEventTypes = PointerEventTypes;
  16520. var PointerInfoBase = (function () {
  16521. function PointerInfoBase(type, event) {
  16522. this.type = type;
  16523. this.event = event;
  16524. }
  16525. return PointerInfoBase;
  16526. }());
  16527. BABYLON.PointerInfoBase = PointerInfoBase;
  16528. /**
  16529. * This class is used to store pointer related info for the onPrePointerObservable event.
  16530. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16531. */
  16532. var PointerInfoPre = (function (_super) {
  16533. __extends(PointerInfoPre, _super);
  16534. function PointerInfoPre(type, event, localX, localY) {
  16535. var _this = _super.call(this, type, event) || this;
  16536. _this.skipOnPointerObservable = false;
  16537. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16538. return _this;
  16539. }
  16540. return PointerInfoPre;
  16541. }(PointerInfoBase));
  16542. BABYLON.PointerInfoPre = PointerInfoPre;
  16543. /**
  16544. * This type contains all the data related to a pointer event in Babylon.js.
  16545. * 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.
  16546. */
  16547. var PointerInfo = (function (_super) {
  16548. __extends(PointerInfo, _super);
  16549. function PointerInfo(type, event, pickInfo) {
  16550. var _this = _super.call(this, type, event) || this;
  16551. _this.pickInfo = pickInfo;
  16552. return _this;
  16553. }
  16554. return PointerInfo;
  16555. }(PointerInfoBase));
  16556. BABYLON.PointerInfo = PointerInfo;
  16557. /**
  16558. * This class is used by the onRenderingGroupObservable
  16559. */
  16560. var RenderingGroupInfo = (function () {
  16561. function RenderingGroupInfo() {
  16562. }
  16563. return RenderingGroupInfo;
  16564. }());
  16565. /**
  16566. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16567. * This stage will be fired no matter what
  16568. */
  16569. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16570. /**
  16571. * Called before opaque object are rendered.
  16572. * This stage will be fired only if there's 3D Opaque content to render
  16573. */
  16574. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16575. /**
  16576. * Called after the opaque objects are rendered and before the transparent ones
  16577. * This stage will be fired only if there's 3D transparent content to render
  16578. */
  16579. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16580. /**
  16581. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16582. * This stage will be fired no matter what
  16583. */
  16584. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16585. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16586. /**
  16587. * Represents a scene to be rendered by the engine.
  16588. * @see http://doc.babylonjs.com/page.php?p=21911
  16589. */
  16590. var Scene = (function () {
  16591. /**
  16592. * @constructor
  16593. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16594. */
  16595. function Scene(engine) {
  16596. // Members
  16597. this.autoClear = true;
  16598. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16599. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16600. this.forceWireframe = false;
  16601. this.forcePointsCloud = false;
  16602. this.forceShowBoundingBoxes = false;
  16603. this.animationsEnabled = true;
  16604. this.constantlyUpdateMeshUnderPointer = false;
  16605. this.useRightHandedSystem = false;
  16606. this.hoverCursor = "pointer";
  16607. // Metadata
  16608. this.metadata = null;
  16609. // Events
  16610. /**
  16611. * An event triggered when the scene is disposed.
  16612. * @type {BABYLON.Observable}
  16613. */
  16614. this.onDisposeObservable = new BABYLON.Observable();
  16615. /**
  16616. * An event triggered before rendering the scene
  16617. * @type {BABYLON.Observable}
  16618. */
  16619. this.onBeforeRenderObservable = new BABYLON.Observable();
  16620. /**
  16621. * An event triggered after rendering the scene
  16622. * @type {BABYLON.Observable}
  16623. */
  16624. this.onAfterRenderObservable = new BABYLON.Observable();
  16625. /**
  16626. * An event triggered when the scene is ready
  16627. * @type {BABYLON.Observable}
  16628. */
  16629. this.onReadyObservable = new BABYLON.Observable();
  16630. /**
  16631. * An event triggered before rendering a camera
  16632. * @type {BABYLON.Observable}
  16633. */
  16634. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16635. /**
  16636. * An event triggered after rendering a camera
  16637. * @type {BABYLON.Observable}
  16638. */
  16639. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16640. /**
  16641. * An event triggered when a camera is created
  16642. * @type {BABYLON.Observable}
  16643. */
  16644. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16645. /**
  16646. * An event triggered when a camera is removed
  16647. * @type {BABYLON.Observable}
  16648. */
  16649. this.onCameraRemovedObservable = new BABYLON.Observable();
  16650. /**
  16651. * An event triggered when a light is created
  16652. * @type {BABYLON.Observable}
  16653. */
  16654. this.onNewLightAddedObservable = new BABYLON.Observable();
  16655. /**
  16656. * An event triggered when a light is removed
  16657. * @type {BABYLON.Observable}
  16658. */
  16659. this.onLightRemovedObservable = new BABYLON.Observable();
  16660. /**
  16661. * An event triggered when a geometry is created
  16662. * @type {BABYLON.Observable}
  16663. */
  16664. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16665. /**
  16666. * An event triggered when a geometry is removed
  16667. * @type {BABYLON.Observable}
  16668. */
  16669. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16670. /**
  16671. * An event triggered when a mesh is created
  16672. * @type {BABYLON.Observable}
  16673. */
  16674. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16675. /**
  16676. * An event triggered when a mesh is removed
  16677. * @type {BABYLON.Observable}
  16678. */
  16679. this.onMeshRemovedObservable = new BABYLON.Observable();
  16680. /**
  16681. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16682. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16683. * 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)
  16684. */
  16685. this.onRenderingGroupObservable = new BABYLON.Observable();
  16686. // Animations
  16687. this.animations = [];
  16688. /**
  16689. * 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).
  16690. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16691. */
  16692. this.onPrePointerObservable = new BABYLON.Observable();
  16693. /**
  16694. * Observable event triggered each time an input event is received from the rendering canvas
  16695. */
  16696. this.onPointerObservable = new BABYLON.Observable();
  16697. 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
  16698. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16699. this._startingPointerTime = 0;
  16700. // Fog
  16701. /**
  16702. * is fog enabled on this scene.
  16703. * @type {boolean}
  16704. */
  16705. this.fogEnabled = true;
  16706. this.fogMode = Scene.FOGMODE_NONE;
  16707. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16708. this.fogDensity = 0.1;
  16709. this.fogStart = 0;
  16710. this.fogEnd = 1000.0;
  16711. // Lights
  16712. /**
  16713. * is shadow enabled on this scene.
  16714. * @type {boolean}
  16715. */
  16716. this.shadowsEnabled = true;
  16717. /**
  16718. * is light enabled on this scene.
  16719. * @type {boolean}
  16720. */
  16721. this.lightsEnabled = true;
  16722. /**
  16723. * All of the lights added to this scene.
  16724. * @see BABYLON.Light
  16725. * @type {BABYLON.Light[]}
  16726. */
  16727. this.lights = new Array();
  16728. // Cameras
  16729. /**
  16730. * All of the cameras added to this scene.
  16731. * @see BABYLON.Camera
  16732. * @type {BABYLON.Camera[]}
  16733. */
  16734. this.cameras = new Array();
  16735. this.activeCameras = new Array();
  16736. // Meshes
  16737. /**
  16738. * All of the (abstract) meshes added to this scene.
  16739. * @see BABYLON.AbstractMesh
  16740. * @type {BABYLON.AbstractMesh[]}
  16741. */
  16742. this.meshes = new Array();
  16743. // Geometries
  16744. this._geometries = new Array();
  16745. this.materials = new Array();
  16746. this.multiMaterials = new Array();
  16747. // Textures
  16748. this.texturesEnabled = true;
  16749. this.textures = new Array();
  16750. // Particles
  16751. this.particlesEnabled = true;
  16752. this.particleSystems = new Array();
  16753. // Sprites
  16754. this.spritesEnabled = true;
  16755. this.spriteManagers = new Array();
  16756. // Layers
  16757. this.layers = new Array();
  16758. this.highlightLayers = new Array();
  16759. // Skeletons
  16760. this.skeletonsEnabled = true;
  16761. this.skeletons = new Array();
  16762. // Lens flares
  16763. this.lensFlaresEnabled = true;
  16764. this.lensFlareSystems = new Array();
  16765. // Collisions
  16766. this.collisionsEnabled = true;
  16767. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16768. // Postprocesses
  16769. this.postProcessesEnabled = true;
  16770. // Customs render targets
  16771. this.renderTargetsEnabled = true;
  16772. this.dumpNextRenderTargets = false;
  16773. this.customRenderTargets = new Array();
  16774. // Imported meshes
  16775. this.importedMeshesFiles = new Array();
  16776. // Probes
  16777. this.probesEnabled = true;
  16778. this.reflectionProbes = new Array();
  16779. this._actionManagers = new Array();
  16780. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16781. // Procedural textures
  16782. this.proceduralTexturesEnabled = true;
  16783. this._proceduralTextures = new Array();
  16784. this.soundTracks = new Array();
  16785. this._audioEnabled = true;
  16786. this._headphone = false;
  16787. // Performance counters
  16788. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16789. this._totalLightsCounter = new BABYLON.PerfCounter();
  16790. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16791. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16792. this._totalVertices = new BABYLON.PerfCounter();
  16793. this._activeIndices = new BABYLON.PerfCounter();
  16794. this._activeParticles = new BABYLON.PerfCounter();
  16795. this._lastFrameDuration = new BABYLON.PerfCounter();
  16796. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16797. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16798. this._particlesDuration = new BABYLON.PerfCounter();
  16799. this._renderDuration = new BABYLON.PerfCounter();
  16800. this._spritesDuration = new BABYLON.PerfCounter();
  16801. this._activeBones = new BABYLON.PerfCounter();
  16802. this._renderId = 0;
  16803. this._executeWhenReadyTimeoutId = -1;
  16804. this._intermediateRendering = false;
  16805. this._toBeDisposed = new BABYLON.SmartArray(256);
  16806. this._pendingData = []; //ANY
  16807. this._activeMeshes = new BABYLON.SmartArray(256);
  16808. this._processedMaterials = new BABYLON.SmartArray(256);
  16809. this._renderTargets = new BABYLON.SmartArray(256);
  16810. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16811. this._activeSkeletons = new BABYLON.SmartArray(32);
  16812. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16813. this._activeAnimatables = new Array();
  16814. this._transformMatrix = BABYLON.Matrix.Zero();
  16815. this._edgesRenderers = new BABYLON.SmartArray(16);
  16816. this._uniqueIdCounter = 0;
  16817. this._engine = engine;
  16818. engine.scenes.push(this);
  16819. this._externalData = new BABYLON.StringDictionary();
  16820. this._uid = null;
  16821. this._renderingManager = new BABYLON.RenderingManager(this);
  16822. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16823. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16824. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16825. if (BABYLON.OutlineRenderer) {
  16826. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16827. }
  16828. this.attachControl();
  16829. if (BABYLON.SoundTrack) {
  16830. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16831. }
  16832. //simplification queue
  16833. if (BABYLON.SimplificationQueue) {
  16834. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16835. }
  16836. //collision coordinator initialization. For now legacy per default.
  16837. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16838. }
  16839. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16840. get: function () {
  16841. return Scene._FOGMODE_NONE;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16847. get: function () {
  16848. return Scene._FOGMODE_EXP;
  16849. },
  16850. enumerable: true,
  16851. configurable: true
  16852. });
  16853. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16854. get: function () {
  16855. return Scene._FOGMODE_EXP2;
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16861. get: function () {
  16862. return Scene._FOGMODE_LINEAR;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Scene.prototype, "onDispose", {
  16868. set: function (callback) {
  16869. if (this._onDisposeObserver) {
  16870. this.onDisposeObservable.remove(this._onDisposeObserver);
  16871. }
  16872. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16873. },
  16874. enumerable: true,
  16875. configurable: true
  16876. });
  16877. Object.defineProperty(Scene.prototype, "beforeRender", {
  16878. set: function (callback) {
  16879. if (this._onBeforeRenderObserver) {
  16880. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16881. }
  16882. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. Object.defineProperty(Scene.prototype, "afterRender", {
  16888. set: function (callback) {
  16889. if (this._onAfterRenderObserver) {
  16890. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16891. }
  16892. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16893. },
  16894. enumerable: true,
  16895. configurable: true
  16896. });
  16897. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16898. set: function (callback) {
  16899. if (this._onBeforeCameraRenderObserver) {
  16900. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16901. }
  16902. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16908. set: function (callback) {
  16909. if (this._onAfterCameraRenderObserver) {
  16910. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16911. }
  16912. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16918. get: function () {
  16919. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16925. get: function () {
  16926. if (!this._defaultMaterial) {
  16927. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16928. }
  16929. return this._defaultMaterial;
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. Object.defineProperty(Scene.prototype, "debugLayer", {
  16935. // Properties
  16936. get: function () {
  16937. if (!this._debugLayer) {
  16938. this._debugLayer = new BABYLON.DebugLayer(this);
  16939. }
  16940. return this._debugLayer;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16946. get: function () {
  16947. return this._workerCollisions;
  16948. },
  16949. set: function (enabled) {
  16950. enabled = (enabled && !!Worker);
  16951. this._workerCollisions = enabled;
  16952. if (this.collisionCoordinator) {
  16953. this.collisionCoordinator.destroy();
  16954. }
  16955. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16956. this.collisionCoordinator.init(this);
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16962. get: function () {
  16963. return this._selectionOctree;
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16969. /**
  16970. * The mesh that is currently under the pointer.
  16971. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16972. */
  16973. get: function () {
  16974. return this._pointerOverMesh;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Object.defineProperty(Scene.prototype, "pointerX", {
  16980. /**
  16981. * Current on-screen X position of the pointer
  16982. * @return {number} X position of the pointer
  16983. */
  16984. get: function () {
  16985. return this._pointerX;
  16986. },
  16987. enumerable: true,
  16988. configurable: true
  16989. });
  16990. Object.defineProperty(Scene.prototype, "pointerY", {
  16991. /**
  16992. * Current on-screen Y position of the pointer
  16993. * @return {number} Y position of the pointer
  16994. */
  16995. get: function () {
  16996. return this._pointerY;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Scene.prototype.getCachedMaterial = function () {
  17002. return this._cachedMaterial;
  17003. };
  17004. Scene.prototype.getBoundingBoxRenderer = function () {
  17005. return this._boundingBoxRenderer;
  17006. };
  17007. Scene.prototype.getOutlineRenderer = function () {
  17008. return this._outlineRenderer;
  17009. };
  17010. Scene.prototype.getEngine = function () {
  17011. return this._engine;
  17012. };
  17013. Scene.prototype.getTotalVertices = function () {
  17014. return this._totalVertices.current;
  17015. };
  17016. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17017. get: function () {
  17018. return this._totalVertices;
  17019. },
  17020. enumerable: true,
  17021. configurable: true
  17022. });
  17023. Scene.prototype.getActiveIndices = function () {
  17024. return this._activeIndices.current;
  17025. };
  17026. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17027. get: function () {
  17028. return this._activeIndices;
  17029. },
  17030. enumerable: true,
  17031. configurable: true
  17032. });
  17033. Scene.prototype.getActiveParticles = function () {
  17034. return this._activeParticles.current;
  17035. };
  17036. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17037. get: function () {
  17038. return this._activeParticles;
  17039. },
  17040. enumerable: true,
  17041. configurable: true
  17042. });
  17043. Scene.prototype.getActiveBones = function () {
  17044. return this._activeBones.current;
  17045. };
  17046. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17047. get: function () {
  17048. return this._activeBones;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. // Stats
  17054. Scene.prototype.getLastFrameDuration = function () {
  17055. return this._lastFrameDuration.current;
  17056. };
  17057. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17058. get: function () {
  17059. return this._lastFrameDuration;
  17060. },
  17061. enumerable: true,
  17062. configurable: true
  17063. });
  17064. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17065. return this._evaluateActiveMeshesDuration.current;
  17066. };
  17067. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17068. get: function () {
  17069. return this._evaluateActiveMeshesDuration;
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. Scene.prototype.getActiveMeshes = function () {
  17075. return this._activeMeshes;
  17076. };
  17077. Scene.prototype.getRenderTargetsDuration = function () {
  17078. return this._renderTargetsDuration.current;
  17079. };
  17080. Scene.prototype.getRenderDuration = function () {
  17081. return this._renderDuration.current;
  17082. };
  17083. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17084. get: function () {
  17085. return this._renderDuration;
  17086. },
  17087. enumerable: true,
  17088. configurable: true
  17089. });
  17090. Scene.prototype.getParticlesDuration = function () {
  17091. return this._particlesDuration.current;
  17092. };
  17093. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17094. get: function () {
  17095. return this._particlesDuration;
  17096. },
  17097. enumerable: true,
  17098. configurable: true
  17099. });
  17100. Scene.prototype.getSpritesDuration = function () {
  17101. return this._spritesDuration.current;
  17102. };
  17103. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17104. get: function () {
  17105. return this._spritesDuration;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Scene.prototype.getAnimationRatio = function () {
  17111. return this._animationRatio;
  17112. };
  17113. Scene.prototype.getRenderId = function () {
  17114. return this._renderId;
  17115. };
  17116. Scene.prototype.incrementRenderId = function () {
  17117. this._renderId++;
  17118. };
  17119. Scene.prototype._updatePointerPosition = function (evt) {
  17120. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17121. this._pointerX = evt.clientX - canvasRect.left;
  17122. this._pointerY = evt.clientY - canvasRect.top;
  17123. this._unTranslatedPointerX = this._pointerX;
  17124. this._unTranslatedPointerY = this._pointerY;
  17125. if (this.cameraToUseForPointers) {
  17126. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17127. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17128. }
  17129. };
  17130. // Pointers handling
  17131. /**
  17132. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17133. * @param attachUp defines if you want to attach events to pointerup
  17134. * @param attachDown defines if you want to attach events to pointerdown
  17135. * @param attachMove defines if you want to attach events to pointermove
  17136. */
  17137. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17138. var _this = this;
  17139. if (attachUp === void 0) { attachUp = true; }
  17140. if (attachDown === void 0) { attachDown = true; }
  17141. if (attachMove === void 0) { attachMove = true; }
  17142. var spritePredicate = function (sprite) {
  17143. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17144. };
  17145. this._onPointerMove = function (evt) {
  17146. _this._updatePointerPosition(evt);
  17147. // PreObservable support
  17148. if (_this.onPrePointerObservable.hasObservers()) {
  17149. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17150. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17151. _this.onPrePointerObservable.notifyObservers(pi, type);
  17152. if (pi.skipOnPointerObservable) {
  17153. return;
  17154. }
  17155. }
  17156. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17157. return;
  17158. }
  17159. var canvas = _this._engine.getRenderingCanvas();
  17160. if (!_this.pointerMovePredicate) {
  17161. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17162. }
  17163. // Meshes
  17164. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17165. if (pickResult.hit && pickResult.pickedMesh) {
  17166. _this.setPointerOverSprite(null);
  17167. _this.setPointerOverMesh(pickResult.pickedMesh);
  17168. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17169. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17170. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17171. }
  17172. else {
  17173. canvas.style.cursor = _this.hoverCursor;
  17174. }
  17175. }
  17176. else {
  17177. canvas.style.cursor = "";
  17178. }
  17179. }
  17180. else {
  17181. _this.setPointerOverMesh(null);
  17182. // Sprites
  17183. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17184. if (pickResult.hit && pickResult.pickedSprite) {
  17185. _this.setPointerOverSprite(pickResult.pickedSprite);
  17186. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17187. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17188. }
  17189. else {
  17190. canvas.style.cursor = _this.hoverCursor;
  17191. }
  17192. }
  17193. else {
  17194. _this.setPointerOverSprite(null);
  17195. // Restore pointer
  17196. canvas.style.cursor = "";
  17197. }
  17198. }
  17199. if (_this.onPointerMove) {
  17200. _this.onPointerMove(evt, pickResult);
  17201. }
  17202. if (_this.onPointerObservable.hasObservers()) {
  17203. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17204. var pi = new PointerInfo(type, evt, pickResult);
  17205. _this.onPointerObservable.notifyObservers(pi, type);
  17206. }
  17207. };
  17208. this._onPointerDown = function (evt) {
  17209. _this._updatePointerPosition(evt);
  17210. // PreObservable support
  17211. if (_this.onPrePointerObservable.hasObservers()) {
  17212. var type = PointerEventTypes.POINTERDOWN;
  17213. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17214. _this.onPrePointerObservable.notifyObservers(pi, type);
  17215. if (pi.skipOnPointerObservable) {
  17216. return;
  17217. }
  17218. }
  17219. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17220. return;
  17221. }
  17222. _this._startingPointerPosition.x = _this._pointerX;
  17223. _this._startingPointerPosition.y = _this._pointerY;
  17224. _this._startingPointerTime = new Date().getTime();
  17225. if (!_this.pointerDownPredicate) {
  17226. _this.pointerDownPredicate = function (mesh) {
  17227. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17228. };
  17229. }
  17230. // Meshes
  17231. _this._pickedDownMesh = null;
  17232. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17233. if (pickResult.hit && pickResult.pickedMesh) {
  17234. if (pickResult.pickedMesh.actionManager) {
  17235. _this._pickedDownMesh = pickResult.pickedMesh;
  17236. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17237. switch (evt.button) {
  17238. case 0:
  17239. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17240. break;
  17241. case 1:
  17242. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17243. break;
  17244. case 2:
  17245. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17246. break;
  17247. }
  17248. if (pickResult.pickedMesh.actionManager) {
  17249. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17250. }
  17251. }
  17252. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17253. var that = _this;
  17254. window.setTimeout(function () {
  17255. 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);
  17256. if (pickResult.hit && pickResult.pickedMesh) {
  17257. if (pickResult.pickedMesh.actionManager) {
  17258. 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)) {
  17259. that._startingPointerTime = 0;
  17260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17261. }
  17262. }
  17263. }
  17264. }, BABYLON.ActionManager.LongPressDelay);
  17265. }
  17266. }
  17267. }
  17268. if (_this.onPointerDown) {
  17269. _this.onPointerDown(evt, pickResult);
  17270. }
  17271. if (_this.onPointerObservable.hasObservers()) {
  17272. var type = PointerEventTypes.POINTERDOWN;
  17273. var pi = new PointerInfo(type, evt, pickResult);
  17274. _this.onPointerObservable.notifyObservers(pi, type);
  17275. }
  17276. // Sprites
  17277. _this._pickedDownSprite = null;
  17278. if (_this.spriteManagers.length > 0) {
  17279. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17280. if (pickResult.hit && pickResult.pickedSprite) {
  17281. if (pickResult.pickedSprite.actionManager) {
  17282. _this._pickedDownSprite = pickResult.pickedSprite;
  17283. switch (evt.button) {
  17284. case 0:
  17285. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17286. break;
  17287. case 1:
  17288. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17289. break;
  17290. case 2:
  17291. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17292. break;
  17293. }
  17294. if (pickResult.pickedSprite.actionManager) {
  17295. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17296. }
  17297. }
  17298. }
  17299. }
  17300. };
  17301. this._onPointerUp = function (evt) {
  17302. _this._updatePointerPosition(evt);
  17303. // PreObservable support
  17304. if (_this.onPrePointerObservable.hasObservers()) {
  17305. var type = PointerEventTypes.POINTERUP;
  17306. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17307. _this.onPrePointerObservable.notifyObservers(pi, type);
  17308. if (pi.skipOnPointerObservable) {
  17309. return;
  17310. }
  17311. }
  17312. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17313. return;
  17314. }
  17315. if (!_this.pointerUpPredicate) {
  17316. _this.pointerUpPredicate = function (mesh) {
  17317. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17318. };
  17319. }
  17320. // Meshes
  17321. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17322. if (pickResult.hit && pickResult.pickedMesh) {
  17323. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17324. if (_this.onPointerPick) {
  17325. _this.onPointerPick(evt, pickResult);
  17326. }
  17327. if (_this.onPointerObservable.hasObservers()) {
  17328. var type = PointerEventTypes.POINTERPICK;
  17329. var pi = new PointerInfo(type, evt, pickResult);
  17330. _this.onPointerObservable.notifyObservers(pi, type);
  17331. }
  17332. }
  17333. if (pickResult.pickedMesh.actionManager) {
  17334. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17335. if (pickResult.pickedMesh.actionManager) {
  17336. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17337. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17338. }
  17339. }
  17340. }
  17341. }
  17342. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17343. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17344. }
  17345. if (_this.onPointerUp) {
  17346. _this.onPointerUp(evt, pickResult);
  17347. }
  17348. if (_this.onPointerObservable.hasObservers()) {
  17349. var type = PointerEventTypes.POINTERUP;
  17350. var pi = new PointerInfo(type, evt, pickResult);
  17351. _this.onPointerObservable.notifyObservers(pi, type);
  17352. }
  17353. _this._startingPointerTime = 0;
  17354. // Sprites
  17355. if (_this.spriteManagers.length > 0) {
  17356. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17357. if (pickResult.hit && pickResult.pickedSprite) {
  17358. if (pickResult.pickedSprite.actionManager) {
  17359. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17360. if (pickResult.pickedSprite.actionManager) {
  17361. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17362. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17363. }
  17364. }
  17365. }
  17366. }
  17367. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17368. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17369. }
  17370. }
  17371. };
  17372. this._onKeyDown = function (evt) {
  17373. if (_this.actionManager) {
  17374. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17375. }
  17376. };
  17377. this._onKeyUp = function (evt) {
  17378. if (_this.actionManager) {
  17379. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17380. }
  17381. };
  17382. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17383. var canvas = this._engine.getRenderingCanvas();
  17384. if (attachMove) {
  17385. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17386. // Wheel
  17387. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17388. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17389. }
  17390. if (attachDown) {
  17391. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17392. }
  17393. if (attachUp) {
  17394. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17395. }
  17396. canvas.tabIndex = 1;
  17397. canvas.addEventListener("keydown", this._onKeyDown, false);
  17398. canvas.addEventListener("keyup", this._onKeyUp, false);
  17399. };
  17400. Scene.prototype.detachControl = function () {
  17401. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17402. var canvas = this._engine.getRenderingCanvas();
  17403. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17404. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17405. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17406. // Wheel
  17407. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17408. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17409. canvas.removeEventListener("keydown", this._onKeyDown);
  17410. canvas.removeEventListener("keyup", this._onKeyUp);
  17411. };
  17412. // Ready
  17413. Scene.prototype.isReady = function () {
  17414. if (this._pendingData.length > 0) {
  17415. return false;
  17416. }
  17417. var index;
  17418. for (index = 0; index < this._geometries.length; index++) {
  17419. var geometry = this._geometries[index];
  17420. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17421. return false;
  17422. }
  17423. }
  17424. for (index = 0; index < this.meshes.length; index++) {
  17425. var mesh = this.meshes[index];
  17426. if (!mesh.isReady()) {
  17427. return false;
  17428. }
  17429. var mat = mesh.material;
  17430. if (mat) {
  17431. if (!mat.isReady(mesh)) {
  17432. return false;
  17433. }
  17434. }
  17435. }
  17436. return true;
  17437. };
  17438. Scene.prototype.resetCachedMaterial = function () {
  17439. this._cachedMaterial = null;
  17440. };
  17441. Scene.prototype.registerBeforeRender = function (func) {
  17442. this.onBeforeRenderObservable.add(func);
  17443. };
  17444. Scene.prototype.unregisterBeforeRender = function (func) {
  17445. this.onBeforeRenderObservable.removeCallback(func);
  17446. };
  17447. Scene.prototype.registerAfterRender = function (func) {
  17448. this.onAfterRenderObservable.add(func);
  17449. };
  17450. Scene.prototype.unregisterAfterRender = function (func) {
  17451. this.onAfterRenderObservable.removeCallback(func);
  17452. };
  17453. Scene.prototype._addPendingData = function (data) {
  17454. this._pendingData.push(data);
  17455. };
  17456. Scene.prototype._removePendingData = function (data) {
  17457. var index = this._pendingData.indexOf(data);
  17458. if (index !== -1) {
  17459. this._pendingData.splice(index, 1);
  17460. }
  17461. };
  17462. Scene.prototype.getWaitingItemsCount = function () {
  17463. return this._pendingData.length;
  17464. };
  17465. /**
  17466. * Registers a function to be executed when the scene is ready.
  17467. * @param {Function} func - the function to be executed.
  17468. */
  17469. Scene.prototype.executeWhenReady = function (func) {
  17470. var _this = this;
  17471. this.onReadyObservable.add(func);
  17472. if (this._executeWhenReadyTimeoutId !== -1) {
  17473. return;
  17474. }
  17475. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17476. _this._checkIsReady();
  17477. }, 150);
  17478. };
  17479. Scene.prototype._checkIsReady = function () {
  17480. var _this = this;
  17481. if (this.isReady()) {
  17482. this.onReadyObservable.notifyObservers(this);
  17483. this.onReadyObservable.clear();
  17484. this._executeWhenReadyTimeoutId = -1;
  17485. return;
  17486. }
  17487. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17488. _this._checkIsReady();
  17489. }, 150);
  17490. };
  17491. // Animations
  17492. /**
  17493. * Will start the animation sequence of a given target
  17494. * @param target - the target
  17495. * @param {number} from - from which frame should animation start
  17496. * @param {number} to - till which frame should animation run.
  17497. * @param {boolean} [loop] - should the animation loop
  17498. * @param {number} [speedRatio] - the speed in which to run the animation
  17499. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17500. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17501. * @return {BABYLON.Animatable} the animatable object created for this animation
  17502. * @see BABYLON.Animatable
  17503. * @see http://doc.babylonjs.com/page.php?p=22081
  17504. */
  17505. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17506. if (speedRatio === void 0) { speedRatio = 1.0; }
  17507. this.stopAnimation(target);
  17508. if (!animatable) {
  17509. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17510. }
  17511. // Local animations
  17512. if (target.animations) {
  17513. animatable.appendAnimations(target, target.animations);
  17514. }
  17515. // Children animations
  17516. if (target.getAnimatables) {
  17517. var animatables = target.getAnimatables();
  17518. for (var index = 0; index < animatables.length; index++) {
  17519. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17520. }
  17521. }
  17522. animatable.reset();
  17523. return animatable;
  17524. };
  17525. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17526. if (speedRatio === undefined) {
  17527. speedRatio = 1.0;
  17528. }
  17529. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17530. return animatable;
  17531. };
  17532. Scene.prototype.getAnimatableByTarget = function (target) {
  17533. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17534. if (this._activeAnimatables[index].target === target) {
  17535. return this._activeAnimatables[index];
  17536. }
  17537. }
  17538. return null;
  17539. };
  17540. Object.defineProperty(Scene.prototype, "Animatables", {
  17541. get: function () {
  17542. return this._activeAnimatables;
  17543. },
  17544. enumerable: true,
  17545. configurable: true
  17546. });
  17547. /**
  17548. * Will stop the animation of the given target
  17549. * @param target - the target
  17550. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17551. * @see beginAnimation
  17552. */
  17553. Scene.prototype.stopAnimation = function (target, animationName) {
  17554. var animatable = this.getAnimatableByTarget(target);
  17555. if (animatable) {
  17556. animatable.stop(animationName);
  17557. }
  17558. };
  17559. Scene.prototype._animate = function () {
  17560. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17561. return;
  17562. }
  17563. if (!this._animationStartDate) {
  17564. if (this._pendingData.length > 0) {
  17565. return;
  17566. }
  17567. this._animationStartDate = BABYLON.Tools.Now;
  17568. }
  17569. // Getting time
  17570. var now = BABYLON.Tools.Now;
  17571. var delay = now - this._animationStartDate;
  17572. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17573. this._activeAnimatables[index]._animate(delay);
  17574. }
  17575. };
  17576. // Matrix
  17577. Scene.prototype.getViewMatrix = function () {
  17578. return this._viewMatrix;
  17579. };
  17580. Scene.prototype.getProjectionMatrix = function () {
  17581. return this._projectionMatrix;
  17582. };
  17583. Scene.prototype.getTransformMatrix = function () {
  17584. return this._transformMatrix;
  17585. };
  17586. Scene.prototype.setTransformMatrix = function (view, projection) {
  17587. this._viewMatrix = view;
  17588. this._projectionMatrix = projection;
  17589. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17590. // Update frustum
  17591. if (!this._frustumPlanes) {
  17592. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17593. }
  17594. else {
  17595. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17596. }
  17597. };
  17598. // Methods
  17599. Scene.prototype.addMesh = function (newMesh) {
  17600. newMesh.uniqueId = this._uniqueIdCounter++;
  17601. var position = this.meshes.push(newMesh);
  17602. //notify the collision coordinator
  17603. this.collisionCoordinator.onMeshAdded(newMesh);
  17604. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17605. };
  17606. Scene.prototype.removeMesh = function (toRemove) {
  17607. var index = this.meshes.indexOf(toRemove);
  17608. if (index !== -1) {
  17609. // Remove from the scene if mesh found
  17610. this.meshes.splice(index, 1);
  17611. }
  17612. //notify the collision coordinator
  17613. this.collisionCoordinator.onMeshRemoved(toRemove);
  17614. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17615. return index;
  17616. };
  17617. Scene.prototype.removeSkeleton = function (toRemove) {
  17618. var index = this.skeletons.indexOf(toRemove);
  17619. if (index !== -1) {
  17620. // Remove from the scene if mesh found
  17621. this.skeletons.splice(index, 1);
  17622. }
  17623. return index;
  17624. };
  17625. Scene.prototype.removeLight = function (toRemove) {
  17626. var index = this.lights.indexOf(toRemove);
  17627. if (index !== -1) {
  17628. // Remove from the scene if mesh found
  17629. this.lights.splice(index, 1);
  17630. }
  17631. this.onLightRemovedObservable.notifyObservers(toRemove);
  17632. return index;
  17633. };
  17634. Scene.prototype.removeCamera = function (toRemove) {
  17635. var index = this.cameras.indexOf(toRemove);
  17636. if (index !== -1) {
  17637. // Remove from the scene if mesh found
  17638. this.cameras.splice(index, 1);
  17639. }
  17640. // Remove from activeCameras
  17641. var index2 = this.activeCameras.indexOf(toRemove);
  17642. if (index2 !== -1) {
  17643. // Remove from the scene if mesh found
  17644. this.activeCameras.splice(index2, 1);
  17645. }
  17646. // Reset the activeCamera
  17647. if (this.activeCamera === toRemove) {
  17648. if (this.cameras.length > 0) {
  17649. this.activeCamera = this.cameras[0];
  17650. }
  17651. else {
  17652. this.activeCamera = null;
  17653. }
  17654. }
  17655. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17656. return index;
  17657. };
  17658. Scene.prototype.addLight = function (newLight) {
  17659. newLight.uniqueId = this._uniqueIdCounter++;
  17660. var position = this.lights.push(newLight);
  17661. this.onNewLightAddedObservable.notifyObservers(newLight);
  17662. };
  17663. Scene.prototype.addCamera = function (newCamera) {
  17664. newCamera.uniqueId = this._uniqueIdCounter++;
  17665. var position = this.cameras.push(newCamera);
  17666. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17667. };
  17668. /**
  17669. * Switch active camera
  17670. * @param {Camera} newCamera - new active camera
  17671. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17672. */
  17673. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17674. if (attachControl === void 0) { attachControl = true; }
  17675. var canvas = this._engine.getRenderingCanvas();
  17676. this.activeCamera.detachControl(canvas);
  17677. this.activeCamera = newCamera;
  17678. if (attachControl) {
  17679. newCamera.attachControl(canvas);
  17680. }
  17681. };
  17682. /**
  17683. * sets the active camera of the scene using its ID
  17684. * @param {string} id - the camera's ID
  17685. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17686. * @see activeCamera
  17687. */
  17688. Scene.prototype.setActiveCameraByID = function (id) {
  17689. var camera = this.getCameraByID(id);
  17690. if (camera) {
  17691. this.activeCamera = camera;
  17692. return camera;
  17693. }
  17694. return null;
  17695. };
  17696. /**
  17697. * sets the active camera of the scene using its name
  17698. * @param {string} name - the camera's name
  17699. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17700. * @see activeCamera
  17701. */
  17702. Scene.prototype.setActiveCameraByName = function (name) {
  17703. var camera = this.getCameraByName(name);
  17704. if (camera) {
  17705. this.activeCamera = camera;
  17706. return camera;
  17707. }
  17708. return null;
  17709. };
  17710. /**
  17711. * get a material using its id
  17712. * @param {string} the material's ID
  17713. * @return {BABYLON.Material|null} the material or null if none found.
  17714. */
  17715. Scene.prototype.getMaterialByID = function (id) {
  17716. for (var index = 0; index < this.materials.length; index++) {
  17717. if (this.materials[index].id === id) {
  17718. return this.materials[index];
  17719. }
  17720. }
  17721. return null;
  17722. };
  17723. /**
  17724. * get a material using its name
  17725. * @param {string} the material's name
  17726. * @return {BABYLON.Material|null} the material or null if none found.
  17727. */
  17728. Scene.prototype.getMaterialByName = function (name) {
  17729. for (var index = 0; index < this.materials.length; index++) {
  17730. if (this.materials[index].name === name) {
  17731. return this.materials[index];
  17732. }
  17733. }
  17734. return null;
  17735. };
  17736. Scene.prototype.getLensFlareSystemByName = function (name) {
  17737. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17738. if (this.lensFlareSystems[index].name === name) {
  17739. return this.lensFlareSystems[index];
  17740. }
  17741. }
  17742. return null;
  17743. };
  17744. Scene.prototype.getLensFlareSystemByID = function (id) {
  17745. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17746. if (this.lensFlareSystems[index].id === id) {
  17747. return this.lensFlareSystems[index];
  17748. }
  17749. }
  17750. return null;
  17751. };
  17752. Scene.prototype.getCameraByID = function (id) {
  17753. for (var index = 0; index < this.cameras.length; index++) {
  17754. if (this.cameras[index].id === id) {
  17755. return this.cameras[index];
  17756. }
  17757. }
  17758. return null;
  17759. };
  17760. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17761. for (var index = 0; index < this.cameras.length; index++) {
  17762. if (this.cameras[index].uniqueId === uniqueId) {
  17763. return this.cameras[index];
  17764. }
  17765. }
  17766. return null;
  17767. };
  17768. /**
  17769. * get a camera using its name
  17770. * @param {string} the camera's name
  17771. * @return {BABYLON.Camera|null} the camera or null if none found.
  17772. */
  17773. Scene.prototype.getCameraByName = function (name) {
  17774. for (var index = 0; index < this.cameras.length; index++) {
  17775. if (this.cameras[index].name === name) {
  17776. return this.cameras[index];
  17777. }
  17778. }
  17779. return null;
  17780. };
  17781. /**
  17782. * get a bone using its id
  17783. * @param {string} the bone's id
  17784. * @return {BABYLON.Bone|null} the bone or null if not found
  17785. */
  17786. Scene.prototype.getBoneByID = function (id) {
  17787. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17788. var skeleton = this.skeletons[skeletonIndex];
  17789. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17790. if (skeleton.bones[boneIndex].id === id) {
  17791. return skeleton.bones[boneIndex];
  17792. }
  17793. }
  17794. }
  17795. return null;
  17796. };
  17797. /**
  17798. * get a bone using its id
  17799. * @param {string} the bone's name
  17800. * @return {BABYLON.Bone|null} the bone or null if not found
  17801. */
  17802. Scene.prototype.getBoneByName = function (name) {
  17803. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17804. var skeleton = this.skeletons[skeletonIndex];
  17805. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17806. if (skeleton.bones[boneIndex].name === name) {
  17807. return skeleton.bones[boneIndex];
  17808. }
  17809. }
  17810. }
  17811. return null;
  17812. };
  17813. /**
  17814. * get a light node using its name
  17815. * @param {string} the light's name
  17816. * @return {BABYLON.Light|null} the light or null if none found.
  17817. */
  17818. Scene.prototype.getLightByName = function (name) {
  17819. for (var index = 0; index < this.lights.length; index++) {
  17820. if (this.lights[index].name === name) {
  17821. return this.lights[index];
  17822. }
  17823. }
  17824. return null;
  17825. };
  17826. /**
  17827. * get a light node using its ID
  17828. * @param {string} the light's id
  17829. * @return {BABYLON.Light|null} the light or null if none found.
  17830. */
  17831. Scene.prototype.getLightByID = function (id) {
  17832. for (var index = 0; index < this.lights.length; index++) {
  17833. if (this.lights[index].id === id) {
  17834. return this.lights[index];
  17835. }
  17836. }
  17837. return null;
  17838. };
  17839. /**
  17840. * get a light node using its scene-generated unique ID
  17841. * @param {number} the light's unique id
  17842. * @return {BABYLON.Light|null} the light or null if none found.
  17843. */
  17844. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17845. for (var index = 0; index < this.lights.length; index++) {
  17846. if (this.lights[index].uniqueId === uniqueId) {
  17847. return this.lights[index];
  17848. }
  17849. }
  17850. return null;
  17851. };
  17852. /**
  17853. * get a particle system by id
  17854. * @param id {number} the particle system id
  17855. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17856. */
  17857. Scene.prototype.getParticleSystemByID = function (id) {
  17858. for (var index = 0; index < this.particleSystems.length; index++) {
  17859. if (this.particleSystems[index].id === id) {
  17860. return this.particleSystems[index];
  17861. }
  17862. }
  17863. return null;
  17864. };
  17865. /**
  17866. * get a geometry using its ID
  17867. * @param {string} the geometry's id
  17868. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17869. */
  17870. Scene.prototype.getGeometryByID = function (id) {
  17871. for (var index = 0; index < this._geometries.length; index++) {
  17872. if (this._geometries[index].id === id) {
  17873. return this._geometries[index];
  17874. }
  17875. }
  17876. return null;
  17877. };
  17878. /**
  17879. * add a new geometry to this scene.
  17880. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17881. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17882. * @return {boolean} was the geometry added or not
  17883. */
  17884. Scene.prototype.pushGeometry = function (geometry, force) {
  17885. if (!force && this.getGeometryByID(geometry.id)) {
  17886. return false;
  17887. }
  17888. this._geometries.push(geometry);
  17889. //notify the collision coordinator
  17890. this.collisionCoordinator.onGeometryAdded(geometry);
  17891. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17892. return true;
  17893. };
  17894. /**
  17895. * Removes an existing geometry
  17896. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17897. * @return {boolean} was the geometry removed or not
  17898. */
  17899. Scene.prototype.removeGeometry = function (geometry) {
  17900. var index = this._geometries.indexOf(geometry);
  17901. if (index > -1) {
  17902. this._geometries.splice(index, 1);
  17903. //notify the collision coordinator
  17904. this.collisionCoordinator.onGeometryDeleted(geometry);
  17905. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17906. return true;
  17907. }
  17908. return false;
  17909. };
  17910. Scene.prototype.getGeometries = function () {
  17911. return this._geometries;
  17912. };
  17913. /**
  17914. * Get the first added mesh found of a given ID
  17915. * @param {string} id - the id to search for
  17916. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17917. */
  17918. Scene.prototype.getMeshByID = function (id) {
  17919. for (var index = 0; index < this.meshes.length; index++) {
  17920. if (this.meshes[index].id === id) {
  17921. return this.meshes[index];
  17922. }
  17923. }
  17924. return null;
  17925. };
  17926. Scene.prototype.getMeshesByID = function (id) {
  17927. return this.meshes.filter(function (m) {
  17928. return m.id === id;
  17929. });
  17930. };
  17931. /**
  17932. * Get a mesh with its auto-generated unique id
  17933. * @param {number} uniqueId - the unique id to search for
  17934. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17935. */
  17936. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17937. for (var index = 0; index < this.meshes.length; index++) {
  17938. if (this.meshes[index].uniqueId === uniqueId) {
  17939. return this.meshes[index];
  17940. }
  17941. }
  17942. return null;
  17943. };
  17944. /**
  17945. * Get a the last added mesh found of a given ID
  17946. * @param {string} id - the id to search for
  17947. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17948. */
  17949. Scene.prototype.getLastMeshByID = function (id) {
  17950. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17951. if (this.meshes[index].id === id) {
  17952. return this.meshes[index];
  17953. }
  17954. }
  17955. return null;
  17956. };
  17957. /**
  17958. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17959. * @param {string} id - the id to search for
  17960. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17961. */
  17962. Scene.prototype.getLastEntryByID = function (id) {
  17963. var index;
  17964. for (index = this.meshes.length - 1; index >= 0; index--) {
  17965. if (this.meshes[index].id === id) {
  17966. return this.meshes[index];
  17967. }
  17968. }
  17969. for (index = this.cameras.length - 1; index >= 0; index--) {
  17970. if (this.cameras[index].id === id) {
  17971. return this.cameras[index];
  17972. }
  17973. }
  17974. for (index = this.lights.length - 1; index >= 0; index--) {
  17975. if (this.lights[index].id === id) {
  17976. return this.lights[index];
  17977. }
  17978. }
  17979. return null;
  17980. };
  17981. Scene.prototype.getNodeByID = function (id) {
  17982. var mesh = this.getMeshByID(id);
  17983. if (mesh) {
  17984. return mesh;
  17985. }
  17986. var light = this.getLightByID(id);
  17987. if (light) {
  17988. return light;
  17989. }
  17990. var camera = this.getCameraByID(id);
  17991. if (camera) {
  17992. return camera;
  17993. }
  17994. var bone = this.getBoneByID(id);
  17995. return bone;
  17996. };
  17997. Scene.prototype.getNodeByName = function (name) {
  17998. var mesh = this.getMeshByName(name);
  17999. if (mesh) {
  18000. return mesh;
  18001. }
  18002. var light = this.getLightByName(name);
  18003. if (light) {
  18004. return light;
  18005. }
  18006. var camera = this.getCameraByName(name);
  18007. if (camera) {
  18008. return camera;
  18009. }
  18010. var bone = this.getBoneByName(name);
  18011. return bone;
  18012. };
  18013. Scene.prototype.getMeshByName = function (name) {
  18014. for (var index = 0; index < this.meshes.length; index++) {
  18015. if (this.meshes[index].name === name) {
  18016. return this.meshes[index];
  18017. }
  18018. }
  18019. return null;
  18020. };
  18021. Scene.prototype.getSoundByName = function (name) {
  18022. var index;
  18023. if (BABYLON.AudioEngine) {
  18024. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18025. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18026. return this.mainSoundTrack.soundCollection[index];
  18027. }
  18028. }
  18029. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18030. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18031. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18032. return this.soundTracks[sdIndex].soundCollection[index];
  18033. }
  18034. }
  18035. }
  18036. }
  18037. return null;
  18038. };
  18039. Scene.prototype.getLastSkeletonByID = function (id) {
  18040. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18041. if (this.skeletons[index].id === id) {
  18042. return this.skeletons[index];
  18043. }
  18044. }
  18045. return null;
  18046. };
  18047. Scene.prototype.getSkeletonById = function (id) {
  18048. for (var index = 0; index < this.skeletons.length; index++) {
  18049. if (this.skeletons[index].id === id) {
  18050. return this.skeletons[index];
  18051. }
  18052. }
  18053. return null;
  18054. };
  18055. Scene.prototype.getSkeletonByName = function (name) {
  18056. for (var index = 0; index < this.skeletons.length; index++) {
  18057. if (this.skeletons[index].name === name) {
  18058. return this.skeletons[index];
  18059. }
  18060. }
  18061. return null;
  18062. };
  18063. Scene.prototype.isActiveMesh = function (mesh) {
  18064. return (this._activeMeshes.indexOf(mesh) !== -1);
  18065. };
  18066. Object.defineProperty(Scene.prototype, "uid", {
  18067. /**
  18068. * Return a unique id as a string which can serve as an identifier for the scene
  18069. */
  18070. get: function () {
  18071. if (!this._uid) {
  18072. this._uid = BABYLON.Tools.RandomId();
  18073. }
  18074. return this._uid;
  18075. },
  18076. enumerable: true,
  18077. configurable: true
  18078. });
  18079. /**
  18080. * Add an externaly attached data from its key.
  18081. * This method call will fail and return false, if such key already exists.
  18082. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18083. * @param key the unique key that identifies the data
  18084. * @param data the data object to associate to the key for this Engine instance
  18085. * @return true if no such key were already present and the data was added successfully, false otherwise
  18086. */
  18087. Scene.prototype.addExternalData = function (key, data) {
  18088. return this._externalData.add(key, data);
  18089. };
  18090. /**
  18091. * Get an externaly attached data from its key
  18092. * @param key the unique key that identifies the data
  18093. * @return the associated data, if present (can be null), or undefined if not present
  18094. */
  18095. Scene.prototype.getExternalData = function (key) {
  18096. return this._externalData.get(key);
  18097. };
  18098. /**
  18099. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18100. * @param key the unique key that identifies the data
  18101. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18102. * @return the associated data, can be null if the factory returned null.
  18103. */
  18104. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18105. return this._externalData.getOrAddWithFactory(key, factory);
  18106. };
  18107. /**
  18108. * Remove an externaly attached data from the Engine instance
  18109. * @param key the unique key that identifies the data
  18110. * @return true if the data was successfully removed, false if it doesn't exist
  18111. */
  18112. Scene.prototype.removeExternalData = function (key) {
  18113. return this._externalData.remove(key);
  18114. };
  18115. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18116. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18117. var material = subMesh.getMaterial();
  18118. if (mesh.showSubMeshesBoundingBox) {
  18119. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18120. }
  18121. if (material) {
  18122. // Render targets
  18123. if (material.getRenderTargetTextures) {
  18124. if (this._processedMaterials.indexOf(material) === -1) {
  18125. this._processedMaterials.push(material);
  18126. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18127. }
  18128. }
  18129. // Dispatch
  18130. this._activeIndices.addCount(subMesh.indexCount, false);
  18131. this._renderingManager.dispatch(subMesh);
  18132. }
  18133. }
  18134. };
  18135. Scene.prototype._isInIntermediateRendering = function () {
  18136. return this._intermediateRendering;
  18137. };
  18138. Scene.prototype._evaluateActiveMeshes = function () {
  18139. this.activeCamera._activeMeshes.reset();
  18140. this._activeMeshes.reset();
  18141. this._renderingManager.reset();
  18142. this._processedMaterials.reset();
  18143. this._activeParticleSystems.reset();
  18144. this._activeSkeletons.reset();
  18145. this._softwareSkinnedMeshes.reset();
  18146. this._boundingBoxRenderer.reset();
  18147. this._edgesRenderers.reset();
  18148. // Meshes
  18149. var meshes;
  18150. var len;
  18151. if (this._selectionOctree) {
  18152. var selection = this._selectionOctree.select(this._frustumPlanes);
  18153. meshes = selection.data;
  18154. len = selection.length;
  18155. }
  18156. else {
  18157. len = this.meshes.length;
  18158. meshes = this.meshes;
  18159. }
  18160. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18161. var mesh = meshes[meshIndex];
  18162. if (mesh.isBlocked) {
  18163. continue;
  18164. }
  18165. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18166. if (!mesh.isReady() || !mesh.isEnabled()) {
  18167. continue;
  18168. }
  18169. mesh.computeWorldMatrix();
  18170. // Intersections
  18171. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18172. this._meshesForIntersections.pushNoDuplicate(mesh);
  18173. }
  18174. // Switch to current LOD
  18175. var meshLOD = mesh.getLOD(this.activeCamera);
  18176. if (!meshLOD) {
  18177. continue;
  18178. }
  18179. mesh._preActivate();
  18180. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18181. this._activeMeshes.push(mesh);
  18182. this.activeCamera._activeMeshes.push(mesh);
  18183. mesh._activate(this._renderId);
  18184. this._activeMesh(mesh, meshLOD);
  18185. }
  18186. }
  18187. // Particle systems
  18188. this._particlesDuration.beginMonitoring();
  18189. var beforeParticlesDate = BABYLON.Tools.Now;
  18190. if (this.particlesEnabled) {
  18191. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18192. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18193. var particleSystem = this.particleSystems[particleIndex];
  18194. if (!particleSystem.isStarted()) {
  18195. continue;
  18196. }
  18197. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18198. this._activeParticleSystems.push(particleSystem);
  18199. particleSystem.animate();
  18200. }
  18201. }
  18202. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18203. }
  18204. this._particlesDuration.endMonitoring(false);
  18205. };
  18206. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18207. if (mesh.skeleton && this.skeletonsEnabled) {
  18208. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18209. mesh.skeleton.prepare();
  18210. }
  18211. if (!mesh.computeBonesUsingShaders) {
  18212. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18213. }
  18214. }
  18215. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18216. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18217. }
  18218. if (sourceMesh._edgesRenderer) {
  18219. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18220. }
  18221. if (mesh && mesh.subMeshes) {
  18222. // Submeshes Octrees
  18223. var len;
  18224. var subMeshes;
  18225. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18226. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18227. len = intersections.length;
  18228. subMeshes = intersections.data;
  18229. }
  18230. else {
  18231. subMeshes = mesh.subMeshes;
  18232. len = subMeshes.length;
  18233. }
  18234. for (var subIndex = 0; subIndex < len; subIndex++) {
  18235. var subMesh = subMeshes[subIndex];
  18236. this._evaluateSubMesh(subMesh, mesh);
  18237. }
  18238. }
  18239. };
  18240. Scene.prototype.updateTransformMatrix = function (force) {
  18241. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18242. };
  18243. Scene.prototype._renderForCamera = function (camera) {
  18244. var engine = this._engine;
  18245. var startTime = BABYLON.Tools.Now;
  18246. this.activeCamera = camera;
  18247. if (!this.activeCamera)
  18248. throw new Error("Active camera not set");
  18249. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18250. // Viewport
  18251. engine.setViewport(this.activeCamera.viewport);
  18252. // Camera
  18253. this.resetCachedMaterial();
  18254. this._renderId++;
  18255. this.updateTransformMatrix();
  18256. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18257. // Meshes
  18258. this._evaluateActiveMeshesDuration.beginMonitoring();
  18259. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18260. this._evaluateActiveMeshes();
  18261. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18262. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18263. // Software skinning
  18264. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18265. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18266. mesh.applySkeleton(mesh.skeleton);
  18267. }
  18268. // Render targets
  18269. this._renderTargetsDuration.beginMonitoring();
  18270. var needsRestoreFrameBuffer = false;
  18271. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18272. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18273. this._intermediateRendering = true;
  18274. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18275. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18276. var renderTarget = this._renderTargets.data[renderIndex];
  18277. if (renderTarget._shouldRender()) {
  18278. this._renderId++;
  18279. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18280. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18281. }
  18282. }
  18283. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18284. this._intermediateRendering = false;
  18285. this._renderId++;
  18286. needsRestoreFrameBuffer = true; // Restore back buffer
  18287. }
  18288. // Render HighlightLayer Texture
  18289. var stencilState = this._engine.getStencilBuffer();
  18290. var renderhighlights = false;
  18291. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18292. this._intermediateRendering = true;
  18293. for (var i = 0; i < this.highlightLayers.length; i++) {
  18294. var highlightLayer = this.highlightLayers[i];
  18295. if (highlightLayer.shouldRender() &&
  18296. (!highlightLayer.camera ||
  18297. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18298. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18299. renderhighlights = true;
  18300. var renderTarget = highlightLayer._mainTexture;
  18301. if (renderTarget._shouldRender()) {
  18302. this._renderId++;
  18303. renderTarget.render(false, false);
  18304. needsRestoreFrameBuffer = true;
  18305. }
  18306. }
  18307. }
  18308. this._intermediateRendering = false;
  18309. this._renderId++;
  18310. }
  18311. if (needsRestoreFrameBuffer) {
  18312. engine.restoreDefaultFramebuffer();
  18313. }
  18314. this._renderTargetsDuration.endMonitoring(false);
  18315. // Prepare Frame
  18316. this.postProcessManager._prepareFrame();
  18317. this._renderDuration.beginMonitoring();
  18318. // Backgrounds
  18319. var layerIndex;
  18320. var layer;
  18321. if (this.layers.length) {
  18322. engine.setDepthBuffer(false);
  18323. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18324. layer = this.layers[layerIndex];
  18325. if (layer.isBackground) {
  18326. layer.render();
  18327. }
  18328. }
  18329. engine.setDepthBuffer(true);
  18330. }
  18331. // Render
  18332. BABYLON.Tools.StartPerformanceCounter("Main render");
  18333. // Activate HighlightLayer stencil
  18334. if (renderhighlights) {
  18335. this._engine.setStencilBuffer(true);
  18336. }
  18337. this._renderingManager.render(null, null, true, true);
  18338. // Restore HighlightLayer stencil
  18339. if (renderhighlights) {
  18340. this._engine.setStencilBuffer(stencilState);
  18341. }
  18342. BABYLON.Tools.EndPerformanceCounter("Main render");
  18343. // Bounding boxes
  18344. this._boundingBoxRenderer.render();
  18345. // Edges
  18346. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18347. this._edgesRenderers.data[edgesRendererIndex].render();
  18348. }
  18349. // Lens flares
  18350. if (this.lensFlaresEnabled) {
  18351. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18352. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18353. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18354. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18355. lensFlareSystem.render();
  18356. }
  18357. }
  18358. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18359. }
  18360. // Foregrounds
  18361. if (this.layers.length) {
  18362. engine.setDepthBuffer(false);
  18363. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18364. layer = this.layers[layerIndex];
  18365. if (!layer.isBackground) {
  18366. layer.render();
  18367. }
  18368. }
  18369. engine.setDepthBuffer(true);
  18370. }
  18371. // Highlight Layer
  18372. if (renderhighlights) {
  18373. engine.setDepthBuffer(false);
  18374. for (var i = 0; i < this.highlightLayers.length; i++) {
  18375. if (this.highlightLayers[i].shouldRender()) {
  18376. this.highlightLayers[i].render();
  18377. }
  18378. }
  18379. engine.setDepthBuffer(true);
  18380. }
  18381. this._renderDuration.endMonitoring(false);
  18382. // Finalize frame
  18383. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18384. // Update camera
  18385. this.activeCamera._updateFromScene();
  18386. // Reset some special arrays
  18387. this._renderTargets.reset();
  18388. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18389. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18390. };
  18391. Scene.prototype._processSubCameras = function (camera) {
  18392. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18393. this._renderForCamera(camera);
  18394. return;
  18395. }
  18396. // rig cameras
  18397. for (var index = 0; index < camera._rigCameras.length; index++) {
  18398. this._renderForCamera(camera._rigCameras[index]);
  18399. }
  18400. this.activeCamera = camera;
  18401. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18402. // Update camera
  18403. this.activeCamera._updateFromScene();
  18404. };
  18405. Scene.prototype._checkIntersections = function () {
  18406. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18407. var sourceMesh = this._meshesForIntersections.data[index];
  18408. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18409. var action = sourceMesh.actionManager.actions[actionIndex];
  18410. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18411. var parameters = action.getTriggerParameter();
  18412. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18413. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18414. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18415. if (areIntersecting && currentIntersectionInProgress === -1) {
  18416. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18417. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18418. sourceMesh._intersectionsInProgress.push(otherMesh);
  18419. }
  18420. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18421. sourceMesh._intersectionsInProgress.push(otherMesh);
  18422. }
  18423. }
  18424. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18425. //They intersected, and now they don't.
  18426. //is this trigger an exit trigger? execute an event.
  18427. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18428. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18429. }
  18430. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18431. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18432. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18433. }
  18434. }
  18435. }
  18436. }
  18437. }
  18438. };
  18439. Scene.prototype.render = function () {
  18440. this._lastFrameDuration.beginMonitoring();
  18441. this._particlesDuration.fetchNewFrame();
  18442. this._spritesDuration.fetchNewFrame();
  18443. this._activeParticles.fetchNewFrame();
  18444. this._renderDuration.fetchNewFrame();
  18445. this._renderTargetsDuration.fetchNewFrame();
  18446. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18447. this._totalVertices.fetchNewFrame();
  18448. this._activeIndices.fetchNewFrame();
  18449. this._activeBones.fetchNewFrame();
  18450. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18451. this._meshesForIntersections.reset();
  18452. this.resetCachedMaterial();
  18453. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18454. // Actions
  18455. if (this.actionManager) {
  18456. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18457. }
  18458. //Simplification Queue
  18459. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18460. this.simplificationQueue.executeNext();
  18461. }
  18462. // Animations
  18463. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18464. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18465. this._animate();
  18466. // Physics
  18467. if (this._physicsEngine) {
  18468. BABYLON.Tools.StartPerformanceCounter("Physics");
  18469. this._physicsEngine._step(deltaTime / 1000.0);
  18470. BABYLON.Tools.EndPerformanceCounter("Physics");
  18471. }
  18472. // Before render
  18473. this.onBeforeRenderObservable.notifyObservers(this);
  18474. // Customs render targets
  18475. this._renderTargetsDuration.beginMonitoring();
  18476. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18477. var engine = this.getEngine();
  18478. var currentActiveCamera = this.activeCamera;
  18479. if (this.renderTargetsEnabled) {
  18480. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18481. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18482. var renderTarget = this.customRenderTargets[customIndex];
  18483. if (renderTarget._shouldRender()) {
  18484. this._renderId++;
  18485. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18486. if (!this.activeCamera)
  18487. throw new Error("Active camera not set");
  18488. // Viewport
  18489. engine.setViewport(this.activeCamera.viewport);
  18490. // Camera
  18491. this.updateTransformMatrix();
  18492. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18493. }
  18494. }
  18495. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18496. this._renderId++;
  18497. }
  18498. if (this.customRenderTargets.length > 0) {
  18499. engine.restoreDefaultFramebuffer();
  18500. }
  18501. this._renderTargetsDuration.endMonitoring();
  18502. this.activeCamera = currentActiveCamera;
  18503. // Procedural textures
  18504. if (this.proceduralTexturesEnabled) {
  18505. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18506. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18507. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18508. if (proceduralTexture._shouldRender()) {
  18509. proceduralTexture.render();
  18510. }
  18511. }
  18512. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18513. }
  18514. // Clear
  18515. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18516. // Shadows
  18517. if (this.shadowsEnabled) {
  18518. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18519. var light = this.lights[lightIndex];
  18520. var shadowGenerator = light.getShadowGenerator();
  18521. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18522. this._renderTargets.push(shadowGenerator.getShadowMap());
  18523. }
  18524. }
  18525. }
  18526. // Depth renderer
  18527. if (this._depthRenderer) {
  18528. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18529. }
  18530. // RenderPipeline
  18531. this.postProcessRenderPipelineManager.update();
  18532. // Multi-cameras?
  18533. if (this.activeCameras.length > 0) {
  18534. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18535. if (cameraIndex > 0) {
  18536. this._engine.clear(0, false, true, true);
  18537. }
  18538. this._processSubCameras(this.activeCameras[cameraIndex]);
  18539. }
  18540. }
  18541. else {
  18542. if (!this.activeCamera) {
  18543. throw new Error("No camera defined");
  18544. }
  18545. this._processSubCameras(this.activeCamera);
  18546. }
  18547. // Intersection checks
  18548. this._checkIntersections();
  18549. // Update the audio listener attached to the camera
  18550. if (BABYLON.AudioEngine) {
  18551. this._updateAudioParameters();
  18552. }
  18553. // After render
  18554. if (this.afterRender) {
  18555. this.afterRender();
  18556. }
  18557. this.onAfterRenderObservable.notifyObservers(this);
  18558. // Cleaning
  18559. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18560. this._toBeDisposed.data[index].dispose();
  18561. this._toBeDisposed[index] = null;
  18562. }
  18563. this._toBeDisposed.reset();
  18564. if (this.dumpNextRenderTargets) {
  18565. this.dumpNextRenderTargets = false;
  18566. }
  18567. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18568. this._lastFrameDuration.endMonitoring();
  18569. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18570. this._totalLightsCounter.addCount(this.lights.length, true);
  18571. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18572. this._totalTexturesCounter.addCount(this.textures.length, true);
  18573. this._activeBones.addCount(0, true);
  18574. this._activeIndices.addCount(0, true);
  18575. this._activeParticles.addCount(0, true);
  18576. };
  18577. Scene.prototype._updateAudioParameters = function () {
  18578. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18579. return;
  18580. }
  18581. var listeningCamera;
  18582. var audioEngine = BABYLON.Engine.audioEngine;
  18583. if (this.activeCameras.length > 0) {
  18584. listeningCamera = this.activeCameras[0];
  18585. }
  18586. else {
  18587. listeningCamera = this.activeCamera;
  18588. }
  18589. if (listeningCamera && audioEngine.canUseWebAudio) {
  18590. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18591. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18592. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18593. cameraDirection.normalize();
  18594. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18595. var i;
  18596. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18597. var sound = this.mainSoundTrack.soundCollection[i];
  18598. if (sound.useCustomAttenuation) {
  18599. sound.updateDistanceFromListener();
  18600. }
  18601. }
  18602. for (i = 0; i < this.soundTracks.length; i++) {
  18603. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18604. sound = this.soundTracks[i].soundCollection[j];
  18605. if (sound.useCustomAttenuation) {
  18606. sound.updateDistanceFromListener();
  18607. }
  18608. }
  18609. }
  18610. }
  18611. };
  18612. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18613. // Audio
  18614. get: function () {
  18615. return this._audioEnabled;
  18616. },
  18617. set: function (value) {
  18618. this._audioEnabled = value;
  18619. if (BABYLON.AudioEngine) {
  18620. if (this._audioEnabled) {
  18621. this._enableAudio();
  18622. }
  18623. else {
  18624. this._disableAudio();
  18625. }
  18626. }
  18627. },
  18628. enumerable: true,
  18629. configurable: true
  18630. });
  18631. Scene.prototype._disableAudio = function () {
  18632. var i;
  18633. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18634. this.mainSoundTrack.soundCollection[i].pause();
  18635. }
  18636. for (i = 0; i < this.soundTracks.length; i++) {
  18637. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18638. this.soundTracks[i].soundCollection[j].pause();
  18639. }
  18640. }
  18641. };
  18642. Scene.prototype._enableAudio = function () {
  18643. var i;
  18644. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18645. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18646. this.mainSoundTrack.soundCollection[i].play();
  18647. }
  18648. }
  18649. for (i = 0; i < this.soundTracks.length; i++) {
  18650. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18651. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18652. this.soundTracks[i].soundCollection[j].play();
  18653. }
  18654. }
  18655. }
  18656. };
  18657. Object.defineProperty(Scene.prototype, "headphone", {
  18658. get: function () {
  18659. return this._headphone;
  18660. },
  18661. set: function (value) {
  18662. this._headphone = value;
  18663. if (BABYLON.AudioEngine) {
  18664. if (this._headphone) {
  18665. this._switchAudioModeForHeadphones();
  18666. }
  18667. else {
  18668. this._switchAudioModeForNormalSpeakers();
  18669. }
  18670. }
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. Scene.prototype._switchAudioModeForHeadphones = function () {
  18676. this.mainSoundTrack.switchPanningModelToHRTF();
  18677. for (var i = 0; i < this.soundTracks.length; i++) {
  18678. this.soundTracks[i].switchPanningModelToHRTF();
  18679. }
  18680. };
  18681. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18682. this.mainSoundTrack.switchPanningModelToEqualPower();
  18683. for (var i = 0; i < this.soundTracks.length; i++) {
  18684. this.soundTracks[i].switchPanningModelToEqualPower();
  18685. }
  18686. };
  18687. Scene.prototype.enableDepthRenderer = function () {
  18688. if (this._depthRenderer) {
  18689. return this._depthRenderer;
  18690. }
  18691. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18692. return this._depthRenderer;
  18693. };
  18694. Scene.prototype.disableDepthRenderer = function () {
  18695. if (!this._depthRenderer) {
  18696. return;
  18697. }
  18698. this._depthRenderer.dispose();
  18699. this._depthRenderer = null;
  18700. };
  18701. Scene.prototype.freezeMaterials = function () {
  18702. for (var i = 0; i < this.materials.length; i++) {
  18703. this.materials[i].freeze();
  18704. }
  18705. };
  18706. Scene.prototype.unfreezeMaterials = function () {
  18707. for (var i = 0; i < this.materials.length; i++) {
  18708. this.materials[i].unfreeze();
  18709. }
  18710. };
  18711. Scene.prototype.dispose = function () {
  18712. this.beforeRender = null;
  18713. this.afterRender = null;
  18714. this.skeletons = [];
  18715. this._boundingBoxRenderer.dispose();
  18716. if (this._depthRenderer) {
  18717. this._depthRenderer.dispose();
  18718. }
  18719. // Debug layer
  18720. if (this._debugLayer) {
  18721. this._debugLayer.hide();
  18722. }
  18723. // Events
  18724. this.onDisposeObservable.notifyObservers(this);
  18725. this.onDisposeObservable.clear();
  18726. this.onBeforeRenderObservable.clear();
  18727. this.onAfterRenderObservable.clear();
  18728. this.detachControl();
  18729. // Release sounds & sounds tracks
  18730. if (BABYLON.AudioEngine) {
  18731. this.disposeSounds();
  18732. }
  18733. // Detach cameras
  18734. var canvas = this._engine.getRenderingCanvas();
  18735. var index;
  18736. for (index = 0; index < this.cameras.length; index++) {
  18737. this.cameras[index].detachControl(canvas);
  18738. }
  18739. // Release lights
  18740. while (this.lights.length) {
  18741. this.lights[0].dispose();
  18742. }
  18743. // Release meshes
  18744. while (this.meshes.length) {
  18745. this.meshes[0].dispose(true);
  18746. }
  18747. // Release cameras
  18748. while (this.cameras.length) {
  18749. this.cameras[0].dispose();
  18750. }
  18751. // Release materials
  18752. while (this.materials.length) {
  18753. this.materials[0].dispose();
  18754. }
  18755. // Release particles
  18756. while (this.particleSystems.length) {
  18757. this.particleSystems[0].dispose();
  18758. }
  18759. // Release sprites
  18760. while (this.spriteManagers.length) {
  18761. this.spriteManagers[0].dispose();
  18762. }
  18763. // Release layers
  18764. while (this.layers.length) {
  18765. this.layers[0].dispose();
  18766. }
  18767. while (this.highlightLayers.length) {
  18768. this.highlightLayers[0].dispose();
  18769. }
  18770. // Release textures
  18771. while (this.textures.length) {
  18772. this.textures[0].dispose();
  18773. }
  18774. // Post-processes
  18775. this.postProcessManager.dispose();
  18776. // Physics
  18777. if (this._physicsEngine) {
  18778. this.disablePhysicsEngine();
  18779. }
  18780. // Remove from engine
  18781. index = this._engine.scenes.indexOf(this);
  18782. if (index > -1) {
  18783. this._engine.scenes.splice(index, 1);
  18784. }
  18785. this._engine.wipeCaches();
  18786. };
  18787. // Release sounds & sounds tracks
  18788. Scene.prototype.disposeSounds = function () {
  18789. this.mainSoundTrack.dispose();
  18790. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18791. this.soundTracks[scIndex].dispose();
  18792. }
  18793. };
  18794. // Octrees
  18795. Scene.prototype.getWorldExtends = function () {
  18796. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18797. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18798. for (var index = 0; index < this.meshes.length; index++) {
  18799. var mesh = this.meshes[index];
  18800. mesh.computeWorldMatrix(true);
  18801. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18802. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18803. BABYLON.Tools.CheckExtends(minBox, min, max);
  18804. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18805. }
  18806. return {
  18807. min: min,
  18808. max: max
  18809. };
  18810. };
  18811. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18812. if (maxCapacity === void 0) { maxCapacity = 64; }
  18813. if (maxDepth === void 0) { maxDepth = 2; }
  18814. if (!this._selectionOctree) {
  18815. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18816. }
  18817. var worldExtends = this.getWorldExtends();
  18818. // Update octree
  18819. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18820. return this._selectionOctree;
  18821. };
  18822. // Picking
  18823. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18824. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18825. var engine = this._engine;
  18826. if (!camera) {
  18827. if (!this.activeCamera)
  18828. throw new Error("Active camera not set");
  18829. camera = this.activeCamera;
  18830. }
  18831. var cameraViewport = camera.viewport;
  18832. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18833. // Moving coordinates to local viewport world
  18834. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18835. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18836. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18837. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18838. };
  18839. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18840. var engine = this._engine;
  18841. if (!camera) {
  18842. if (!this.activeCamera)
  18843. throw new Error("Active camera not set");
  18844. camera = this.activeCamera;
  18845. }
  18846. var cameraViewport = camera.viewport;
  18847. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18848. var identity = BABYLON.Matrix.Identity();
  18849. // Moving coordinates to local viewport world
  18850. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18851. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18852. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18853. };
  18854. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18855. var pickingInfo = null;
  18856. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18857. var mesh = this.meshes[meshIndex];
  18858. if (predicate) {
  18859. if (!predicate(mesh)) {
  18860. continue;
  18861. }
  18862. }
  18863. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18864. continue;
  18865. }
  18866. var world = mesh.getWorldMatrix();
  18867. var ray = rayFunction(world);
  18868. var result = mesh.intersects(ray, fastCheck);
  18869. if (!result || !result.hit)
  18870. continue;
  18871. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18872. continue;
  18873. pickingInfo = result;
  18874. if (fastCheck) {
  18875. break;
  18876. }
  18877. }
  18878. return pickingInfo || new BABYLON.PickingInfo();
  18879. };
  18880. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18881. var pickingInfos = new Array();
  18882. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18883. var mesh = this.meshes[meshIndex];
  18884. if (predicate) {
  18885. if (!predicate(mesh)) {
  18886. continue;
  18887. }
  18888. }
  18889. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18890. continue;
  18891. }
  18892. var world = mesh.getWorldMatrix();
  18893. var ray = rayFunction(world);
  18894. var result = mesh.intersects(ray, false);
  18895. if (!result || !result.hit)
  18896. continue;
  18897. pickingInfos.push(result);
  18898. }
  18899. return pickingInfos;
  18900. };
  18901. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18902. var pickingInfo = null;
  18903. camera = camera || this.activeCamera;
  18904. if (this.spriteManagers.length > 0) {
  18905. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18906. var spriteManager = this.spriteManagers[spriteIndex];
  18907. if (!spriteManager.isPickable) {
  18908. continue;
  18909. }
  18910. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18911. if (!result || !result.hit)
  18912. continue;
  18913. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18914. continue;
  18915. pickingInfo = result;
  18916. if (fastCheck) {
  18917. break;
  18918. }
  18919. }
  18920. }
  18921. return pickingInfo || new BABYLON.PickingInfo();
  18922. };
  18923. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18924. /// <param name="x">X position on screen</param>
  18925. /// <param name="y">Y position on screen</param>
  18926. /// <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>
  18927. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18928. /// <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>
  18929. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18930. var _this = this;
  18931. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18932. };
  18933. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18934. /// <param name="x">X position on screen</param>
  18935. /// <param name="y">Y position on screen</param>
  18936. /// <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>
  18937. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18938. /// <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>
  18939. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18940. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18941. };
  18942. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18943. var _this = this;
  18944. return this._internalPick(function (world) {
  18945. if (!_this._pickWithRayInverseMatrix) {
  18946. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18947. }
  18948. world.invertToRef(_this._pickWithRayInverseMatrix);
  18949. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18950. }, predicate, fastCheck);
  18951. };
  18952. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18953. /// <param name="x">X position on screen</param>
  18954. /// <param name="y">Y position on screen</param>
  18955. /// <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>
  18956. /// <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>
  18957. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18958. var _this = this;
  18959. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18960. };
  18961. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18962. /// <param name="ray">Ray to use</param>
  18963. /// <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>
  18964. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18965. var _this = this;
  18966. return this._internalMultiPick(function (world) {
  18967. if (!_this._pickWithRayInverseMatrix) {
  18968. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18969. }
  18970. world.invertToRef(_this._pickWithRayInverseMatrix);
  18971. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18972. }, predicate);
  18973. };
  18974. Scene.prototype.setPointerOverMesh = function (mesh) {
  18975. if (this._pointerOverMesh === mesh) {
  18976. return;
  18977. }
  18978. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18979. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18980. }
  18981. this._pointerOverMesh = mesh;
  18982. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18983. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18984. }
  18985. };
  18986. Scene.prototype.getPointerOverMesh = function () {
  18987. return this._pointerOverMesh;
  18988. };
  18989. Scene.prototype.setPointerOverSprite = function (sprite) {
  18990. if (this._pointerOverSprite === sprite) {
  18991. return;
  18992. }
  18993. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18994. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18995. }
  18996. this._pointerOverSprite = sprite;
  18997. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18998. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18999. }
  19000. };
  19001. Scene.prototype.getPointerOverSprite = function () {
  19002. return this._pointerOverSprite;
  19003. };
  19004. // Physics
  19005. Scene.prototype.getPhysicsEngine = function () {
  19006. return this._physicsEngine;
  19007. };
  19008. /**
  19009. * Enables physics to the current scene
  19010. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19011. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19012. * @return {boolean} was the physics engine initialized
  19013. */
  19014. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19015. if (this._physicsEngine) {
  19016. return true;
  19017. }
  19018. try {
  19019. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19020. return true;
  19021. }
  19022. catch (e) {
  19023. BABYLON.Tools.Error(e.message);
  19024. return false;
  19025. }
  19026. };
  19027. Scene.prototype.disablePhysicsEngine = function () {
  19028. if (!this._physicsEngine) {
  19029. return;
  19030. }
  19031. this._physicsEngine.dispose();
  19032. this._physicsEngine = undefined;
  19033. };
  19034. Scene.prototype.isPhysicsEnabled = function () {
  19035. return this._physicsEngine !== undefined;
  19036. };
  19037. /**
  19038. *
  19039. * Sets the gravity of the physics engine (and NOT of the scene)
  19040. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19041. */
  19042. Scene.prototype.setGravity = function (gravity) {
  19043. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19044. if (!this._physicsEngine) {
  19045. return;
  19046. }
  19047. this._physicsEngine.setGravity(gravity);
  19048. };
  19049. /**
  19050. * Legacy support, using the new API
  19051. * @Deprecated
  19052. */
  19053. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19054. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19055. if (parts.parts) {
  19056. options = parts;
  19057. parts = parts.parts;
  19058. }
  19059. var mainMesh = parts[0].mesh;
  19060. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19061. for (var index = 1; index < parts.length; index++) {
  19062. var mesh = parts[index].mesh;
  19063. if (mesh.parent !== mainMesh) {
  19064. mesh.position = mesh.position.subtract(mainMesh.position);
  19065. mesh.parent = mainMesh;
  19066. }
  19067. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19068. }
  19069. mainMesh.physicsImpostor.forceUpdate();
  19070. };
  19071. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19072. var mesh = compound.parts[0].mesh;
  19073. mesh.physicsImpostor.dispose();
  19074. mesh.physicsImpostor = null;
  19075. };
  19076. // Misc.
  19077. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19078. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19079. // Light
  19080. if (this.lights.length === 0) {
  19081. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19082. }
  19083. // Camera
  19084. if (!this.activeCamera) {
  19085. // Compute position
  19086. var worldExtends = this.getWorldExtends();
  19087. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19088. var camera;
  19089. if (createArcRotateCamera) {
  19090. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19091. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19092. camera.setTarget(worldCenter);
  19093. }
  19094. else {
  19095. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19096. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19097. camera.setTarget(worldCenter);
  19098. }
  19099. this.activeCamera = camera;
  19100. }
  19101. };
  19102. // Tags
  19103. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19104. if (tagsQuery === undefined) {
  19105. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19106. return list;
  19107. }
  19108. var listByTags = [];
  19109. forEach = forEach || (function (item) { return; });
  19110. for (var i in list) {
  19111. var item = list[i];
  19112. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19113. listByTags.push(item);
  19114. forEach(item);
  19115. }
  19116. }
  19117. return listByTags;
  19118. };
  19119. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19120. return this._getByTags(this.meshes, tagsQuery, forEach);
  19121. };
  19122. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19123. return this._getByTags(this.cameras, tagsQuery, forEach);
  19124. };
  19125. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19126. return this._getByTags(this.lights, tagsQuery, forEach);
  19127. };
  19128. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19129. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19130. };
  19131. /**
  19132. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19133. * This allowed control for front to back rendering or reversly depending of the special needs.
  19134. *
  19135. * @param renderingGroupId The rendering group id corresponding to its index
  19136. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19137. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19138. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19139. */
  19140. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19141. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19142. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19143. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19144. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19145. };
  19146. /**
  19147. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19148. *
  19149. * @param renderingGroupId The rendering group id corresponding to its index
  19150. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19151. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19152. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19153. */
  19154. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19155. if (depth === void 0) { depth = true; }
  19156. if (stencil === void 0) { stencil = true; }
  19157. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19158. };
  19159. return Scene;
  19160. }());
  19161. // Statics
  19162. Scene._FOGMODE_NONE = 0;
  19163. Scene._FOGMODE_EXP = 1;
  19164. Scene._FOGMODE_EXP2 = 2;
  19165. Scene._FOGMODE_LINEAR = 3;
  19166. Scene.MinDeltaTime = 1.0;
  19167. Scene.MaxDeltaTime = 1000.0;
  19168. BABYLON.Scene = Scene;
  19169. })(BABYLON || (BABYLON = {}));
  19170. //# sourceMappingURL=babylon.scene.js.map
  19171. var BABYLON;
  19172. (function (BABYLON) {
  19173. var Buffer = (function () {
  19174. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19175. if (engine instanceof BABYLON.Mesh) {
  19176. this._engine = engine.getScene().getEngine();
  19177. }
  19178. else {
  19179. this._engine = engine;
  19180. }
  19181. this._updatable = updatable;
  19182. this._data = data;
  19183. this._strideSize = stride;
  19184. if (!postponeInternalCreation) {
  19185. this.create();
  19186. }
  19187. this._instanced = instanced;
  19188. }
  19189. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19190. // a lot of these parameters are ignored as they are overriden by the buffer
  19191. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19192. };
  19193. // Properties
  19194. Buffer.prototype.isUpdatable = function () {
  19195. return this._updatable;
  19196. };
  19197. Buffer.prototype.getData = function () {
  19198. return this._data;
  19199. };
  19200. Buffer.prototype.getBuffer = function () {
  19201. return this._buffer;
  19202. };
  19203. Buffer.prototype.getStrideSize = function () {
  19204. return this._strideSize;
  19205. };
  19206. Buffer.prototype.getIsInstanced = function () {
  19207. return this._instanced;
  19208. };
  19209. // Methods
  19210. Buffer.prototype.create = function (data) {
  19211. if (!data && this._buffer) {
  19212. return; // nothing to do
  19213. }
  19214. data = data || this._data;
  19215. if (!this._buffer) {
  19216. if (this._updatable) {
  19217. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19218. this._data = data;
  19219. }
  19220. else {
  19221. this._buffer = this._engine.createVertexBuffer(data);
  19222. }
  19223. }
  19224. else if (this._updatable) {
  19225. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19226. this._data = data;
  19227. }
  19228. };
  19229. Buffer.prototype.update = function (data) {
  19230. this.create(data);
  19231. };
  19232. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19233. if (!this._buffer) {
  19234. return;
  19235. }
  19236. if (this._updatable) {
  19237. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19238. this._data = null;
  19239. }
  19240. };
  19241. Buffer.prototype.dispose = function () {
  19242. if (!this._buffer) {
  19243. return;
  19244. }
  19245. if (this._engine._releaseBuffer(this._buffer)) {
  19246. this._buffer = null;
  19247. }
  19248. };
  19249. return Buffer;
  19250. }());
  19251. BABYLON.Buffer = Buffer;
  19252. })(BABYLON || (BABYLON = {}));
  19253. //# sourceMappingURL=babylon.buffer.js.map
  19254. var BABYLON;
  19255. (function (BABYLON) {
  19256. var VertexBuffer = (function () {
  19257. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19258. if (!stride) {
  19259. // Deduce stride from kind
  19260. switch (kind) {
  19261. case VertexBuffer.PositionKind:
  19262. stride = 3;
  19263. break;
  19264. case VertexBuffer.NormalKind:
  19265. stride = 3;
  19266. break;
  19267. case VertexBuffer.UVKind:
  19268. case VertexBuffer.UV2Kind:
  19269. case VertexBuffer.UV3Kind:
  19270. case VertexBuffer.UV4Kind:
  19271. case VertexBuffer.UV5Kind:
  19272. case VertexBuffer.UV6Kind:
  19273. stride = 2;
  19274. break;
  19275. case VertexBuffer.ColorKind:
  19276. stride = 4;
  19277. break;
  19278. case VertexBuffer.MatricesIndicesKind:
  19279. case VertexBuffer.MatricesIndicesExtraKind:
  19280. stride = 4;
  19281. break;
  19282. case VertexBuffer.MatricesWeightsKind:
  19283. case VertexBuffer.MatricesWeightsExtraKind:
  19284. stride = 4;
  19285. break;
  19286. }
  19287. }
  19288. if (data instanceof BABYLON.Buffer) {
  19289. if (!stride) {
  19290. stride = data.getStrideSize();
  19291. }
  19292. this._buffer = data;
  19293. this._ownsBuffer = false;
  19294. }
  19295. else {
  19296. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19297. this._ownsBuffer = true;
  19298. }
  19299. this._stride = stride;
  19300. this._offset = offset ? offset : 0;
  19301. this._size = size ? size : stride;
  19302. this._kind = kind;
  19303. }
  19304. VertexBuffer.prototype.getKind = function () {
  19305. return this._kind;
  19306. };
  19307. // Properties
  19308. VertexBuffer.prototype.isUpdatable = function () {
  19309. return this._buffer.isUpdatable();
  19310. };
  19311. VertexBuffer.prototype.getData = function () {
  19312. return this._buffer.getData();
  19313. };
  19314. VertexBuffer.prototype.getBuffer = function () {
  19315. return this._buffer.getBuffer();
  19316. };
  19317. VertexBuffer.prototype.getStrideSize = function () {
  19318. return this._stride;
  19319. };
  19320. VertexBuffer.prototype.getOffset = function () {
  19321. return this._offset;
  19322. };
  19323. VertexBuffer.prototype.getSize = function () {
  19324. return this._size;
  19325. };
  19326. VertexBuffer.prototype.getIsInstanced = function () {
  19327. return this._buffer.getIsInstanced();
  19328. };
  19329. // Methods
  19330. VertexBuffer.prototype.create = function (data) {
  19331. return this._buffer.create(data);
  19332. };
  19333. VertexBuffer.prototype.update = function (data) {
  19334. return this._buffer.update(data);
  19335. };
  19336. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19337. return this._buffer.updateDirectly(data, offset);
  19338. };
  19339. VertexBuffer.prototype.dispose = function () {
  19340. if (this._ownsBuffer) {
  19341. this._buffer.dispose();
  19342. }
  19343. };
  19344. Object.defineProperty(VertexBuffer, "PositionKind", {
  19345. get: function () {
  19346. return VertexBuffer._PositionKind;
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(VertexBuffer, "NormalKind", {
  19352. get: function () {
  19353. return VertexBuffer._NormalKind;
  19354. },
  19355. enumerable: true,
  19356. configurable: true
  19357. });
  19358. Object.defineProperty(VertexBuffer, "UVKind", {
  19359. get: function () {
  19360. return VertexBuffer._UVKind;
  19361. },
  19362. enumerable: true,
  19363. configurable: true
  19364. });
  19365. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19366. get: function () {
  19367. return VertexBuffer._UV2Kind;
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19373. get: function () {
  19374. return VertexBuffer._UV3Kind;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19380. get: function () {
  19381. return VertexBuffer._UV4Kind;
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19387. get: function () {
  19388. return VertexBuffer._UV5Kind;
  19389. },
  19390. enumerable: true,
  19391. configurable: true
  19392. });
  19393. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19394. get: function () {
  19395. return VertexBuffer._UV6Kind;
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. Object.defineProperty(VertexBuffer, "ColorKind", {
  19401. get: function () {
  19402. return VertexBuffer._ColorKind;
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19408. get: function () {
  19409. return VertexBuffer._MatricesIndicesKind;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19415. get: function () {
  19416. return VertexBuffer._MatricesWeightsKind;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19422. get: function () {
  19423. return VertexBuffer._MatricesIndicesExtraKind;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19429. get: function () {
  19430. return VertexBuffer._MatricesWeightsExtraKind;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. return VertexBuffer;
  19436. }());
  19437. // Enums
  19438. VertexBuffer._PositionKind = "position";
  19439. VertexBuffer._NormalKind = "normal";
  19440. VertexBuffer._UVKind = "uv";
  19441. VertexBuffer._UV2Kind = "uv2";
  19442. VertexBuffer._UV3Kind = "uv3";
  19443. VertexBuffer._UV4Kind = "uv4";
  19444. VertexBuffer._UV5Kind = "uv5";
  19445. VertexBuffer._UV6Kind = "uv6";
  19446. VertexBuffer._ColorKind = "color";
  19447. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19448. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19449. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19450. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19451. BABYLON.VertexBuffer = VertexBuffer;
  19452. })(BABYLON || (BABYLON = {}));
  19453. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19454. var BABYLON;
  19455. (function (BABYLON) {
  19456. /**
  19457. * Creates an instance based on a source mesh.
  19458. */
  19459. var InstancedMesh = (function (_super) {
  19460. __extends(InstancedMesh, _super);
  19461. function InstancedMesh(name, source) {
  19462. var _this = _super.call(this, name, source.getScene()) || this;
  19463. source.instances.push(_this);
  19464. _this._sourceMesh = source;
  19465. _this.position.copyFrom(source.position);
  19466. _this.rotation.copyFrom(source.rotation);
  19467. _this.scaling.copyFrom(source.scaling);
  19468. if (source.rotationQuaternion) {
  19469. _this.rotationQuaternion = source.rotationQuaternion.clone();
  19470. }
  19471. _this.infiniteDistance = source.infiniteDistance;
  19472. _this.setPivotMatrix(source.getPivotMatrix());
  19473. _this.refreshBoundingInfo();
  19474. _this._syncSubMeshes();
  19475. return _this;
  19476. }
  19477. InstancedMesh.prototype.getClassName = function () {
  19478. return "InstancedMesh";
  19479. };
  19480. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19481. // Methods
  19482. get: function () {
  19483. return this._sourceMesh.receiveShadows;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(InstancedMesh.prototype, "material", {
  19489. get: function () {
  19490. return this._sourceMesh.material;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19496. get: function () {
  19497. return this._sourceMesh.visibility;
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19503. get: function () {
  19504. return this._sourceMesh.skeleton;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19510. get: function () {
  19511. return this._sourceMesh.renderingGroupId;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. InstancedMesh.prototype.getTotalVertices = function () {
  19517. return this._sourceMesh.getTotalVertices();
  19518. };
  19519. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19520. get: function () {
  19521. return this._sourceMesh;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19527. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19528. };
  19529. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19530. return this._sourceMesh.isVerticesDataPresent(kind);
  19531. };
  19532. InstancedMesh.prototype.getIndices = function () {
  19533. return this._sourceMesh.getIndices();
  19534. };
  19535. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19536. get: function () {
  19537. return this._sourceMesh._positions;
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19543. var meshBB = this._sourceMesh.getBoundingInfo();
  19544. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19545. this._updateBoundingInfo();
  19546. };
  19547. InstancedMesh.prototype._preActivate = function () {
  19548. if (this._currentLOD) {
  19549. this._currentLOD._preActivate();
  19550. }
  19551. };
  19552. InstancedMesh.prototype._activate = function (renderId) {
  19553. if (this._currentLOD) {
  19554. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19555. }
  19556. };
  19557. InstancedMesh.prototype.getLOD = function (camera) {
  19558. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19559. if (this._currentLOD === this.sourceMesh) {
  19560. return this;
  19561. }
  19562. return this._currentLOD;
  19563. };
  19564. InstancedMesh.prototype._syncSubMeshes = function () {
  19565. this.releaseSubMeshes();
  19566. if (this._sourceMesh.subMeshes) {
  19567. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19568. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19569. }
  19570. }
  19571. };
  19572. InstancedMesh.prototype._generatePointsArray = function () {
  19573. return this._sourceMesh._generatePointsArray();
  19574. };
  19575. // Clone
  19576. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19577. var result = this._sourceMesh.createInstance(name);
  19578. // Deep copy
  19579. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19580. // Bounding info
  19581. this.refreshBoundingInfo();
  19582. // Parent
  19583. if (newParent) {
  19584. result.parent = newParent;
  19585. }
  19586. if (!doNotCloneChildren) {
  19587. // Children
  19588. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19589. var mesh = this.getScene().meshes[index];
  19590. if (mesh.parent === this) {
  19591. mesh.clone(mesh.name, result);
  19592. }
  19593. }
  19594. }
  19595. result.computeWorldMatrix(true);
  19596. return result;
  19597. };
  19598. // Dispoe
  19599. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19600. // Remove from mesh
  19601. var index = this._sourceMesh.instances.indexOf(this);
  19602. this._sourceMesh.instances.splice(index, 1);
  19603. _super.prototype.dispose.call(this, doNotRecurse);
  19604. };
  19605. return InstancedMesh;
  19606. }(BABYLON.AbstractMesh));
  19607. BABYLON.InstancedMesh = InstancedMesh;
  19608. })(BABYLON || (BABYLON = {}));
  19609. //# sourceMappingURL=babylon.instancedMesh.js.map
  19610. var BABYLON;
  19611. (function (BABYLON) {
  19612. var _InstancesBatch = (function () {
  19613. function _InstancesBatch() {
  19614. this.mustReturn = false;
  19615. this.visibleInstances = new Array();
  19616. this.renderSelf = new Array();
  19617. }
  19618. return _InstancesBatch;
  19619. }());
  19620. BABYLON._InstancesBatch = _InstancesBatch;
  19621. var Mesh = (function (_super) {
  19622. __extends(Mesh, _super);
  19623. /**
  19624. * @constructor
  19625. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19626. * @param {Scene} scene The scene to add this mesh to.
  19627. * @param {Node} parent The parent of this mesh, if it has one
  19628. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19629. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19630. * When false, achieved by calling a clone(), also passing False.
  19631. * This will make creation of children, recursive.
  19632. */
  19633. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19634. if (parent === void 0) { parent = null; }
  19635. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19636. var _this = _super.call(this, name, scene) || this;
  19637. // Events
  19638. /**
  19639. * An event triggered before rendering the mesh
  19640. * @type {BABYLON.Observable}
  19641. */
  19642. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19643. /**
  19644. * An event triggered after rendering the mesh
  19645. * @type {BABYLON.Observable}
  19646. */
  19647. _this.onAfterRenderObservable = new BABYLON.Observable();
  19648. /**
  19649. * An event triggered before drawing the mesh
  19650. * @type {BABYLON.Observable}
  19651. */
  19652. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19653. // Members
  19654. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19655. _this.instances = new Array();
  19656. _this._LODLevels = new Array();
  19657. _this._visibleInstances = {};
  19658. _this._renderIdForInstances = new Array();
  19659. _this._batchCache = new _InstancesBatch();
  19660. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19661. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19662. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19663. if (source) {
  19664. // Geometry
  19665. if (source._geometry) {
  19666. source._geometry.applyToMesh(_this);
  19667. }
  19668. // Deep copy
  19669. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19670. // Parent
  19671. _this.parent = source.parent;
  19672. // Pivot
  19673. _this.setPivotMatrix(source.getPivotMatrix());
  19674. _this.id = name + "." + source.id;
  19675. // Material
  19676. _this.material = source.material;
  19677. var index;
  19678. if (!doNotCloneChildren) {
  19679. // Children
  19680. for (index = 0; index < scene.meshes.length; index++) {
  19681. var mesh = scene.meshes[index];
  19682. if (mesh.parent === source) {
  19683. // doNotCloneChildren is always going to be False
  19684. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19685. }
  19686. }
  19687. }
  19688. // Physics clone
  19689. var physicsEngine = _this.getScene().getPhysicsEngine();
  19690. if (clonePhysicsImpostor && physicsEngine) {
  19691. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19692. if (impostor) {
  19693. _this.physicsImpostor = impostor.clone(_this);
  19694. }
  19695. }
  19696. // Particles
  19697. for (index = 0; index < scene.particleSystems.length; index++) {
  19698. var system = scene.particleSystems[index];
  19699. if (system.emitter === source) {
  19700. system.clone(system.name, _this);
  19701. }
  19702. }
  19703. _this.computeWorldMatrix(true);
  19704. }
  19705. // Parent
  19706. if (parent !== null) {
  19707. _this.parent = parent;
  19708. }
  19709. return _this;
  19710. }
  19711. Object.defineProperty(Mesh, "FRONTSIDE", {
  19712. /**
  19713. * Mesh side orientation : usually the external or front surface
  19714. */
  19715. get: function () {
  19716. return Mesh._FRONTSIDE;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(Mesh, "BACKSIDE", {
  19722. /**
  19723. * Mesh side orientation : usually the internal or back surface
  19724. */
  19725. get: function () {
  19726. return Mesh._BACKSIDE;
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19732. /**
  19733. * Mesh side orientation : both internal and external or front and back surfaces
  19734. */
  19735. get: function () {
  19736. return Mesh._DOUBLESIDE;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19742. /**
  19743. * Mesh side orientation : by default, `FRONTSIDE`
  19744. */
  19745. get: function () {
  19746. return Mesh._DEFAULTSIDE;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(Mesh, "NO_CAP", {
  19752. /**
  19753. * Mesh cap setting : no cap
  19754. */
  19755. get: function () {
  19756. return Mesh._NO_CAP;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Mesh, "CAP_START", {
  19762. /**
  19763. * Mesh cap setting : one cap at the beginning of the mesh
  19764. */
  19765. get: function () {
  19766. return Mesh._CAP_START;
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(Mesh, "CAP_END", {
  19772. /**
  19773. * Mesh cap setting : one cap at the end of the mesh
  19774. */
  19775. get: function () {
  19776. return Mesh._CAP_END;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(Mesh, "CAP_ALL", {
  19782. /**
  19783. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19784. */
  19785. get: function () {
  19786. return Mesh._CAP_ALL;
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19792. set: function (callback) {
  19793. if (this._onBeforeDrawObserver) {
  19794. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19795. }
  19796. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. // Methods
  19802. Mesh.prototype.getClassName = function () {
  19803. return "Mesh";
  19804. };
  19805. /**
  19806. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19807. */
  19808. Mesh.prototype.toString = function (fullDetails) {
  19809. var ret = _super.prototype.toString.call(this, fullDetails);
  19810. ret += ", n vertices: " + this.getTotalVertices();
  19811. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19812. if (this.animations) {
  19813. for (var i = 0; i < this.animations.length; i++) {
  19814. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19815. }
  19816. }
  19817. if (fullDetails) {
  19818. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19819. }
  19820. return ret;
  19821. };
  19822. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19823. get: function () {
  19824. return this._LODLevels.length > 0;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Mesh.prototype._sortLODLevels = function () {
  19830. this._LODLevels.sort(function (a, b) {
  19831. if (a.distance < b.distance) {
  19832. return 1;
  19833. }
  19834. if (a.distance > b.distance) {
  19835. return -1;
  19836. }
  19837. return 0;
  19838. });
  19839. };
  19840. /**
  19841. * Add a mesh as LOD level triggered at the given distance.
  19842. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19843. * @param {number} distance The distance from the center of the object to show this level
  19844. * @param {Mesh} mesh The mesh to be added as LOD level
  19845. * @return {Mesh} This mesh (for chaining)
  19846. */
  19847. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19848. if (mesh && mesh._masterMesh) {
  19849. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19850. return this;
  19851. }
  19852. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19853. this._LODLevels.push(level);
  19854. if (mesh) {
  19855. mesh._masterMesh = this;
  19856. }
  19857. this._sortLODLevels();
  19858. return this;
  19859. };
  19860. /**
  19861. * Returns the LOD level mesh at the passed distance or null if not found.
  19862. * It is related to the method `addLODLevel(distance, mesh)`.
  19863. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19864. */
  19865. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19866. for (var index = 0; index < this._LODLevels.length; index++) {
  19867. var level = this._LODLevels[index];
  19868. if (level.distance === distance) {
  19869. return level.mesh;
  19870. }
  19871. }
  19872. return null;
  19873. };
  19874. /**
  19875. * Remove a mesh from the LOD array
  19876. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19877. * @param {Mesh} mesh The mesh to be removed.
  19878. * @return {Mesh} This mesh (for chaining)
  19879. */
  19880. Mesh.prototype.removeLODLevel = function (mesh) {
  19881. for (var index = 0; index < this._LODLevels.length; index++) {
  19882. if (this._LODLevels[index].mesh === mesh) {
  19883. this._LODLevels.splice(index, 1);
  19884. if (mesh) {
  19885. mesh._masterMesh = null;
  19886. }
  19887. }
  19888. }
  19889. this._sortLODLevels();
  19890. return this;
  19891. };
  19892. /**
  19893. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19894. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19895. */
  19896. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19897. if (!this._LODLevels || this._LODLevels.length === 0) {
  19898. return this;
  19899. }
  19900. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19901. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19902. if (this.onLODLevelSelection) {
  19903. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19904. }
  19905. return this;
  19906. }
  19907. for (var index = 0; index < this._LODLevels.length; index++) {
  19908. var level = this._LODLevels[index];
  19909. if (level.distance < distanceToCamera) {
  19910. if (level.mesh) {
  19911. level.mesh._preActivate();
  19912. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19913. }
  19914. if (this.onLODLevelSelection) {
  19915. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19916. }
  19917. return level.mesh;
  19918. }
  19919. }
  19920. if (this.onLODLevelSelection) {
  19921. this.onLODLevelSelection(distanceToCamera, this, this);
  19922. }
  19923. return this;
  19924. };
  19925. Object.defineProperty(Mesh.prototype, "geometry", {
  19926. /**
  19927. * Returns the mesh internal Geometry object.
  19928. */
  19929. get: function () {
  19930. return this._geometry;
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. /**
  19936. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19937. */
  19938. Mesh.prototype.getTotalVertices = function () {
  19939. if (!this._geometry) {
  19940. return 0;
  19941. }
  19942. return this._geometry.getTotalVertices();
  19943. };
  19944. /**
  19945. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19946. * 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.
  19947. * Returns null if the mesh has no geometry or no vertex buffer.
  19948. * Possible `kind` values :
  19949. * - BABYLON.VertexBuffer.PositionKind
  19950. * - BABYLON.VertexBuffer.UVKind
  19951. * - BABYLON.VertexBuffer.UV2Kind
  19952. * - BABYLON.VertexBuffer.UV3Kind
  19953. * - BABYLON.VertexBuffer.UV4Kind
  19954. * - BABYLON.VertexBuffer.UV5Kind
  19955. * - BABYLON.VertexBuffer.UV6Kind
  19956. * - BABYLON.VertexBuffer.ColorKind
  19957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19961. */
  19962. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19963. if (!this._geometry) {
  19964. return null;
  19965. }
  19966. return this._geometry.getVerticesData(kind, copyWhenShared);
  19967. };
  19968. /**
  19969. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19970. * Returns `undefined` if the mesh has no geometry.
  19971. * Possible `kind` values :
  19972. * - BABYLON.VertexBuffer.PositionKind
  19973. * - BABYLON.VertexBuffer.UVKind
  19974. * - BABYLON.VertexBuffer.UV2Kind
  19975. * - BABYLON.VertexBuffer.UV3Kind
  19976. * - BABYLON.VertexBuffer.UV4Kind
  19977. * - BABYLON.VertexBuffer.UV5Kind
  19978. * - BABYLON.VertexBuffer.UV6Kind
  19979. * - BABYLON.VertexBuffer.ColorKind
  19980. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19981. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19982. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19983. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19984. */
  19985. Mesh.prototype.getVertexBuffer = function (kind) {
  19986. if (!this._geometry) {
  19987. return undefined;
  19988. }
  19989. return this._geometry.getVertexBuffer(kind);
  19990. };
  19991. /**
  19992. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19993. * Possible `kind` values :
  19994. * - BABYLON.VertexBuffer.PositionKind
  19995. * - BABYLON.VertexBuffer.UVKind
  19996. * - BABYLON.VertexBuffer.UV2Kind
  19997. * - BABYLON.VertexBuffer.UV3Kind
  19998. * - BABYLON.VertexBuffer.UV4Kind
  19999. * - BABYLON.VertexBuffer.UV5Kind
  20000. * - BABYLON.VertexBuffer.UV6Kind
  20001. * - BABYLON.VertexBuffer.ColorKind
  20002. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20003. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20004. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20005. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20006. */
  20007. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20008. if (!this._geometry) {
  20009. if (this._delayInfo) {
  20010. return this._delayInfo.indexOf(kind) !== -1;
  20011. }
  20012. return false;
  20013. }
  20014. return this._geometry.isVerticesDataPresent(kind);
  20015. };
  20016. /**
  20017. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20018. * Possible `kind` values :
  20019. * - BABYLON.VertexBuffer.PositionKind
  20020. * - BABYLON.VertexBuffer.UVKind
  20021. * - BABYLON.VertexBuffer.UV2Kind
  20022. * - BABYLON.VertexBuffer.UV3Kind
  20023. * - BABYLON.VertexBuffer.UV4Kind
  20024. * - BABYLON.VertexBuffer.UV5Kind
  20025. * - BABYLON.VertexBuffer.UV6Kind
  20026. * - BABYLON.VertexBuffer.ColorKind
  20027. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20028. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20029. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20030. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20031. */
  20032. Mesh.prototype.getVerticesDataKinds = function () {
  20033. if (!this._geometry) {
  20034. var result = [];
  20035. if (this._delayInfo) {
  20036. this._delayInfo.forEach(function (kind, index, array) {
  20037. result.push(kind);
  20038. });
  20039. }
  20040. return result;
  20041. }
  20042. return this._geometry.getVerticesDataKinds();
  20043. };
  20044. /**
  20045. * Returns a positive integer : the total number of indices in this mesh geometry.
  20046. * Returns zero if the mesh has no geometry.
  20047. */
  20048. Mesh.prototype.getTotalIndices = function () {
  20049. if (!this._geometry) {
  20050. return 0;
  20051. }
  20052. return this._geometry.getTotalIndices();
  20053. };
  20054. /**
  20055. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20056. * 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.
  20057. * Returns an empty array if the mesh has no geometry.
  20058. */
  20059. Mesh.prototype.getIndices = function (copyWhenShared) {
  20060. if (!this._geometry) {
  20061. return [];
  20062. }
  20063. return this._geometry.getIndices(copyWhenShared);
  20064. };
  20065. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20066. get: function () {
  20067. return this._masterMesh !== null && this._masterMesh !== undefined;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. /**
  20073. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20074. */
  20075. Mesh.prototype.isReady = function () {
  20076. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20077. return false;
  20078. }
  20079. return _super.prototype.isReady.call(this);
  20080. };
  20081. /**
  20082. * Boolean : true if the mesh has been disposed.
  20083. */
  20084. Mesh.prototype.isDisposed = function () {
  20085. return this._isDisposed;
  20086. };
  20087. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20088. get: function () {
  20089. return this._sideOrientation;
  20090. },
  20091. /**
  20092. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20093. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20094. */
  20095. set: function (sideO) {
  20096. this._sideOrientation = sideO;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20102. /**
  20103. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20104. * This property is pertinent only for updatable parametric shapes.
  20105. */
  20106. get: function () {
  20107. return this._areNormalsFrozen;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. /**
  20113. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20114. * It has no effect at all on other shapes.
  20115. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20116. */
  20117. Mesh.prototype.freezeNormals = function () {
  20118. this._areNormalsFrozen = true;
  20119. };
  20120. /**
  20121. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20122. * It has no effect at all on other shapes.
  20123. * It reactivates the mesh normals computation if it was previously frozen.
  20124. */
  20125. Mesh.prototype.unfreezeNormals = function () {
  20126. this._areNormalsFrozen = false;
  20127. };
  20128. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20129. /**
  20130. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20131. */
  20132. set: function (count) {
  20133. this._overridenInstanceCount = count;
  20134. },
  20135. enumerable: true,
  20136. configurable: true
  20137. });
  20138. // Methods
  20139. Mesh.prototype._preActivate = function () {
  20140. var sceneRenderId = this.getScene().getRenderId();
  20141. if (this._preActivateId === sceneRenderId) {
  20142. return;
  20143. }
  20144. this._preActivateId = sceneRenderId;
  20145. this._visibleInstances = null;
  20146. };
  20147. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20148. if (this._visibleInstances) {
  20149. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20150. }
  20151. };
  20152. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20153. if (!this._visibleInstances) {
  20154. this._visibleInstances = {};
  20155. this._visibleInstances.defaultRenderId = renderId;
  20156. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20157. }
  20158. if (!this._visibleInstances[renderId]) {
  20159. this._visibleInstances[renderId] = new Array();
  20160. }
  20161. this._visibleInstances[renderId].push(instance);
  20162. };
  20163. /**
  20164. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20165. * This means the mesh underlying bounding box and sphere are recomputed.
  20166. */
  20167. Mesh.prototype.refreshBoundingInfo = function () {
  20168. if (this._boundingInfo.isLocked) {
  20169. return;
  20170. }
  20171. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20172. if (data) {
  20173. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20174. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20175. }
  20176. if (this.subMeshes) {
  20177. for (var index = 0; index < this.subMeshes.length; index++) {
  20178. this.subMeshes[index].refreshBoundingInfo();
  20179. }
  20180. }
  20181. this._updateBoundingInfo();
  20182. };
  20183. Mesh.prototype._createGlobalSubMesh = function () {
  20184. var totalVertices = this.getTotalVertices();
  20185. if (!totalVertices || !this.getIndices()) {
  20186. return null;
  20187. }
  20188. this.releaseSubMeshes();
  20189. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20190. };
  20191. Mesh.prototype.subdivide = function (count) {
  20192. if (count < 1) {
  20193. return;
  20194. }
  20195. var totalIndices = this.getTotalIndices();
  20196. var subdivisionSize = (totalIndices / count) | 0;
  20197. var offset = 0;
  20198. // Ensure that subdivisionSize is a multiple of 3
  20199. while (subdivisionSize % 3 !== 0) {
  20200. subdivisionSize++;
  20201. }
  20202. this.releaseSubMeshes();
  20203. for (var index = 0; index < count; index++) {
  20204. if (offset >= totalIndices) {
  20205. break;
  20206. }
  20207. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20208. offset += subdivisionSize;
  20209. }
  20210. this.synchronizeInstances();
  20211. };
  20212. /**
  20213. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20214. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20215. * The `data` are either a numeric array either a Float32Array.
  20216. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20217. * 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).
  20218. * Note that a new underlying VertexBuffer object is created each call.
  20219. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20220. *
  20221. * Possible `kind` values :
  20222. * - BABYLON.VertexBuffer.PositionKind
  20223. * - BABYLON.VertexBuffer.UVKind
  20224. * - BABYLON.VertexBuffer.UV2Kind
  20225. * - BABYLON.VertexBuffer.UV3Kind
  20226. * - BABYLON.VertexBuffer.UV4Kind
  20227. * - BABYLON.VertexBuffer.UV5Kind
  20228. * - BABYLON.VertexBuffer.UV6Kind
  20229. * - BABYLON.VertexBuffer.ColorKind
  20230. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20231. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20232. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20233. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20234. */
  20235. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20236. if (!this._geometry) {
  20237. var vertexData = new BABYLON.VertexData();
  20238. vertexData.set(data, kind);
  20239. var scene = this.getScene();
  20240. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20241. }
  20242. else {
  20243. this._geometry.setVerticesData(kind, data, updatable, stride);
  20244. }
  20245. };
  20246. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20247. if (!this._geometry) {
  20248. var scene = this.getScene();
  20249. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20250. }
  20251. this._geometry.setVerticesBuffer(buffer);
  20252. };
  20253. /**
  20254. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20255. * If the mesh has no geometry, it is simply returned as it is.
  20256. * The `data` are either a numeric array either a Float32Array.
  20257. * No new underlying VertexBuffer object is created.
  20258. * 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.
  20259. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20260. *
  20261. * Possible `kind` values :
  20262. * - BABYLON.VertexBuffer.PositionKind
  20263. * - BABYLON.VertexBuffer.UVKind
  20264. * - BABYLON.VertexBuffer.UV2Kind
  20265. * - BABYLON.VertexBuffer.UV3Kind
  20266. * - BABYLON.VertexBuffer.UV4Kind
  20267. * - BABYLON.VertexBuffer.UV5Kind
  20268. * - BABYLON.VertexBuffer.UV6Kind
  20269. * - BABYLON.VertexBuffer.ColorKind
  20270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20274. */
  20275. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20276. if (!this._geometry) {
  20277. return;
  20278. }
  20279. if (!makeItUnique) {
  20280. this._geometry.updateVerticesData(kind, data, updateExtends);
  20281. }
  20282. else {
  20283. this.makeGeometryUnique();
  20284. this.updateVerticesData(kind, data, updateExtends, false);
  20285. }
  20286. };
  20287. /**
  20288. * Deprecated since BabylonJS v2.3
  20289. */
  20290. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20291. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20292. if (!this._geometry) {
  20293. return;
  20294. }
  20295. if (!makeItUnique) {
  20296. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20297. }
  20298. else {
  20299. this.makeGeometryUnique();
  20300. this.updateVerticesDataDirectly(kind, data, offset, false);
  20301. }
  20302. };
  20303. /**
  20304. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20305. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20306. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20307. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20308. */
  20309. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20310. if (computeNormals === void 0) { computeNormals = true; }
  20311. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20312. positionFunction(positions);
  20313. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20314. if (computeNormals) {
  20315. var indices = this.getIndices();
  20316. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20317. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20318. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20319. }
  20320. };
  20321. Mesh.prototype.makeGeometryUnique = function () {
  20322. if (!this._geometry) {
  20323. return;
  20324. }
  20325. var oldGeometry = this._geometry;
  20326. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20327. oldGeometry.releaseForMesh(this, true);
  20328. geometry.applyToMesh(this);
  20329. };
  20330. /**
  20331. * Sets the mesh indices.
  20332. * Expects an array populated with integers or a Int32Array.
  20333. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20334. * This method creates a new index buffer each call.
  20335. */
  20336. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20337. if (!this._geometry) {
  20338. var vertexData = new BABYLON.VertexData();
  20339. vertexData.indices = indices;
  20340. var scene = this.getScene();
  20341. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20342. }
  20343. else {
  20344. this._geometry.setIndices(indices, totalVertices);
  20345. }
  20346. };
  20347. /**
  20348. * Invert the geometry to move from a right handed system to a left handed one.
  20349. */
  20350. Mesh.prototype.toLeftHanded = function () {
  20351. if (!this._geometry) {
  20352. return;
  20353. }
  20354. this._geometry.toLeftHanded();
  20355. };
  20356. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20357. var engine = this.getScene().getEngine();
  20358. // Wireframe
  20359. var indexToBind;
  20360. if (this._unIndexed) {
  20361. indexToBind = null;
  20362. }
  20363. else {
  20364. switch (fillMode) {
  20365. case BABYLON.Material.PointFillMode:
  20366. indexToBind = null;
  20367. break;
  20368. case BABYLON.Material.WireFrameFillMode:
  20369. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20370. break;
  20371. default:
  20372. case BABYLON.Material.TriangleFillMode:
  20373. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20374. break;
  20375. }
  20376. }
  20377. // VBOs
  20378. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20379. };
  20380. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20381. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20382. return;
  20383. }
  20384. this.onBeforeDrawObservable.notifyObservers(this);
  20385. var engine = this.getScene().getEngine();
  20386. // Draw order
  20387. switch (fillMode) {
  20388. case BABYLON.Material.PointFillMode:
  20389. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20390. break;
  20391. case BABYLON.Material.WireFrameFillMode:
  20392. if (this._unIndexed) {
  20393. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20394. }
  20395. else {
  20396. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20397. }
  20398. break;
  20399. default:
  20400. if (this._unIndexed) {
  20401. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20402. }
  20403. else {
  20404. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20405. }
  20406. }
  20407. };
  20408. /**
  20409. * Registers for this mesh a javascript function called just before the rendering process.
  20410. * This function is passed the current mesh and doesn't return anything.
  20411. */
  20412. Mesh.prototype.registerBeforeRender = function (func) {
  20413. this.onBeforeRenderObservable.add(func);
  20414. };
  20415. /**
  20416. * Disposes a previously registered javascript function called before the rendering.
  20417. * This function is passed the current mesh and doesn't return anything.
  20418. */
  20419. Mesh.prototype.unregisterBeforeRender = function (func) {
  20420. this.onBeforeRenderObservable.removeCallback(func);
  20421. };
  20422. /**
  20423. * Registers for this mesh a javascript function called just after the rendering is complete.
  20424. * This function is passed the current mesh and doesn't return anything.
  20425. */
  20426. Mesh.prototype.registerAfterRender = function (func) {
  20427. this.onAfterRenderObservable.add(func);
  20428. };
  20429. /**
  20430. * Disposes a previously registered javascript function called after the rendering.
  20431. * This function is passed the current mesh and doesn't return anything.
  20432. */
  20433. Mesh.prototype.unregisterAfterRender = function (func) {
  20434. this.onAfterRenderObservable.removeCallback(func);
  20435. };
  20436. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20437. var scene = this.getScene();
  20438. this._batchCache.mustReturn = false;
  20439. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20440. this._batchCache.visibleInstances[subMeshId] = null;
  20441. if (this._visibleInstances) {
  20442. var currentRenderId = scene.getRenderId();
  20443. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20444. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20445. var selfRenderId = this._renderId;
  20446. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20447. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20448. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20449. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20450. }
  20451. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20452. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20453. this._batchCache.mustReturn = true;
  20454. return this._batchCache;
  20455. }
  20456. if (currentRenderId !== selfRenderId) {
  20457. this._batchCache.renderSelf[subMeshId] = false;
  20458. }
  20459. }
  20460. this._renderIdForInstances[subMeshId] = currentRenderId;
  20461. }
  20462. return this._batchCache;
  20463. };
  20464. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20465. var visibleInstances = batch.visibleInstances[subMesh._id];
  20466. var matricesCount = visibleInstances.length + 1;
  20467. var bufferSize = matricesCount * 16 * 4;
  20468. var currentInstancesBufferSize = this._instancesBufferSize;
  20469. var instancesBuffer = this._instancesBuffer;
  20470. while (this._instancesBufferSize < bufferSize) {
  20471. this._instancesBufferSize *= 2;
  20472. }
  20473. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20474. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20475. }
  20476. var offset = 0;
  20477. var instancesCount = 0;
  20478. var world = this.getWorldMatrix();
  20479. if (batch.renderSelf[subMesh._id]) {
  20480. world.copyToArray(this._instancesData, offset);
  20481. offset += 16;
  20482. instancesCount++;
  20483. }
  20484. if (visibleInstances) {
  20485. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20486. var instance = visibleInstances[instanceIndex];
  20487. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20488. offset += 16;
  20489. instancesCount++;
  20490. }
  20491. }
  20492. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20493. if (instancesBuffer) {
  20494. instancesBuffer.dispose();
  20495. }
  20496. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20497. this._instancesBuffer = instancesBuffer;
  20498. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20499. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20500. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20501. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20502. }
  20503. else {
  20504. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20505. }
  20506. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20507. this._draw(subMesh, fillMode, instancesCount);
  20508. engine.unbindInstanceAttributes();
  20509. };
  20510. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20511. var scene = this.getScene();
  20512. var engine = scene.getEngine();
  20513. if (hardwareInstancedRendering) {
  20514. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20515. }
  20516. else {
  20517. if (batch.renderSelf[subMesh._id]) {
  20518. // Draw
  20519. if (onBeforeDraw) {
  20520. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20521. }
  20522. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20523. }
  20524. if (batch.visibleInstances[subMesh._id]) {
  20525. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20526. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20527. // World
  20528. var world = instance.getWorldMatrix();
  20529. if (onBeforeDraw) {
  20530. onBeforeDraw(true, world, effectiveMaterial);
  20531. }
  20532. // Draw
  20533. this._draw(subMesh, fillMode);
  20534. }
  20535. }
  20536. }
  20537. };
  20538. /**
  20539. * Triggers the draw call for the mesh.
  20540. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20541. */
  20542. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20543. var scene = this.getScene();
  20544. // Managing instances
  20545. var batch = this._getInstancesRenderList(subMesh._id);
  20546. if (batch.mustReturn) {
  20547. return;
  20548. }
  20549. // Checking geometry state
  20550. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20551. return;
  20552. }
  20553. var callbackIndex;
  20554. this.onBeforeRenderObservable.notifyObservers(this);
  20555. var engine = scene.getEngine();
  20556. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20557. // Material
  20558. var effectiveMaterial = subMesh.getMaterial();
  20559. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20560. return;
  20561. }
  20562. // Outline - step 1
  20563. var savedDepthWrite = engine.getDepthWrite();
  20564. if (this.renderOutline) {
  20565. engine.setDepthWrite(false);
  20566. scene.getOutlineRenderer().render(subMesh, batch);
  20567. engine.setDepthWrite(savedDepthWrite);
  20568. }
  20569. effectiveMaterial._preBind();
  20570. var effect = effectiveMaterial.getEffect();
  20571. // Bind
  20572. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20573. this._bind(subMesh, effect, fillMode);
  20574. var world = this.getWorldMatrix();
  20575. effectiveMaterial.bind(world, this);
  20576. // Alpha mode
  20577. if (enableAlphaMode) {
  20578. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20579. }
  20580. // Draw
  20581. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20582. // Unbind
  20583. effectiveMaterial.unbind();
  20584. // Outline - step 2
  20585. if (this.renderOutline && savedDepthWrite) {
  20586. engine.setDepthWrite(true);
  20587. engine.setColorWrite(false);
  20588. scene.getOutlineRenderer().render(subMesh, batch);
  20589. engine.setColorWrite(true);
  20590. }
  20591. // Overlay
  20592. if (this.renderOverlay) {
  20593. var currentMode = engine.getAlphaMode();
  20594. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20595. scene.getOutlineRenderer().render(subMesh, batch, true);
  20596. engine.setAlphaMode(currentMode);
  20597. }
  20598. this.onAfterRenderObservable.notifyObservers(this);
  20599. };
  20600. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20601. if (isInstance) {
  20602. effectiveMaterial.bindOnlyWorldMatrix(world);
  20603. }
  20604. };
  20605. /**
  20606. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20607. */
  20608. Mesh.prototype.getEmittedParticleSystems = function () {
  20609. var results = new Array();
  20610. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20611. var particleSystem = this.getScene().particleSystems[index];
  20612. if (particleSystem.emitter === this) {
  20613. results.push(particleSystem);
  20614. }
  20615. }
  20616. return results;
  20617. };
  20618. /**
  20619. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20620. */
  20621. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20622. var results = new Array();
  20623. var descendants = this.getDescendants();
  20624. descendants.push(this);
  20625. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20626. var particleSystem = this.getScene().particleSystems[index];
  20627. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20628. results.push(particleSystem);
  20629. }
  20630. }
  20631. return results;
  20632. };
  20633. Mesh.prototype._checkDelayState = function () {
  20634. var scene = this.getScene();
  20635. if (this._geometry) {
  20636. this._geometry.load(scene);
  20637. }
  20638. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20639. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20640. this._queueLoad(this, scene);
  20641. }
  20642. };
  20643. Mesh.prototype._queueLoad = function (mesh, scene) {
  20644. var _this = this;
  20645. scene._addPendingData(mesh);
  20646. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20647. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20648. if (data instanceof ArrayBuffer) {
  20649. _this._delayLoadingFunction(data, _this);
  20650. }
  20651. else {
  20652. _this._delayLoadingFunction(JSON.parse(data), _this);
  20653. }
  20654. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20655. scene._removePendingData(_this);
  20656. }, function () { }, scene.database, getBinaryData);
  20657. };
  20658. /**
  20659. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20660. */
  20661. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20662. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20663. return false;
  20664. }
  20665. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20666. return false;
  20667. }
  20668. this._checkDelayState();
  20669. return true;
  20670. };
  20671. /**
  20672. * Sets the mesh material by the material or multiMaterial `id` property.
  20673. * The material `id` is a string identifying the material or the multiMaterial.
  20674. * This method returns nothing.
  20675. */
  20676. Mesh.prototype.setMaterialByID = function (id) {
  20677. var materials = this.getScene().materials;
  20678. var index;
  20679. for (index = 0; index < materials.length; index++) {
  20680. if (materials[index].id === id) {
  20681. this.material = materials[index];
  20682. return;
  20683. }
  20684. }
  20685. // Multi
  20686. var multiMaterials = this.getScene().multiMaterials;
  20687. for (index = 0; index < multiMaterials.length; index++) {
  20688. if (multiMaterials[index].id === id) {
  20689. this.material = multiMaterials[index];
  20690. return;
  20691. }
  20692. }
  20693. };
  20694. /**
  20695. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20696. */
  20697. Mesh.prototype.getAnimatables = function () {
  20698. var results = [];
  20699. if (this.material) {
  20700. results.push(this.material);
  20701. }
  20702. if (this.skeleton) {
  20703. results.push(this.skeleton);
  20704. }
  20705. return results;
  20706. };
  20707. /**
  20708. * Modifies the mesh geometry according to the passed transformation matrix.
  20709. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20710. * The mesh normals are modified accordingly the same transformation.
  20711. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20712. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20713. */
  20714. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20715. // Position
  20716. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20717. return;
  20718. }
  20719. var submeshes = this.subMeshes.splice(0);
  20720. this._resetPointsArrayCache();
  20721. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20722. var temp = [];
  20723. var index;
  20724. for (index = 0; index < data.length; index += 3) {
  20725. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20726. }
  20727. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20728. // Normals
  20729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20730. return;
  20731. }
  20732. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20733. temp = [];
  20734. for (index = 0; index < data.length; index += 3) {
  20735. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20736. }
  20737. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20738. // flip faces?
  20739. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20740. this.flipFaces();
  20741. }
  20742. // Restore submeshes
  20743. this.releaseSubMeshes();
  20744. this.subMeshes = submeshes;
  20745. };
  20746. /**
  20747. * Modifies the mesh geometry according to its own current World Matrix.
  20748. * The mesh World Matrix is then reset.
  20749. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20750. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20751. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20752. */
  20753. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20754. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20755. this.scaling.copyFromFloats(1, 1, 1);
  20756. this.position.copyFromFloats(0, 0, 0);
  20757. this.rotation.copyFromFloats(0, 0, 0);
  20758. //only if quaternion is already set
  20759. if (this.rotationQuaternion) {
  20760. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20761. }
  20762. this._worldMatrix = BABYLON.Matrix.Identity();
  20763. };
  20764. // Cache
  20765. Mesh.prototype._resetPointsArrayCache = function () {
  20766. this._positions = null;
  20767. };
  20768. Mesh.prototype._generatePointsArray = function () {
  20769. if (this._positions)
  20770. return true;
  20771. this._positions = [];
  20772. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20773. if (!data) {
  20774. return false;
  20775. }
  20776. for (var index = 0; index < data.length; index += 3) {
  20777. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20778. }
  20779. return true;
  20780. };
  20781. /**
  20782. * Returns a new Mesh object generated from the current mesh properties.
  20783. * This method must not get confused with createInstance().
  20784. * The parameter `name` is a string, the name given to the new mesh.
  20785. * The optional parameter `newParent` can be any Node object (default `null`).
  20786. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20787. * 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.
  20788. */
  20789. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20790. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20791. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20792. };
  20793. /**
  20794. * Disposes the mesh.
  20795. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20796. */
  20797. Mesh.prototype.dispose = function (doNotRecurse) {
  20798. if (this._geometry) {
  20799. this._geometry.releaseForMesh(this, true);
  20800. }
  20801. // Instances
  20802. if (this._instancesBuffer) {
  20803. this._instancesBuffer.dispose();
  20804. this._instancesBuffer = null;
  20805. }
  20806. while (this.instances.length) {
  20807. this.instances[0].dispose();
  20808. }
  20809. // Highlight layers.
  20810. var highlightLayers = this.getScene().highlightLayers;
  20811. for (var i = 0; i < highlightLayers.length; i++) {
  20812. var highlightLayer = highlightLayers[i];
  20813. if (highlightLayer) {
  20814. highlightLayer.removeMesh(this);
  20815. highlightLayer.removeExcludedMesh(this);
  20816. }
  20817. }
  20818. _super.prototype.dispose.call(this, doNotRecurse);
  20819. };
  20820. /**
  20821. * Modifies the mesh geometry according to a displacement map.
  20822. * 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.
  20823. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20824. * This method returns nothing.
  20825. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20826. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20827. * 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.
  20828. */
  20829. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20830. var _this = this;
  20831. var scene = this.getScene();
  20832. var onload = function (img) {
  20833. // Getting height map data
  20834. var canvas = document.createElement("canvas");
  20835. var context = canvas.getContext("2d");
  20836. var heightMapWidth = img.width;
  20837. var heightMapHeight = img.height;
  20838. canvas.width = heightMapWidth;
  20839. canvas.height = heightMapHeight;
  20840. context.drawImage(img, 0, 0);
  20841. // Create VertexData from map data
  20842. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20843. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20844. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20845. //execute success callback, if set
  20846. if (onSuccess) {
  20847. onSuccess(_this);
  20848. }
  20849. };
  20850. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20851. };
  20852. /**
  20853. * Modifies the mesh geometry according to a displacementMap buffer.
  20854. * 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.
  20855. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20856. * This method returns nothing.
  20857. * 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.
  20858. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20859. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20860. */
  20861. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20862. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20863. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20864. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20865. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20866. return;
  20867. }
  20868. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20869. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20870. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20871. var position = BABYLON.Vector3.Zero();
  20872. var normal = BABYLON.Vector3.Zero();
  20873. var uv = BABYLON.Vector2.Zero();
  20874. for (var index = 0; index < positions.length; index += 3) {
  20875. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20876. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20877. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20878. // Compute height
  20879. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20880. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20881. var pos = (u + v * heightMapWidth) * 4;
  20882. var r = buffer[pos] / 255.0;
  20883. var g = buffer[pos + 1] / 255.0;
  20884. var b = buffer[pos + 2] / 255.0;
  20885. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20886. normal.normalize();
  20887. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20888. position = position.add(normal);
  20889. position.toArray(positions, index);
  20890. }
  20891. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20892. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20893. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20894. };
  20895. /**
  20896. * Modify the mesh to get a flat shading rendering.
  20897. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20898. * This method returns nothing.
  20899. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20900. */
  20901. Mesh.prototype.convertToFlatShadedMesh = function () {
  20902. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20903. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20904. var kinds = this.getVerticesDataKinds();
  20905. var vbs = [];
  20906. var data = [];
  20907. var newdata = [];
  20908. var updatableNormals = false;
  20909. var kindIndex;
  20910. var kind;
  20911. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20912. kind = kinds[kindIndex];
  20913. var vertexBuffer = this.getVertexBuffer(kind);
  20914. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20915. updatableNormals = vertexBuffer.isUpdatable();
  20916. kinds.splice(kindIndex, 1);
  20917. kindIndex--;
  20918. continue;
  20919. }
  20920. vbs[kind] = vertexBuffer;
  20921. data[kind] = vbs[kind].getData();
  20922. newdata[kind] = [];
  20923. }
  20924. // Save previous submeshes
  20925. var previousSubmeshes = this.subMeshes.slice(0);
  20926. var indices = this.getIndices();
  20927. var totalIndices = this.getTotalIndices();
  20928. // Generating unique vertices per face
  20929. var index;
  20930. for (index = 0; index < totalIndices; index++) {
  20931. var vertexIndex = indices[index];
  20932. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20933. kind = kinds[kindIndex];
  20934. var stride = vbs[kind].getStrideSize();
  20935. for (var offset = 0; offset < stride; offset++) {
  20936. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20937. }
  20938. }
  20939. }
  20940. // Updating faces & normal
  20941. var normals = [];
  20942. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20943. for (index = 0; index < totalIndices; index += 3) {
  20944. indices[index] = index;
  20945. indices[index + 1] = index + 1;
  20946. indices[index + 2] = index + 2;
  20947. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20948. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20949. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20950. var p1p2 = p1.subtract(p2);
  20951. var p3p2 = p3.subtract(p2);
  20952. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20953. // Store same normals for every vertex
  20954. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20955. normals.push(normal.x);
  20956. normals.push(normal.y);
  20957. normals.push(normal.z);
  20958. }
  20959. }
  20960. this.setIndices(indices);
  20961. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20962. // Updating vertex buffers
  20963. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20964. kind = kinds[kindIndex];
  20965. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20966. }
  20967. // Updating submeshes
  20968. this.releaseSubMeshes();
  20969. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20970. var previousOne = previousSubmeshes[submeshIndex];
  20971. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20972. }
  20973. this.synchronizeInstances();
  20974. };
  20975. /**
  20976. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20977. * In other words, more vertices, no more indices and a single bigger VBO.
  20978. * This method returns nothing.
  20979. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20980. *
  20981. */
  20982. Mesh.prototype.convertToUnIndexedMesh = function () {
  20983. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20984. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20985. var kinds = this.getVerticesDataKinds();
  20986. var vbs = [];
  20987. var data = [];
  20988. var newdata = [];
  20989. var updatableNormals = false;
  20990. var kindIndex;
  20991. var kind;
  20992. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20993. kind = kinds[kindIndex];
  20994. var vertexBuffer = this.getVertexBuffer(kind);
  20995. vbs[kind] = vertexBuffer;
  20996. data[kind] = vbs[kind].getData();
  20997. newdata[kind] = [];
  20998. }
  20999. // Save previous submeshes
  21000. var previousSubmeshes = this.subMeshes.slice(0);
  21001. var indices = this.getIndices();
  21002. var totalIndices = this.getTotalIndices();
  21003. // Generating unique vertices per face
  21004. var index;
  21005. for (index = 0; index < totalIndices; index++) {
  21006. var vertexIndex = indices[index];
  21007. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21008. kind = kinds[kindIndex];
  21009. var stride = vbs[kind].getStrideSize();
  21010. for (var offset = 0; offset < stride; offset++) {
  21011. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21012. }
  21013. }
  21014. }
  21015. // Updating indices
  21016. for (index = 0; index < totalIndices; index += 3) {
  21017. indices[index] = index;
  21018. indices[index + 1] = index + 1;
  21019. indices[index + 2] = index + 2;
  21020. }
  21021. this.setIndices(indices);
  21022. // Updating vertex buffers
  21023. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21024. kind = kinds[kindIndex];
  21025. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21026. }
  21027. // Updating submeshes
  21028. this.releaseSubMeshes();
  21029. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21030. var previousOne = previousSubmeshes[submeshIndex];
  21031. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21032. }
  21033. this._unIndexed = true;
  21034. this.synchronizeInstances();
  21035. };
  21036. /**
  21037. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21038. * This method returns nothing.
  21039. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21040. */
  21041. Mesh.prototype.flipFaces = function (flipNormals) {
  21042. if (flipNormals === void 0) { flipNormals = false; }
  21043. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21044. var i;
  21045. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21046. for (i = 0; i < vertex_data.normals.length; i++) {
  21047. vertex_data.normals[i] *= -1;
  21048. }
  21049. }
  21050. var temp;
  21051. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21052. // reassign indices
  21053. temp = vertex_data.indices[i + 1];
  21054. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21055. vertex_data.indices[i + 2] = temp;
  21056. }
  21057. vertex_data.applyToMesh(this);
  21058. };
  21059. // Instances
  21060. /**
  21061. * Creates a new InstancedMesh object from the mesh model.
  21062. * An instance shares the same properties and the same material than its model.
  21063. * Only these properties of each instance can then be set individually :
  21064. * - position
  21065. * - rotation
  21066. * - rotationQuaternion
  21067. * - setPivotMatrix
  21068. * - scaling
  21069. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21070. * Warning : this method is not supported for Line mesh and LineSystem
  21071. */
  21072. Mesh.prototype.createInstance = function (name) {
  21073. return new BABYLON.InstancedMesh(name, this);
  21074. };
  21075. /**
  21076. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21077. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21078. * This method returns nothing.
  21079. */
  21080. Mesh.prototype.synchronizeInstances = function () {
  21081. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21082. var instance = this.instances[instanceIndex];
  21083. instance._syncSubMeshes();
  21084. }
  21085. };
  21086. /**
  21087. * Simplify the mesh according to the given array of settings.
  21088. * Function will return immediately and will simplify async. It returns nothing.
  21089. * @param settings a collection of simplification settings.
  21090. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21091. * @param type the type of simplification to run.
  21092. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21093. */
  21094. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21095. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21096. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21097. this.getScene().simplificationQueue.addTask({
  21098. settings: settings,
  21099. parallelProcessing: parallelProcessing,
  21100. mesh: this,
  21101. simplificationType: simplificationType,
  21102. successCallback: successCallback
  21103. });
  21104. };
  21105. /**
  21106. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21107. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21108. * This should be used together with the simplification to avoid disappearing triangles.
  21109. * @param successCallback an optional success callback to be called after the optimization finished.
  21110. */
  21111. Mesh.prototype.optimizeIndices = function (successCallback) {
  21112. var _this = this;
  21113. var indices = this.getIndices();
  21114. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21115. var vectorPositions = [];
  21116. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21117. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21118. }
  21119. var dupes = [];
  21120. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21121. var realPos = vectorPositions.length - 1 - iteration;
  21122. var testedPosition = vectorPositions[realPos];
  21123. for (var j = 0; j < realPos; ++j) {
  21124. var againstPosition = vectorPositions[j];
  21125. if (testedPosition.equals(againstPosition)) {
  21126. dupes[realPos] = j;
  21127. break;
  21128. }
  21129. }
  21130. }, function () {
  21131. for (var i = 0; i < indices.length; ++i) {
  21132. indices[i] = dupes[indices[i]] || indices[i];
  21133. }
  21134. //indices are now reordered
  21135. var originalSubMeshes = _this.subMeshes.slice(0);
  21136. _this.setIndices(indices);
  21137. _this.subMeshes = originalSubMeshes;
  21138. if (successCallback) {
  21139. successCallback(_this);
  21140. }
  21141. });
  21142. };
  21143. // Statics
  21144. /**
  21145. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21146. * The parameter `parsedMesh` is the mesh to be copied.
  21147. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21148. */
  21149. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21150. var mesh = new Mesh(parsedMesh.name, scene);
  21151. mesh.id = parsedMesh.id;
  21152. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21153. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21154. if (parsedMesh.metadata !== undefined) {
  21155. mesh.metadata = parsedMesh.metadata;
  21156. }
  21157. if (parsedMesh.rotationQuaternion) {
  21158. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21159. }
  21160. else if (parsedMesh.rotation) {
  21161. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21162. }
  21163. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21164. if (parsedMesh.localMatrix) {
  21165. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21166. }
  21167. else if (parsedMesh.pivotMatrix) {
  21168. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21169. }
  21170. mesh.setEnabled(parsedMesh.isEnabled);
  21171. mesh.isVisible = parsedMesh.isVisible;
  21172. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21173. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21174. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21175. if (parsedMesh.applyFog !== undefined) {
  21176. mesh.applyFog = parsedMesh.applyFog;
  21177. }
  21178. if (parsedMesh.pickable !== undefined) {
  21179. mesh.isPickable = parsedMesh.pickable;
  21180. }
  21181. if (parsedMesh.alphaIndex !== undefined) {
  21182. mesh.alphaIndex = parsedMesh.alphaIndex;
  21183. }
  21184. mesh.receiveShadows = parsedMesh.receiveShadows;
  21185. mesh.billboardMode = parsedMesh.billboardMode;
  21186. if (parsedMesh.visibility !== undefined) {
  21187. mesh.visibility = parsedMesh.visibility;
  21188. }
  21189. mesh.checkCollisions = parsedMesh.checkCollisions;
  21190. if (parsedMesh.isBlocker !== undefined) {
  21191. mesh.isBlocker = parsedMesh.isBlocker;
  21192. }
  21193. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21194. // freezeWorldMatrix
  21195. if (parsedMesh.freezeWorldMatrix) {
  21196. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21197. }
  21198. // Parent
  21199. if (parsedMesh.parentId) {
  21200. mesh._waitingParentId = parsedMesh.parentId;
  21201. }
  21202. // Actions
  21203. if (parsedMesh.actions !== undefined) {
  21204. mesh._waitingActions = parsedMesh.actions;
  21205. }
  21206. // Overlay
  21207. if (parsedMesh.overlayAlpha !== undefined) {
  21208. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21209. }
  21210. if (parsedMesh.overlayColor !== undefined) {
  21211. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21212. }
  21213. if (parsedMesh.renderOverlay !== undefined) {
  21214. mesh.renderOverlay = parsedMesh.renderOverlay;
  21215. }
  21216. // Geometry
  21217. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21218. if (parsedMesh.delayLoadingFile) {
  21219. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21220. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21221. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21222. if (parsedMesh._binaryInfo) {
  21223. mesh._binaryInfo = parsedMesh._binaryInfo;
  21224. }
  21225. mesh._delayInfo = [];
  21226. if (parsedMesh.hasUVs) {
  21227. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21228. }
  21229. if (parsedMesh.hasUVs2) {
  21230. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21231. }
  21232. if (parsedMesh.hasUVs3) {
  21233. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21234. }
  21235. if (parsedMesh.hasUVs4) {
  21236. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21237. }
  21238. if (parsedMesh.hasUVs5) {
  21239. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21240. }
  21241. if (parsedMesh.hasUVs6) {
  21242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21243. }
  21244. if (parsedMesh.hasColors) {
  21245. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21246. }
  21247. if (parsedMesh.hasMatricesIndices) {
  21248. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21249. }
  21250. if (parsedMesh.hasMatricesWeights) {
  21251. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21252. }
  21253. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21254. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21255. mesh._checkDelayState();
  21256. }
  21257. }
  21258. else {
  21259. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21260. }
  21261. // Material
  21262. if (parsedMesh.materialId) {
  21263. mesh.setMaterialByID(parsedMesh.materialId);
  21264. }
  21265. else {
  21266. mesh.material = null;
  21267. }
  21268. // Skeleton
  21269. if (parsedMesh.skeletonId > -1) {
  21270. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21271. if (parsedMesh.numBoneInfluencers) {
  21272. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21273. }
  21274. }
  21275. // Animations
  21276. if (parsedMesh.animations) {
  21277. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21278. var parsedAnimation = parsedMesh.animations[animationIndex];
  21279. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21280. }
  21281. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21282. }
  21283. if (parsedMesh.autoAnimate) {
  21284. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21285. }
  21286. // Layer Mask
  21287. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21288. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21289. }
  21290. else {
  21291. mesh.layerMask = 0x0FFFFFFF;
  21292. }
  21293. //(Deprecated) physics
  21294. if (parsedMesh.physicsImpostor) {
  21295. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21296. mass: parsedMesh.physicsMass,
  21297. friction: parsedMesh.physicsFriction,
  21298. restitution: parsedMesh.physicsRestitution
  21299. }, scene);
  21300. }
  21301. // Instances
  21302. if (parsedMesh.instances) {
  21303. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21304. var parsedInstance = parsedMesh.instances[index];
  21305. var instance = mesh.createInstance(parsedInstance.name);
  21306. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21307. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21308. if (parsedInstance.parentId) {
  21309. instance._waitingParentId = parsedInstance.parentId;
  21310. }
  21311. if (parsedInstance.rotationQuaternion) {
  21312. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21313. }
  21314. else if (parsedInstance.rotation) {
  21315. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21316. }
  21317. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21318. instance.checkCollisions = mesh.checkCollisions;
  21319. if (parsedMesh.animations) {
  21320. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21321. parsedAnimation = parsedMesh.animations[animationIndex];
  21322. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21323. }
  21324. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21325. }
  21326. }
  21327. }
  21328. return mesh;
  21329. };
  21330. /**
  21331. * Creates a ribbon mesh.
  21332. * Please consider using the same method from the MeshBuilder class instead.
  21333. * 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.
  21334. *
  21335. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21336. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21337. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21338. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21339. * 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.
  21340. * 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.
  21341. * 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
  21342. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21345. */
  21346. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21347. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21348. pathArray: pathArray,
  21349. closeArray: closeArray,
  21350. closePath: closePath,
  21351. offset: offset,
  21352. updatable: updatable,
  21353. sideOrientation: sideOrientation,
  21354. instance: instance
  21355. }, scene);
  21356. };
  21357. /**
  21358. * Creates a plane polygonal mesh. By default, this is a disc.
  21359. * Please consider using the same method from the MeshBuilder class instead.
  21360. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21361. * 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.
  21362. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21365. */
  21366. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21367. var options = {
  21368. radius: radius,
  21369. tessellation: tessellation,
  21370. sideOrientation: sideOrientation,
  21371. updatable: updatable
  21372. };
  21373. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21374. };
  21375. /**
  21376. * Creates a box mesh.
  21377. * Please consider using the same method from the MeshBuilder class instead.
  21378. * The parameter `size` sets the size (float) of each box side (default 1).
  21379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21380. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21382. */
  21383. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21384. var options = {
  21385. size: size,
  21386. sideOrientation: sideOrientation,
  21387. updatable: updatable
  21388. };
  21389. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21390. };
  21391. /**
  21392. * Creates a sphere mesh.
  21393. * Please consider using the same method from the MeshBuilder class instead.
  21394. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21395. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21397. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21398. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21399. */
  21400. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21401. var options = {
  21402. segments: segments,
  21403. diameterX: diameter,
  21404. diameterY: diameter,
  21405. diameterZ: diameter,
  21406. sideOrientation: sideOrientation,
  21407. updatable: updatable
  21408. };
  21409. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21410. };
  21411. /**
  21412. * Creates a cylinder or a cone mesh.
  21413. * Please consider using the same method from the MeshBuilder class instead.
  21414. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21415. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21416. * 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.
  21417. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21418. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21422. */
  21423. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21424. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21425. if (scene !== undefined) {
  21426. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21427. updatable = scene;
  21428. }
  21429. scene = subdivisions;
  21430. subdivisions = 1;
  21431. }
  21432. var options = {
  21433. height: height,
  21434. diameterTop: diameterTop,
  21435. diameterBottom: diameterBottom,
  21436. tessellation: tessellation,
  21437. subdivisions: subdivisions,
  21438. sideOrientation: sideOrientation,
  21439. updatable: updatable
  21440. };
  21441. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21442. };
  21443. // Torus (Code from SharpDX.org)
  21444. /**
  21445. * Creates a torus mesh.
  21446. * Please consider using the same method from the MeshBuilder class instead.
  21447. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21448. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21449. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21453. */
  21454. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21455. var options = {
  21456. diameter: diameter,
  21457. thickness: thickness,
  21458. tessellation: tessellation,
  21459. sideOrientation: sideOrientation,
  21460. updatable: updatable
  21461. };
  21462. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21463. };
  21464. /**
  21465. * Creates a torus knot mesh.
  21466. * Please consider using the same method from the MeshBuilder class instead.
  21467. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21468. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21469. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21470. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21474. */
  21475. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21476. var options = {
  21477. radius: radius,
  21478. tube: tube,
  21479. radialSegments: radialSegments,
  21480. tubularSegments: tubularSegments,
  21481. p: p,
  21482. q: q,
  21483. sideOrientation: sideOrientation,
  21484. updatable: updatable
  21485. };
  21486. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21487. };
  21488. /**
  21489. * Creates a line mesh.
  21490. * Please consider using the same method from the MeshBuilder class instead.
  21491. * 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.
  21492. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21493. * The parameter `points` is an array successive Vector3.
  21494. * 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
  21495. * When updating an instance, remember that only point positions can change, not the number of points.
  21496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21497. */
  21498. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21499. var options = {
  21500. points: points,
  21501. updatable: updatable,
  21502. instance: instance
  21503. };
  21504. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21505. };
  21506. /**
  21507. * Creates a dashed line mesh.
  21508. * Please consider using the same method from the MeshBuilder class instead.
  21509. * 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.
  21510. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21511. * The parameter `points` is an array successive Vector3.
  21512. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21513. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21514. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21515. * 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
  21516. * When updating an instance, remember that only point positions can change, not the number of points.
  21517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21518. */
  21519. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21520. var options = {
  21521. points: points,
  21522. dashSize: dashSize,
  21523. gapSize: gapSize,
  21524. dashNb: dashNb,
  21525. updatable: updatable,
  21526. instance: instance
  21527. };
  21528. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21529. };
  21530. /**
  21531. * Creates an extruded shape mesh.
  21532. * 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.
  21533. * Please consider using the same method from the MeshBuilder class instead.
  21534. *
  21535. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21536. * 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
  21537. * extruded along the Z axis.
  21538. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21539. * 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.
  21540. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21541. * 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
  21542. * 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
  21543. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21544. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21547. */
  21548. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21549. var options = {
  21550. shape: shape,
  21551. path: path,
  21552. scale: scale,
  21553. rotation: rotation,
  21554. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21555. sideOrientation: sideOrientation,
  21556. instance: instance,
  21557. updatable: updatable
  21558. };
  21559. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21560. };
  21561. /**
  21562. * Creates an custom extruded shape mesh.
  21563. * 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.
  21564. * Please consider using the same method from the MeshBuilder class instead.
  21565. *
  21566. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21567. * 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
  21568. * extruded along the Z axis.
  21569. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21570. * 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
  21571. * and the distance of this point from the begining of the path :
  21572. * ```javascript
  21573. * var rotationFunction = function(i, distance) {
  21574. * // do things
  21575. * return rotationValue; }
  21576. * ```
  21577. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21578. * 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
  21579. * and the distance of this point from the begining of the path :
  21580. * ```javascript
  21581. * var scaleFunction = function(i, distance) {
  21582. * // do things
  21583. * return scaleValue;}
  21584. * ```
  21585. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21586. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21587. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21588. * 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
  21589. * 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
  21590. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21594. */
  21595. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21596. var options = {
  21597. shape: shape,
  21598. path: path,
  21599. scaleFunction: scaleFunction,
  21600. rotationFunction: rotationFunction,
  21601. ribbonCloseArray: ribbonCloseArray,
  21602. ribbonClosePath: ribbonClosePath,
  21603. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21604. sideOrientation: sideOrientation,
  21605. instance: instance,
  21606. updatable: updatable
  21607. };
  21608. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21609. };
  21610. /**
  21611. * Creates lathe mesh.
  21612. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21613. * Please consider using the same method from the MeshBuilder class instead.
  21614. * 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
  21615. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21616. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21617. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21621. */
  21622. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21623. var options = {
  21624. shape: shape,
  21625. radius: radius,
  21626. tessellation: tessellation,
  21627. sideOrientation: sideOrientation,
  21628. updatable: updatable
  21629. };
  21630. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21631. };
  21632. /**
  21633. * Creates a plane mesh.
  21634. * Please consider using the same method from the MeshBuilder class instead.
  21635. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21639. */
  21640. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21641. var options = {
  21642. size: size,
  21643. width: size,
  21644. height: size,
  21645. sideOrientation: sideOrientation,
  21646. updatable: updatable
  21647. };
  21648. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21649. };
  21650. /**
  21651. * Creates a ground mesh.
  21652. * Please consider using the same method from the MeshBuilder class instead.
  21653. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21654. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21655. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21656. */
  21657. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21658. var options = {
  21659. width: width,
  21660. height: height,
  21661. subdivisions: subdivisions,
  21662. updatable: updatable
  21663. };
  21664. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21665. };
  21666. /**
  21667. * Creates a tiled ground mesh.
  21668. * Please consider using the same method from the MeshBuilder class instead.
  21669. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21670. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21671. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21672. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21673. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21674. * numbers of subdivisions on the ground width and height of each tile.
  21675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21676. */
  21677. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21678. var options = {
  21679. xmin: xmin,
  21680. zmin: zmin,
  21681. xmax: xmax,
  21682. zmax: zmax,
  21683. subdivisions: subdivisions,
  21684. precision: precision,
  21685. updatable: updatable
  21686. };
  21687. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21688. };
  21689. /**
  21690. * Creates a ground mesh from a height map.
  21691. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21692. * Please consider using the same method from the MeshBuilder class instead.
  21693. * The parameter `url` sets the URL of the height map image resource.
  21694. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21695. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21696. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21697. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21698. * 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).
  21699. * This function is passed the newly built mesh :
  21700. * ```javascript
  21701. * function(mesh) { // do things
  21702. * return; }
  21703. * ```
  21704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21705. */
  21706. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21707. var options = {
  21708. width: width,
  21709. height: height,
  21710. subdivisions: subdivisions,
  21711. minHeight: minHeight,
  21712. maxHeight: maxHeight,
  21713. updatable: updatable,
  21714. onReady: onReady
  21715. };
  21716. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21717. };
  21718. /**
  21719. * Creates a tube mesh.
  21720. * 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.
  21721. * Please consider using the same method from the MeshBuilder class instead.
  21722. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21723. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21724. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21725. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21726. * 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.
  21727. * It must return a radius value (positive float) :
  21728. * ```javascript
  21729. * var radiusFunction = function(i, distance) {
  21730. * // do things
  21731. * return radius; }
  21732. * ```
  21733. * 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
  21734. * 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
  21735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21737. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21738. */
  21739. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21740. var options = {
  21741. path: path,
  21742. radius: radius,
  21743. tessellation: tessellation,
  21744. radiusFunction: radiusFunction,
  21745. arc: 1,
  21746. cap: cap,
  21747. updatable: updatable,
  21748. sideOrientation: sideOrientation,
  21749. instance: instance
  21750. };
  21751. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21752. };
  21753. /**
  21754. * Creates a polyhedron mesh.
  21755. * Please consider using the same method from the MeshBuilder class instead.
  21756. * 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
  21757. * to choose the wanted type.
  21758. * The parameter `size` (positive float, default 1) sets the polygon size.
  21759. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21760. * 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`.
  21761. * 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
  21762. * 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)`).
  21763. * 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
  21764. * 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.
  21765. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21766. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21768. */
  21769. Mesh.CreatePolyhedron = function (name, options, scene) {
  21770. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21771. };
  21772. /**
  21773. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21774. * Please consider using the same method from the MeshBuilder class instead.
  21775. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21776. * 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`).
  21777. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21778. * 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.
  21779. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21780. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21782. */
  21783. Mesh.CreateIcoSphere = function (name, options, scene) {
  21784. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21785. };
  21786. /**
  21787. * Creates a decal mesh.
  21788. * Please consider using the same method from the MeshBuilder class instead.
  21789. * 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.
  21790. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21791. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21792. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21793. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21794. */
  21795. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21796. var options = {
  21797. position: position,
  21798. normal: normal,
  21799. size: size,
  21800. angle: angle
  21801. };
  21802. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21803. };
  21804. // Skeletons
  21805. /**
  21806. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21807. */
  21808. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21809. var source;
  21810. if (!this._sourcePositions) {
  21811. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21812. this._sourcePositions = new Float32Array(source);
  21813. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21814. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21815. }
  21816. }
  21817. return this._sourcePositions;
  21818. };
  21819. /**
  21820. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21821. */
  21822. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21823. var source;
  21824. if (!this._sourceNormals) {
  21825. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21826. this._sourceNormals = new Float32Array(source);
  21827. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21828. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21829. }
  21830. }
  21831. return this._sourceNormals;
  21832. };
  21833. /**
  21834. * Update the vertex buffers by applying transformation from the bones
  21835. * @param {skeleton} skeleton to apply
  21836. */
  21837. Mesh.prototype.applySkeleton = function (skeleton) {
  21838. if (!this.geometry) {
  21839. return;
  21840. }
  21841. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21842. return;
  21843. }
  21844. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21845. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21846. return this;
  21847. }
  21848. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21849. return this;
  21850. }
  21851. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21852. return this;
  21853. }
  21854. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21855. return this;
  21856. }
  21857. if (!this._sourcePositions) {
  21858. var submeshes = this.subMeshes.slice();
  21859. this.setPositionsForCPUSkinning();
  21860. this.subMeshes = submeshes;
  21861. }
  21862. if (!this._sourceNormals) {
  21863. this.setNormalsForCPUSkinning();
  21864. }
  21865. // positionsData checks for not being Float32Array will only pass at most once
  21866. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21867. if (!(positionsData instanceof Float32Array)) {
  21868. positionsData = new Float32Array(positionsData);
  21869. }
  21870. // normalsData checks for not being Float32Array will only pass at most once
  21871. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21872. if (!(normalsData instanceof Float32Array)) {
  21873. normalsData = new Float32Array(normalsData);
  21874. }
  21875. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21876. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21877. var needExtras = this.numBoneInfluencers > 4;
  21878. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21879. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21880. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21881. var tempVector3 = BABYLON.Vector3.Zero();
  21882. var finalMatrix = new BABYLON.Matrix();
  21883. var tempMatrix = new BABYLON.Matrix();
  21884. var matWeightIdx = 0;
  21885. var inf;
  21886. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21887. var weight;
  21888. for (inf = 0; inf < 4; inf++) {
  21889. weight = matricesWeightsData[matWeightIdx + inf];
  21890. if (weight > 0) {
  21891. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21892. finalMatrix.addToSelf(tempMatrix);
  21893. }
  21894. else
  21895. break;
  21896. }
  21897. if (needExtras) {
  21898. for (inf = 0; inf < 4; inf++) {
  21899. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21900. if (weight > 0) {
  21901. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21902. finalMatrix.addToSelf(tempMatrix);
  21903. }
  21904. else
  21905. break;
  21906. }
  21907. }
  21908. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21909. tempVector3.toArray(positionsData, index);
  21910. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21911. tempVector3.toArray(normalsData, index);
  21912. finalMatrix.reset();
  21913. }
  21914. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21915. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21916. return this;
  21917. };
  21918. // Tools
  21919. /**
  21920. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21921. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21922. */
  21923. Mesh.MinMax = function (meshes) {
  21924. var minVector = null;
  21925. var maxVector = null;
  21926. meshes.forEach(function (mesh, index, array) {
  21927. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21928. if (!minVector) {
  21929. minVector = boundingBox.minimumWorld;
  21930. maxVector = boundingBox.maximumWorld;
  21931. }
  21932. else {
  21933. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21934. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21935. }
  21936. });
  21937. return {
  21938. min: minVector,
  21939. max: maxVector
  21940. };
  21941. };
  21942. /**
  21943. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21944. */
  21945. Mesh.Center = function (meshesOrMinMaxVector) {
  21946. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21947. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21948. };
  21949. /**
  21950. * Merge the array of meshes into a single mesh for performance reasons.
  21951. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21952. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21953. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21954. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21955. */
  21956. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21957. if (disposeSource === void 0) { disposeSource = true; }
  21958. var index;
  21959. if (!allow32BitsIndices) {
  21960. var totalVertices = 0;
  21961. // Counting vertices
  21962. for (index = 0; index < meshes.length; index++) {
  21963. if (meshes[index]) {
  21964. totalVertices += meshes[index].getTotalVertices();
  21965. if (totalVertices > 65536) {
  21966. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21967. return null;
  21968. }
  21969. }
  21970. }
  21971. }
  21972. // Merge
  21973. var vertexData;
  21974. var otherVertexData;
  21975. var source;
  21976. for (index = 0; index < meshes.length; index++) {
  21977. if (meshes[index]) {
  21978. meshes[index].computeWorldMatrix(true);
  21979. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21980. otherVertexData.transform(meshes[index].getWorldMatrix());
  21981. if (vertexData) {
  21982. vertexData.merge(otherVertexData);
  21983. }
  21984. else {
  21985. vertexData = otherVertexData;
  21986. source = meshes[index];
  21987. }
  21988. }
  21989. }
  21990. if (!meshSubclass) {
  21991. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21992. }
  21993. vertexData.applyToMesh(meshSubclass);
  21994. // Setting properties
  21995. meshSubclass.material = source.material;
  21996. meshSubclass.checkCollisions = source.checkCollisions;
  21997. // Cleaning
  21998. if (disposeSource) {
  21999. for (index = 0; index < meshes.length; index++) {
  22000. if (meshes[index]) {
  22001. meshes[index].dispose();
  22002. }
  22003. }
  22004. }
  22005. return meshSubclass;
  22006. };
  22007. return Mesh;
  22008. }(BABYLON.AbstractMesh));
  22009. // Consts
  22010. Mesh._FRONTSIDE = 0;
  22011. Mesh._BACKSIDE = 1;
  22012. Mesh._DOUBLESIDE = 2;
  22013. Mesh._DEFAULTSIDE = 0;
  22014. Mesh._NO_CAP = 0;
  22015. Mesh._CAP_START = 1;
  22016. Mesh._CAP_END = 2;
  22017. Mesh._CAP_ALL = 3;
  22018. BABYLON.Mesh = Mesh;
  22019. })(BABYLON || (BABYLON = {}));
  22020. //# sourceMappingURL=babylon.mesh.js.map
  22021. var BABYLON;
  22022. (function (BABYLON) {
  22023. var SubMesh = (function () {
  22024. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22025. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22026. this.materialIndex = materialIndex;
  22027. this.verticesStart = verticesStart;
  22028. this.verticesCount = verticesCount;
  22029. this.indexStart = indexStart;
  22030. this.indexCount = indexCount;
  22031. this._renderId = 0;
  22032. this._mesh = mesh;
  22033. this._renderingMesh = renderingMesh || mesh;
  22034. mesh.subMeshes.push(this);
  22035. this._trianglePlanes = [];
  22036. this._id = mesh.subMeshes.length - 1;
  22037. if (createBoundingBox) {
  22038. this.refreshBoundingInfo();
  22039. mesh.computeWorldMatrix(true);
  22040. }
  22041. }
  22042. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22043. get: function () {
  22044. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22045. },
  22046. enumerable: true,
  22047. configurable: true
  22048. });
  22049. SubMesh.prototype.getBoundingInfo = function () {
  22050. if (this.IsGlobal) {
  22051. return this._mesh.getBoundingInfo();
  22052. }
  22053. return this._boundingInfo;
  22054. };
  22055. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22056. this._boundingInfo = boundingInfo;
  22057. };
  22058. SubMesh.prototype.getMesh = function () {
  22059. return this._mesh;
  22060. };
  22061. SubMesh.prototype.getRenderingMesh = function () {
  22062. return this._renderingMesh;
  22063. };
  22064. SubMesh.prototype.getMaterial = function () {
  22065. var rootMaterial = this._renderingMesh.material;
  22066. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22067. var multiMaterial = rootMaterial;
  22068. return multiMaterial.getSubMaterial(this.materialIndex);
  22069. }
  22070. if (!rootMaterial) {
  22071. return this._mesh.getScene().defaultMaterial;
  22072. }
  22073. return rootMaterial;
  22074. };
  22075. // Methods
  22076. SubMesh.prototype.refreshBoundingInfo = function () {
  22077. this._lastColliderWorldVertices = null;
  22078. if (this.IsGlobal) {
  22079. return;
  22080. }
  22081. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22082. if (!data) {
  22083. this._boundingInfo = this._mesh._boundingInfo;
  22084. return;
  22085. }
  22086. var indices = this._renderingMesh.getIndices();
  22087. var extend;
  22088. //is this the only submesh?
  22089. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22090. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22091. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22092. }
  22093. else {
  22094. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22095. }
  22096. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22097. };
  22098. SubMesh.prototype._checkCollision = function (collider) {
  22099. return this.getBoundingInfo()._checkCollision(collider);
  22100. };
  22101. SubMesh.prototype.updateBoundingInfo = function (world) {
  22102. if (!this.getBoundingInfo()) {
  22103. this.refreshBoundingInfo();
  22104. }
  22105. this.getBoundingInfo().update(world);
  22106. };
  22107. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22108. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22109. };
  22110. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22111. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22112. };
  22113. SubMesh.prototype.render = function (enableAlphaMode) {
  22114. this._renderingMesh.render(this, enableAlphaMode);
  22115. };
  22116. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22117. if (!this._linesIndexBuffer) {
  22118. var linesIndices = [];
  22119. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22120. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22121. }
  22122. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22123. this.linesIndexCount = linesIndices.length;
  22124. }
  22125. return this._linesIndexBuffer;
  22126. };
  22127. SubMesh.prototype.canIntersects = function (ray) {
  22128. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22129. };
  22130. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22131. var intersectInfo = null;
  22132. // LineMesh first as it's also a Mesh...
  22133. if (this._mesh instanceof BABYLON.LinesMesh) {
  22134. var lineMesh = this._mesh;
  22135. // Line test
  22136. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22137. var p0 = positions[indices[index]];
  22138. var p1 = positions[indices[index + 1]];
  22139. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22140. if (length < 0) {
  22141. continue;
  22142. }
  22143. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22144. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22145. if (fastCheck) {
  22146. break;
  22147. }
  22148. }
  22149. }
  22150. }
  22151. else {
  22152. // Triangles test
  22153. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22154. var p0 = positions[indices[index]];
  22155. var p1 = positions[indices[index + 1]];
  22156. var p2 = positions[indices[index + 2]];
  22157. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22158. if (currentIntersectInfo) {
  22159. if (currentIntersectInfo.distance < 0) {
  22160. continue;
  22161. }
  22162. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22163. intersectInfo = currentIntersectInfo;
  22164. intersectInfo.faceId = index / 3;
  22165. if (fastCheck) {
  22166. break;
  22167. }
  22168. }
  22169. }
  22170. }
  22171. }
  22172. return intersectInfo;
  22173. };
  22174. // Clone
  22175. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22176. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22177. if (!this.IsGlobal) {
  22178. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22179. }
  22180. return result;
  22181. };
  22182. // Dispose
  22183. SubMesh.prototype.dispose = function () {
  22184. if (this._linesIndexBuffer) {
  22185. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22186. this._linesIndexBuffer = null;
  22187. }
  22188. // Remove from mesh
  22189. var index = this._mesh.subMeshes.indexOf(this);
  22190. this._mesh.subMeshes.splice(index, 1);
  22191. };
  22192. // Statics
  22193. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22194. var minVertexIndex = Number.MAX_VALUE;
  22195. var maxVertexIndex = -Number.MAX_VALUE;
  22196. renderingMesh = renderingMesh || mesh;
  22197. var indices = renderingMesh.getIndices();
  22198. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22199. var vertexIndex = indices[index];
  22200. if (vertexIndex < minVertexIndex)
  22201. minVertexIndex = vertexIndex;
  22202. if (vertexIndex > maxVertexIndex)
  22203. maxVertexIndex = vertexIndex;
  22204. }
  22205. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22206. };
  22207. return SubMesh;
  22208. }());
  22209. BABYLON.SubMesh = SubMesh;
  22210. })(BABYLON || (BABYLON = {}));
  22211. //# sourceMappingURL=babylon.subMesh.js.map
  22212. var BABYLON;
  22213. (function (BABYLON) {
  22214. var MeshBuilder = (function () {
  22215. function MeshBuilder() {
  22216. }
  22217. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22218. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22219. return BABYLON.Mesh.DOUBLESIDE;
  22220. }
  22221. if (orientation === undefined || orientation === null) {
  22222. return BABYLON.Mesh.FRONTSIDE;
  22223. }
  22224. return orientation;
  22225. };
  22226. /**
  22227. * Creates a box mesh.
  22228. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22229. * The parameter `size` sets the size (float) of each box side (default 1).
  22230. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22231. * 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).
  22232. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22236. */
  22237. MeshBuilder.CreateBox = function (name, options, scene) {
  22238. var box = new BABYLON.Mesh(name, scene);
  22239. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22240. box.sideOrientation = options.sideOrientation;
  22241. var vertexData = BABYLON.VertexData.CreateBox(options);
  22242. vertexData.applyToMesh(box, options.updatable);
  22243. return box;
  22244. };
  22245. /**
  22246. * Creates a sphere mesh.
  22247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22248. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22249. * 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`).
  22250. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22251. * 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
  22252. * 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).
  22253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22256. */
  22257. MeshBuilder.CreateSphere = function (name, options, scene) {
  22258. var sphere = new BABYLON.Mesh(name, scene);
  22259. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22260. sphere.sideOrientation = options.sideOrientation;
  22261. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22262. vertexData.applyToMesh(sphere, options.updatable);
  22263. return sphere;
  22264. };
  22265. /**
  22266. * Creates a plane polygonal mesh. By default, this is a disc.
  22267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22268. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22269. * 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.
  22270. * 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
  22271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22274. */
  22275. MeshBuilder.CreateDisc = function (name, options, scene) {
  22276. var disc = new BABYLON.Mesh(name, scene);
  22277. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22278. disc.sideOrientation = options.sideOrientation;
  22279. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22280. vertexData.applyToMesh(disc, options.updatable);
  22281. return disc;
  22282. };
  22283. /**
  22284. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22286. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22287. * 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`).
  22288. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22289. * 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.
  22290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22291. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22293. */
  22294. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22295. var sphere = new BABYLON.Mesh(name, scene);
  22296. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22297. sphere.sideOrientation = options.sideOrientation;
  22298. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22299. vertexData.applyToMesh(sphere, options.updatable);
  22300. return sphere;
  22301. };
  22302. ;
  22303. /**
  22304. * Creates a ribbon mesh.
  22305. * 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.
  22306. *
  22307. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22308. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22309. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22310. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22311. * 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.
  22312. * 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.
  22313. * 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
  22314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22316. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22318. */
  22319. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22320. var pathArray = options.pathArray;
  22321. var closeArray = options.closeArray;
  22322. var closePath = options.closePath;
  22323. var offset = options.offset;
  22324. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22325. var instance = options.instance;
  22326. var updatable = options.updatable;
  22327. if (instance) {
  22328. // positionFunction : ribbon case
  22329. // only pathArray and sideOrientation parameters are taken into account for positions update
  22330. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22331. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22332. var positionFunction = function (positions) {
  22333. var minlg = pathArray[0].length;
  22334. var i = 0;
  22335. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22336. for (var si = 1; si <= ns; si++) {
  22337. for (var p = 0; p < pathArray.length; p++) {
  22338. var path = pathArray[p];
  22339. var l = path.length;
  22340. minlg = (minlg < l) ? minlg : l;
  22341. var j = 0;
  22342. while (j < minlg) {
  22343. positions[i] = path[j].x;
  22344. positions[i + 1] = path[j].y;
  22345. positions[i + 2] = path[j].z;
  22346. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22347. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22348. }
  22349. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22350. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22351. }
  22352. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22353. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22354. }
  22355. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22356. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22357. }
  22358. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22359. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22360. }
  22361. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22362. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22363. }
  22364. j++;
  22365. i += 3;
  22366. }
  22367. if (instance._closePath) {
  22368. positions[i] = path[0].x;
  22369. positions[i + 1] = path[0].y;
  22370. positions[i + 2] = path[0].z;
  22371. i += 3;
  22372. }
  22373. }
  22374. }
  22375. };
  22376. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22377. positionFunction(positions);
  22378. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22379. instance._boundingInfo.update(instance._worldMatrix);
  22380. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22381. if (!(instance.areNormalsFrozen)) {
  22382. var indices = instance.getIndices();
  22383. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22384. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22385. if (instance._closePath) {
  22386. var indexFirst = 0;
  22387. var indexLast = 0;
  22388. for (var p = 0; p < pathArray.length; p++) {
  22389. indexFirst = instance._idx[p] * 3;
  22390. if (p + 1 < pathArray.length) {
  22391. indexLast = (instance._idx[p + 1] - 1) * 3;
  22392. }
  22393. else {
  22394. indexLast = normals.length - 3;
  22395. }
  22396. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22397. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22398. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22399. normals[indexLast] = normals[indexFirst];
  22400. normals[indexLast + 1] = normals[indexFirst + 1];
  22401. normals[indexLast + 2] = normals[indexFirst + 2];
  22402. }
  22403. }
  22404. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22405. }
  22406. return instance;
  22407. }
  22408. else {
  22409. var ribbon = new BABYLON.Mesh(name, scene);
  22410. ribbon.sideOrientation = sideOrientation;
  22411. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22412. if (closePath) {
  22413. ribbon._idx = vertexData._idx;
  22414. }
  22415. ribbon._closePath = closePath;
  22416. ribbon._closeArray = closeArray;
  22417. vertexData.applyToMesh(ribbon, updatable);
  22418. return ribbon;
  22419. }
  22420. };
  22421. /**
  22422. * Creates a cylinder or a cone mesh.
  22423. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22424. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22425. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22426. * 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.
  22427. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22428. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22429. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22430. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22431. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22432. * 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).
  22433. * 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
  22434. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22435. * 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
  22436. * 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.
  22437. * If `enclose` is false, a ring surface is one element.
  22438. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22439. * 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
  22440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22443. */
  22444. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22445. var cylinder = new BABYLON.Mesh(name, scene);
  22446. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22447. cylinder.sideOrientation = options.sideOrientation;
  22448. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22449. vertexData.applyToMesh(cylinder, options.updatable);
  22450. return cylinder;
  22451. };
  22452. /**
  22453. * Creates a torus mesh.
  22454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22455. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22456. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22457. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22461. */
  22462. MeshBuilder.CreateTorus = function (name, options, scene) {
  22463. var torus = new BABYLON.Mesh(name, scene);
  22464. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22465. torus.sideOrientation = options.sideOrientation;
  22466. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22467. vertexData.applyToMesh(torus, options.updatable);
  22468. return torus;
  22469. };
  22470. /**
  22471. * Creates a torus knot mesh.
  22472. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22473. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22474. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22475. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22476. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22478. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22480. */
  22481. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22482. var torusKnot = new BABYLON.Mesh(name, scene);
  22483. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22484. torusKnot.sideOrientation = options.sideOrientation;
  22485. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22486. vertexData.applyToMesh(torusKnot, options.updatable);
  22487. return torusKnot;
  22488. };
  22489. /**
  22490. * Creates a line system mesh.
  22491. * A line system is a pool of many lines gathered in a single mesh.
  22492. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22493. * 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.
  22494. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22495. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22496. * 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
  22497. * 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
  22498. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22500. */
  22501. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22502. var instance = options.instance;
  22503. var lines = options.lines;
  22504. if (instance) {
  22505. var positionFunction = function (positions) {
  22506. var i = 0;
  22507. for (var l = 0; l < lines.length; l++) {
  22508. var points = lines[l];
  22509. for (var p = 0; p < points.length; p++) {
  22510. positions[i] = points[p].x;
  22511. positions[i + 1] = points[p].y;
  22512. positions[i + 2] = points[p].z;
  22513. i += 3;
  22514. }
  22515. }
  22516. };
  22517. instance.updateMeshPositions(positionFunction, false);
  22518. return instance;
  22519. }
  22520. // line system creation
  22521. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22522. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22523. vertexData.applyToMesh(lineSystem, options.updatable);
  22524. return lineSystem;
  22525. };
  22526. /**
  22527. * Creates a line mesh.
  22528. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22529. * 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.
  22530. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22531. * The parameter `points` is an array successive Vector3.
  22532. * 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
  22533. * When updating an instance, remember that only point positions can change, not the number of points.
  22534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22535. */
  22536. MeshBuilder.CreateLines = function (name, options, scene) {
  22537. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22538. return lines;
  22539. };
  22540. /**
  22541. * Creates a dashed line mesh.
  22542. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22543. * 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.
  22544. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22545. * The parameter `points` is an array successive Vector3.
  22546. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22547. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22548. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22549. * 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
  22550. * When updating an instance, remember that only point positions can change, not the number of points.
  22551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22552. */
  22553. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22554. var points = options.points;
  22555. var instance = options.instance;
  22556. var gapSize = options.gapSize;
  22557. var dashNb = options.dashNb;
  22558. var dashSize = options.dashSize;
  22559. if (instance) {
  22560. var positionFunction = function (positions) {
  22561. var curvect = BABYLON.Vector3.Zero();
  22562. var nbSeg = positions.length / 6;
  22563. var lg = 0;
  22564. var nb = 0;
  22565. var shft = 0;
  22566. var dashshft = 0;
  22567. var curshft = 0;
  22568. var p = 0;
  22569. var i = 0;
  22570. var j = 0;
  22571. for (i = 0; i < points.length - 1; i++) {
  22572. points[i + 1].subtractToRef(points[i], curvect);
  22573. lg += curvect.length();
  22574. }
  22575. shft = lg / nbSeg;
  22576. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22577. for (i = 0; i < points.length - 1; i++) {
  22578. points[i + 1].subtractToRef(points[i], curvect);
  22579. nb = Math.floor(curvect.length() / shft);
  22580. curvect.normalize();
  22581. j = 0;
  22582. while (j < nb && p < positions.length) {
  22583. curshft = shft * j;
  22584. positions[p] = points[i].x + curshft * curvect.x;
  22585. positions[p + 1] = points[i].y + curshft * curvect.y;
  22586. positions[p + 2] = points[i].z + curshft * curvect.z;
  22587. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22588. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22589. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22590. p += 6;
  22591. j++;
  22592. }
  22593. }
  22594. while (p < positions.length) {
  22595. positions[p] = points[i].x;
  22596. positions[p + 1] = points[i].y;
  22597. positions[p + 2] = points[i].z;
  22598. p += 3;
  22599. }
  22600. };
  22601. instance.updateMeshPositions(positionFunction, false);
  22602. return instance;
  22603. }
  22604. // dashed lines creation
  22605. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22606. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22607. vertexData.applyToMesh(dashedLines, options.updatable);
  22608. dashedLines.dashSize = dashSize;
  22609. dashedLines.gapSize = gapSize;
  22610. return dashedLines;
  22611. };
  22612. /**
  22613. * Creates an extruded shape mesh.
  22614. * 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.
  22615. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22616. *
  22617. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22618. * 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
  22619. * extruded along the Z axis.
  22620. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22621. * 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.
  22622. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22623. * 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
  22624. * 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
  22625. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22628. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22630. */
  22631. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22632. var path = options.path;
  22633. var shape = options.shape;
  22634. var scale = options.scale || 1;
  22635. var rotation = options.rotation || 0;
  22636. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22637. var updatable = options.updatable;
  22638. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22639. var instance = options.instance;
  22640. var invertUV = options.invertUV || false;
  22641. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22642. };
  22643. /**
  22644. * Creates an custom extruded shape mesh.
  22645. * 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.
  22646. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22647. *
  22648. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22649. * 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
  22650. * extruded along the Z axis.
  22651. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22652. * 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
  22653. * and the distance of this point from the begining of the path :
  22654. * ```javascript
  22655. * var rotationFunction = function(i, distance) {
  22656. * // do things
  22657. * return rotationValue; }
  22658. * ```
  22659. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22660. * 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
  22661. * and the distance of this point from the begining of the path :
  22662. * ```javascript
  22663. * var scaleFunction = function(i, distance) {
  22664. * // do things
  22665. * return scaleValue;}
  22666. * ```
  22667. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22668. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22669. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22670. * 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
  22671. * 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
  22672. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22673. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22674. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22675. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22677. */
  22678. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22679. var path = options.path;
  22680. var shape = options.shape;
  22681. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22682. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22683. var ribbonCloseArray = options.ribbonCloseArray || false;
  22684. var ribbonClosePath = options.ribbonClosePath || false;
  22685. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22686. var updatable = options.updatable;
  22687. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22688. var instance = options.instance;
  22689. var invertUV = options.invertUV || false;
  22690. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22691. };
  22692. /**
  22693. * Creates lathe mesh.
  22694. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22695. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22696. *
  22697. * 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
  22698. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22699. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22700. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22701. * 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.
  22702. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22703. * 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
  22704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22705. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22706. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22708. */
  22709. MeshBuilder.CreateLathe = function (name, options, scene) {
  22710. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22711. var closed = (options.closed === undefined) ? true : options.closed;
  22712. var shape = options.shape;
  22713. var radius = options.radius || 1;
  22714. var tessellation = options.tessellation || 64;
  22715. var updatable = options.updatable;
  22716. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22717. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22718. var pi2 = Math.PI * 2;
  22719. var paths = new Array();
  22720. var invertUV = options.invertUV || false;
  22721. var i = 0;
  22722. var p = 0;
  22723. var step = pi2 / tessellation * arc;
  22724. var rotated;
  22725. var path = new Array();
  22726. ;
  22727. for (i = 0; i <= tessellation; i++) {
  22728. var path = [];
  22729. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22730. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22731. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22732. }
  22733. for (p = 0; p < shape.length; p++) {
  22734. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22735. path.push(rotated);
  22736. }
  22737. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22738. 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));
  22739. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22740. }
  22741. paths.push(path);
  22742. }
  22743. // lathe ribbon
  22744. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22745. return lathe;
  22746. };
  22747. /**
  22748. * Creates a plane mesh.
  22749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22750. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22751. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22752. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22753. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22754. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22756. */
  22757. MeshBuilder.CreatePlane = function (name, options, scene) {
  22758. var plane = new BABYLON.Mesh(name, scene);
  22759. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22760. plane.sideOrientation = options.sideOrientation;
  22761. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22762. vertexData.applyToMesh(plane, options.updatable);
  22763. if (options.sourcePlane) {
  22764. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22765. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22766. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22767. plane.rotate(vectorProduct, product);
  22768. }
  22769. return plane;
  22770. };
  22771. /**
  22772. * Creates a ground mesh.
  22773. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22774. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22775. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22777. */
  22778. MeshBuilder.CreateGround = function (name, options, scene) {
  22779. var ground = new BABYLON.GroundMesh(name, scene);
  22780. ground._setReady(false);
  22781. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22782. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22783. ground._width = options.width || 1;
  22784. ground._height = options.height || 1;
  22785. ground._maxX = ground._width / 2;
  22786. ground._maxZ = ground._height / 2;
  22787. ground._minX = -ground._maxX;
  22788. ground._minZ = -ground._maxZ;
  22789. var vertexData = BABYLON.VertexData.CreateGround(options);
  22790. vertexData.applyToMesh(ground, options.updatable);
  22791. ground._setReady(true);
  22792. return ground;
  22793. };
  22794. /**
  22795. * Creates a tiled ground mesh.
  22796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22797. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22798. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22799. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22800. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22801. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22802. * numbers of subdivisions on the ground width and height of each tile.
  22803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22804. */
  22805. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22806. var tiledGround = new BABYLON.Mesh(name, scene);
  22807. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22808. vertexData.applyToMesh(tiledGround, options.updatable);
  22809. return tiledGround;
  22810. };
  22811. /**
  22812. * Creates a ground mesh from a height map.
  22813. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22815. * The parameter `url` sets the URL of the height map image resource.
  22816. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22817. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22818. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22819. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22820. * 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).
  22821. * This function is passed the newly built mesh :
  22822. * ```javascript
  22823. * function(mesh) { // do things
  22824. * return; }
  22825. * ```
  22826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22827. */
  22828. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22829. var width = options.width || 10.0;
  22830. var height = options.height || 10.0;
  22831. var subdivisions = options.subdivisions || 1 | 0;
  22832. var minHeight = options.minHeight || 0.0;
  22833. var maxHeight = options.maxHeight || 10.0;
  22834. var updatable = options.updatable;
  22835. var onReady = options.onReady;
  22836. var ground = new BABYLON.GroundMesh(name, scene);
  22837. ground._subdivisionsX = subdivisions;
  22838. ground._subdivisionsY = subdivisions;
  22839. ground._width = width;
  22840. ground._height = height;
  22841. ground._maxX = ground._width / 2.0;
  22842. ground._maxZ = ground._height / 2.0;
  22843. ground._minX = -ground._maxX;
  22844. ground._minZ = -ground._maxZ;
  22845. ground._setReady(false);
  22846. var onload = function (img) {
  22847. // Getting height map data
  22848. var canvas = document.createElement("canvas");
  22849. var context = canvas.getContext("2d");
  22850. var bufferWidth = img.width;
  22851. var bufferHeight = img.height;
  22852. canvas.width = bufferWidth;
  22853. canvas.height = bufferHeight;
  22854. context.drawImage(img, 0, 0);
  22855. // Create VertexData from map data
  22856. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22857. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22858. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22859. width: width, height: height,
  22860. subdivisions: subdivisions,
  22861. minHeight: minHeight, maxHeight: maxHeight,
  22862. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22863. });
  22864. vertexData.applyToMesh(ground, updatable);
  22865. ground._setReady(true);
  22866. //execute ready callback, if set
  22867. if (onReady) {
  22868. onReady(ground);
  22869. }
  22870. };
  22871. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22872. return ground;
  22873. };
  22874. /**
  22875. * Creates a tube mesh.
  22876. * 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.
  22877. *
  22878. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22879. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22880. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22881. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22882. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22883. * 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.
  22884. * It must return a radius value (positive float) :
  22885. * ```javascript
  22886. * var radiusFunction = function(i, distance) {
  22887. * // do things
  22888. * return radius; }
  22889. * ```
  22890. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22891. * 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
  22892. * 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
  22893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22894. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22895. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22897. */
  22898. MeshBuilder.CreateTube = function (name, options, scene) {
  22899. var path = options.path;
  22900. var radius = options.radius || 1.0;
  22901. var tessellation = options.tessellation || 64 | 0;
  22902. var radiusFunction = options.radiusFunction;
  22903. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22904. var invertUV = options.invertUV || false;
  22905. var updatable = options.updatable;
  22906. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22907. var instance = options.instance;
  22908. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22909. // tube geometry
  22910. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22911. var tangents = path3D.getTangents();
  22912. var normals = path3D.getNormals();
  22913. var distances = path3D.getDistances();
  22914. var pi2 = Math.PI * 2;
  22915. var step = pi2 / tessellation * arc;
  22916. var returnRadius = function () { return radius; };
  22917. var radiusFunctionFinal = radiusFunction || returnRadius;
  22918. var circlePath;
  22919. var rad;
  22920. var normal;
  22921. var rotated;
  22922. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22923. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22924. for (var i = 0; i < path.length; i++) {
  22925. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22926. circlePath = Array(); // current circle array
  22927. normal = normals[i]; // current normal
  22928. for (var t = 0; t < tessellation; t++) {
  22929. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22930. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22931. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22932. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22933. circlePath[t] = rotated;
  22934. }
  22935. circlePaths[index] = circlePath;
  22936. index++;
  22937. }
  22938. // cap
  22939. var capPath = function (nbPoints, pathIndex) {
  22940. var pointCap = Array();
  22941. for (var i = 0; i < nbPoints; i++) {
  22942. pointCap.push(path[pathIndex]);
  22943. }
  22944. return pointCap;
  22945. };
  22946. switch (cap) {
  22947. case BABYLON.Mesh.NO_CAP:
  22948. break;
  22949. case BABYLON.Mesh.CAP_START:
  22950. circlePaths[0] = capPath(tessellation, 0);
  22951. circlePaths[1] = circlePaths[2].slice(0);
  22952. break;
  22953. case BABYLON.Mesh.CAP_END:
  22954. circlePaths[index] = circlePaths[index - 1].slice(0);
  22955. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22956. break;
  22957. case BABYLON.Mesh.CAP_ALL:
  22958. circlePaths[0] = capPath(tessellation, 0);
  22959. circlePaths[1] = circlePaths[2].slice(0);
  22960. circlePaths[index] = circlePaths[index - 1].slice(0);
  22961. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22962. break;
  22963. default:
  22964. break;
  22965. }
  22966. return circlePaths;
  22967. };
  22968. var path3D;
  22969. var pathArray;
  22970. if (instance) {
  22971. var arc = options.arc || instance.arc;
  22972. path3D = (instance.path3D).update(path);
  22973. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22974. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22975. instance.path3D = path3D;
  22976. instance.pathArray = pathArray;
  22977. instance.arc = arc;
  22978. return instance;
  22979. }
  22980. // tube creation
  22981. path3D = new BABYLON.Path3D(path);
  22982. var newPathArray = new Array();
  22983. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22984. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22985. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22986. tube.pathArray = pathArray;
  22987. tube.path3D = path3D;
  22988. tube.tessellation = tessellation;
  22989. tube.cap = cap;
  22990. tube.arc = options.arc;
  22991. return tube;
  22992. };
  22993. /**
  22994. * Creates a polyhedron mesh.
  22995. *
  22996. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22997. * 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
  22998. * to choose the wanted type.
  22999. * The parameter `size` (positive float, default 1) sets the polygon size.
  23000. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23001. * 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`.
  23002. * 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
  23003. * 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)`).
  23004. * 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
  23005. * 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.
  23006. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23007. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23009. */
  23010. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23011. var polyhedron = new BABYLON.Mesh(name, scene);
  23012. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  23013. polyhedron.sideOrientation = options.sideOrientation;
  23014. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23015. vertexData.applyToMesh(polyhedron, options.updatable);
  23016. return polyhedron;
  23017. };
  23018. /**
  23019. * Creates a decal mesh.
  23020. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23021. * 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.
  23022. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23023. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23024. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23025. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23026. */
  23027. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23028. var indices = sourceMesh.getIndices();
  23029. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23030. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23031. var position = options.position || BABYLON.Vector3.Zero();
  23032. var normal = options.normal || BABYLON.Vector3.Up();
  23033. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23034. var angle = options.angle || 0;
  23035. // Getting correct rotation
  23036. if (!normal) {
  23037. var target = new BABYLON.Vector3(0, 0, 1);
  23038. var camera = sourceMesh.getScene().activeCamera;
  23039. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23040. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23041. }
  23042. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23043. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23044. var pitch = Math.atan2(normal.y, len);
  23045. // Matrix
  23046. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23047. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23048. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23049. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23050. var vertexData = new BABYLON.VertexData();
  23051. vertexData.indices = [];
  23052. vertexData.positions = [];
  23053. vertexData.normals = [];
  23054. vertexData.uvs = [];
  23055. var currentVertexDataIndex = 0;
  23056. var extractDecalVector3 = function (indexId) {
  23057. var vertexId = indices[indexId];
  23058. var result = new BABYLON.PositionNormalVertex();
  23059. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23060. // Send vector to decal local world
  23061. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23062. // Get normal
  23063. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23064. return result;
  23065. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23066. var clip = function (vertices, axis) {
  23067. if (vertices.length === 0) {
  23068. return vertices;
  23069. }
  23070. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23071. var clipVertices = function (v0, v1) {
  23072. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23073. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23074. };
  23075. var result = new Array();
  23076. for (var index = 0; index < vertices.length; index += 3) {
  23077. var v1Out;
  23078. var v2Out;
  23079. var v3Out;
  23080. var total = 0;
  23081. var nV1, nV2, nV3, nV4;
  23082. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23083. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23084. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23085. v1Out = d1 > 0;
  23086. v2Out = d2 > 0;
  23087. v3Out = d3 > 0;
  23088. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23089. switch (total) {
  23090. case 0:
  23091. result.push(vertices[index]);
  23092. result.push(vertices[index + 1]);
  23093. result.push(vertices[index + 2]);
  23094. break;
  23095. case 1:
  23096. if (v1Out) {
  23097. nV1 = vertices[index + 1];
  23098. nV2 = vertices[index + 2];
  23099. nV3 = clipVertices(vertices[index], nV1);
  23100. nV4 = clipVertices(vertices[index], nV2);
  23101. }
  23102. if (v2Out) {
  23103. nV1 = vertices[index];
  23104. nV2 = vertices[index + 2];
  23105. nV3 = clipVertices(vertices[index + 1], nV1);
  23106. nV4 = clipVertices(vertices[index + 1], nV2);
  23107. result.push(nV3);
  23108. result.push(nV2.clone());
  23109. result.push(nV1.clone());
  23110. result.push(nV2.clone());
  23111. result.push(nV3.clone());
  23112. result.push(nV4);
  23113. break;
  23114. }
  23115. if (v3Out) {
  23116. nV1 = vertices[index];
  23117. nV2 = vertices[index + 1];
  23118. nV3 = clipVertices(vertices[index + 2], nV1);
  23119. nV4 = clipVertices(vertices[index + 2], nV2);
  23120. }
  23121. result.push(nV1.clone());
  23122. result.push(nV2.clone());
  23123. result.push(nV3);
  23124. result.push(nV4);
  23125. result.push(nV3.clone());
  23126. result.push(nV2.clone());
  23127. break;
  23128. case 2:
  23129. if (!v1Out) {
  23130. nV1 = vertices[index].clone();
  23131. nV2 = clipVertices(nV1, vertices[index + 1]);
  23132. nV3 = clipVertices(nV1, vertices[index + 2]);
  23133. result.push(nV1);
  23134. result.push(nV2);
  23135. result.push(nV3);
  23136. }
  23137. if (!v2Out) {
  23138. nV1 = vertices[index + 1].clone();
  23139. nV2 = clipVertices(nV1, vertices[index + 2]);
  23140. nV3 = clipVertices(nV1, vertices[index]);
  23141. result.push(nV1);
  23142. result.push(nV2);
  23143. result.push(nV3);
  23144. }
  23145. if (!v3Out) {
  23146. nV1 = vertices[index + 2].clone();
  23147. nV2 = clipVertices(nV1, vertices[index]);
  23148. nV3 = clipVertices(nV1, vertices[index + 1]);
  23149. result.push(nV1);
  23150. result.push(nV2);
  23151. result.push(nV3);
  23152. }
  23153. break;
  23154. case 3:
  23155. break;
  23156. }
  23157. }
  23158. return result;
  23159. };
  23160. for (var index = 0; index < indices.length; index += 3) {
  23161. var faceVertices = new Array();
  23162. faceVertices.push(extractDecalVector3(index));
  23163. faceVertices.push(extractDecalVector3(index + 1));
  23164. faceVertices.push(extractDecalVector3(index + 2));
  23165. // Clip
  23166. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23167. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23168. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23169. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23170. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23171. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23172. if (faceVertices.length === 0) {
  23173. continue;
  23174. }
  23175. // Add UVs and get back to world
  23176. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23177. var vertex = faceVertices[vIndex];
  23178. //TODO check for Int32Array
  23179. vertexData.indices.push(currentVertexDataIndex);
  23180. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23181. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23182. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23183. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23184. currentVertexDataIndex++;
  23185. }
  23186. }
  23187. // Return mesh
  23188. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23189. vertexData.applyToMesh(decal);
  23190. decal.position = position.clone();
  23191. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23192. return decal;
  23193. };
  23194. // Privates
  23195. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23196. // extrusion geometry
  23197. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23198. var tangents = path3D.getTangents();
  23199. var normals = path3D.getNormals();
  23200. var binormals = path3D.getBinormals();
  23201. var distances = path3D.getDistances();
  23202. var angle = 0;
  23203. var returnScale = function () { return scale; };
  23204. var returnRotation = function () { return rotation; };
  23205. var rotate = custom ? rotateFunction : returnRotation;
  23206. var scl = custom ? scaleFunction : returnScale;
  23207. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23208. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23209. for (var i = 0; i < curve.length; i++) {
  23210. var shapePath = new Array();
  23211. var angleStep = rotate(i, distances[i]);
  23212. var scaleRatio = scl(i, distances[i]);
  23213. for (var p = 0; p < shape.length; p++) {
  23214. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23215. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23216. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23217. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23218. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23219. shapePath[p] = rotated;
  23220. }
  23221. shapePaths[index] = shapePath;
  23222. angle += angleStep;
  23223. index++;
  23224. }
  23225. // cap
  23226. var capPath = function (shapePath) {
  23227. var pointCap = Array();
  23228. var barycenter = BABYLON.Vector3.Zero();
  23229. var i;
  23230. for (i = 0; i < shapePath.length; i++) {
  23231. barycenter.addInPlace(shapePath[i]);
  23232. }
  23233. barycenter.scaleInPlace(1 / shapePath.length);
  23234. for (i = 0; i < shapePath.length; i++) {
  23235. pointCap.push(barycenter);
  23236. }
  23237. return pointCap;
  23238. };
  23239. switch (cap) {
  23240. case BABYLON.Mesh.NO_CAP:
  23241. break;
  23242. case BABYLON.Mesh.CAP_START:
  23243. shapePaths[0] = capPath(shapePaths[2]);
  23244. shapePaths[1] = shapePaths[2].slice(0);
  23245. break;
  23246. case BABYLON.Mesh.CAP_END:
  23247. shapePaths[index] = shapePaths[index - 1];
  23248. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23249. break;
  23250. case BABYLON.Mesh.CAP_ALL:
  23251. shapePaths[0] = capPath(shapePaths[2]);
  23252. shapePaths[1] = shapePaths[2].slice(0);
  23253. shapePaths[index] = shapePaths[index - 1];
  23254. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23255. break;
  23256. default:
  23257. break;
  23258. }
  23259. return shapePaths;
  23260. };
  23261. var path3D;
  23262. var pathArray;
  23263. if (instance) {
  23264. path3D = (instance.path3D).update(curve);
  23265. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23266. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23267. return instance;
  23268. }
  23269. // extruded shape creation
  23270. path3D = new BABYLON.Path3D(curve);
  23271. var newShapePaths = new Array();
  23272. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23273. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23274. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23275. extrudedGeneric.pathArray = pathArray;
  23276. extrudedGeneric.path3D = path3D;
  23277. extrudedGeneric.cap = cap;
  23278. return extrudedGeneric;
  23279. };
  23280. return MeshBuilder;
  23281. }());
  23282. BABYLON.MeshBuilder = MeshBuilder;
  23283. })(BABYLON || (BABYLON = {}));
  23284. //# sourceMappingURL=babylon.meshBuilder.js.map
  23285. var BABYLON;
  23286. (function (BABYLON) {
  23287. var BaseTexture = (function () {
  23288. function BaseTexture(scene) {
  23289. this.hasAlpha = false;
  23290. this.getAlphaFromRGB = false;
  23291. this.level = 1;
  23292. this.coordinatesIndex = 0;
  23293. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23294. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23295. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23296. this.anisotropicFilteringLevel = 4;
  23297. this.isCube = false;
  23298. this.isRenderTarget = false;
  23299. this.animations = new Array();
  23300. /**
  23301. * An event triggered when the texture is disposed.
  23302. * @type {BABYLON.Observable}
  23303. */
  23304. this.onDisposeObservable = new BABYLON.Observable();
  23305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23306. this._scene = scene;
  23307. this._scene.textures.push(this);
  23308. this._uid = null;
  23309. }
  23310. Object.defineProperty(BaseTexture.prototype, "uid", {
  23311. get: function () {
  23312. if (!this._uid) {
  23313. this._uid = BABYLON.Tools.RandomId();
  23314. }
  23315. return this._uid;
  23316. },
  23317. enumerable: true,
  23318. configurable: true
  23319. });
  23320. BaseTexture.prototype.toString = function () {
  23321. return this.name;
  23322. };
  23323. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23324. set: function (callback) {
  23325. if (this._onDisposeObserver) {
  23326. this.onDisposeObservable.remove(this._onDisposeObserver);
  23327. }
  23328. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23329. },
  23330. enumerable: true,
  23331. configurable: true
  23332. });
  23333. BaseTexture.prototype.getScene = function () {
  23334. return this._scene;
  23335. };
  23336. BaseTexture.prototype.getTextureMatrix = function () {
  23337. return null;
  23338. };
  23339. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23340. return null;
  23341. };
  23342. BaseTexture.prototype.getInternalTexture = function () {
  23343. return this._texture;
  23344. };
  23345. BaseTexture.prototype.isReady = function () {
  23346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23347. return true;
  23348. }
  23349. if (this._texture) {
  23350. return this._texture.isReady;
  23351. }
  23352. return false;
  23353. };
  23354. BaseTexture.prototype.getSize = function () {
  23355. if (this._texture._width) {
  23356. return new BABYLON.Size(this._texture._width, this._texture._height);
  23357. }
  23358. if (this._texture._size) {
  23359. return new BABYLON.Size(this._texture._size, this._texture._size);
  23360. }
  23361. return BABYLON.Size.Zero();
  23362. };
  23363. BaseTexture.prototype.getBaseSize = function () {
  23364. if (!this.isReady() || !this._texture)
  23365. return BABYLON.Size.Zero();
  23366. if (this._texture._size) {
  23367. return new BABYLON.Size(this._texture._size, this._texture._size);
  23368. }
  23369. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23370. };
  23371. BaseTexture.prototype.scale = function (ratio) {
  23372. };
  23373. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23374. get: function () {
  23375. return false;
  23376. },
  23377. enumerable: true,
  23378. configurable: true
  23379. });
  23380. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23381. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23382. for (var index = 0; index < texturesCache.length; index++) {
  23383. var texturesCacheEntry = texturesCache[index];
  23384. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23385. texturesCache.splice(index, 1);
  23386. return;
  23387. }
  23388. }
  23389. };
  23390. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23391. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23392. for (var index = 0; index < texturesCache.length; index++) {
  23393. var texturesCacheEntry = texturesCache[index];
  23394. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23395. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23396. texturesCacheEntry.references++;
  23397. return texturesCacheEntry;
  23398. }
  23399. }
  23400. }
  23401. return null;
  23402. };
  23403. BaseTexture.prototype.delayLoad = function () {
  23404. };
  23405. BaseTexture.prototype.clone = function () {
  23406. return null;
  23407. };
  23408. BaseTexture.prototype.releaseInternalTexture = function () {
  23409. if (this._texture) {
  23410. this._scene.getEngine().releaseInternalTexture(this._texture);
  23411. delete this._texture;
  23412. }
  23413. };
  23414. BaseTexture.prototype.dispose = function () {
  23415. // Animations
  23416. this.getScene().stopAnimation(this);
  23417. // Remove from scene
  23418. var index = this._scene.textures.indexOf(this);
  23419. if (index >= 0) {
  23420. this._scene.textures.splice(index, 1);
  23421. }
  23422. if (this._texture === undefined) {
  23423. return;
  23424. }
  23425. // Release
  23426. this.releaseInternalTexture();
  23427. // Callback
  23428. this.onDisposeObservable.notifyObservers(this);
  23429. this.onDisposeObservable.clear();
  23430. };
  23431. BaseTexture.prototype.serialize = function () {
  23432. if (!this.name) {
  23433. return null;
  23434. }
  23435. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23436. // Animations
  23437. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23438. return serializationObject;
  23439. };
  23440. return BaseTexture;
  23441. }());
  23442. __decorate([
  23443. BABYLON.serialize()
  23444. ], BaseTexture.prototype, "name", void 0);
  23445. __decorate([
  23446. BABYLON.serialize()
  23447. ], BaseTexture.prototype, "hasAlpha", void 0);
  23448. __decorate([
  23449. BABYLON.serialize()
  23450. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23451. __decorate([
  23452. BABYLON.serialize()
  23453. ], BaseTexture.prototype, "level", void 0);
  23454. __decorate([
  23455. BABYLON.serialize()
  23456. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23457. __decorate([
  23458. BABYLON.serialize()
  23459. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23460. __decorate([
  23461. BABYLON.serialize()
  23462. ], BaseTexture.prototype, "wrapU", void 0);
  23463. __decorate([
  23464. BABYLON.serialize()
  23465. ], BaseTexture.prototype, "wrapV", void 0);
  23466. __decorate([
  23467. BABYLON.serialize()
  23468. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23469. __decorate([
  23470. BABYLON.serialize()
  23471. ], BaseTexture.prototype, "isCube", void 0);
  23472. __decorate([
  23473. BABYLON.serialize()
  23474. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23475. BABYLON.BaseTexture = BaseTexture;
  23476. })(BABYLON || (BABYLON = {}));
  23477. //# sourceMappingURL=babylon.baseTexture.js.map
  23478. var BABYLON;
  23479. (function (BABYLON) {
  23480. var Texture = (function (_super) {
  23481. __extends(Texture, _super);
  23482. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23483. if (noMipmap === void 0) { noMipmap = false; }
  23484. if (invertY === void 0) { invertY = true; }
  23485. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23486. if (onLoad === void 0) { onLoad = null; }
  23487. if (onError === void 0) { onError = null; }
  23488. if (buffer === void 0) { buffer = null; }
  23489. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23490. var _this = _super.call(this, scene) || this;
  23491. _this.uOffset = 0;
  23492. _this.vOffset = 0;
  23493. _this.uScale = 1.0;
  23494. _this.vScale = 1.0;
  23495. _this.uAng = 0;
  23496. _this.vAng = 0;
  23497. _this.wAng = 0;
  23498. _this.name = url;
  23499. _this.url = url;
  23500. _this._noMipmap = noMipmap;
  23501. _this._invertY = invertY;
  23502. _this._samplingMode = samplingMode;
  23503. _this._buffer = buffer;
  23504. _this._deleteBuffer = deleteBuffer;
  23505. if (!url) {
  23506. return _this;
  23507. }
  23508. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  23509. var load = function () {
  23510. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23511. _this.onLoadObservable.notifyObservers(true);
  23512. }
  23513. if (onLoad) {
  23514. onLoad();
  23515. }
  23516. };
  23517. if (!_this._texture) {
  23518. if (!scene.useDelayedTextureLoading) {
  23519. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  23520. if (deleteBuffer) {
  23521. delete _this._buffer;
  23522. }
  23523. }
  23524. else {
  23525. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23526. _this._delayedOnLoad = load;
  23527. _this._delayedOnError = onError;
  23528. }
  23529. }
  23530. else {
  23531. if (_this._texture.isReady) {
  23532. BABYLON.Tools.SetImmediate(function () { return load(); });
  23533. }
  23534. else {
  23535. _this._texture.onLoadedCallbacks.push(load);
  23536. }
  23537. }
  23538. return _this;
  23539. }
  23540. Object.defineProperty(Texture.prototype, "noMipmap", {
  23541. get: function () {
  23542. return this._noMipmap;
  23543. },
  23544. enumerable: true,
  23545. configurable: true
  23546. });
  23547. Texture.prototype.delayLoad = function () {
  23548. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23549. return;
  23550. }
  23551. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23552. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23553. if (!this._texture) {
  23554. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23555. if (this._deleteBuffer) {
  23556. delete this._buffer;
  23557. }
  23558. }
  23559. };
  23560. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23561. if (!this._texture) {
  23562. return;
  23563. }
  23564. this._samplingMode = samplingMode;
  23565. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23566. };
  23567. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23568. x *= this.uScale;
  23569. y *= this.vScale;
  23570. x -= 0.5 * this.uScale;
  23571. y -= 0.5 * this.vScale;
  23572. z -= 0.5;
  23573. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23574. t.x += 0.5 * this.uScale + this.uOffset;
  23575. t.y += 0.5 * this.vScale + this.vOffset;
  23576. t.z += 0.5;
  23577. };
  23578. Texture.prototype.getTextureMatrix = function () {
  23579. if (this.uOffset === this._cachedUOffset &&
  23580. this.vOffset === this._cachedVOffset &&
  23581. this.uScale === this._cachedUScale &&
  23582. this.vScale === this._cachedVScale &&
  23583. this.uAng === this._cachedUAng &&
  23584. this.vAng === this._cachedVAng &&
  23585. this.wAng === this._cachedWAng) {
  23586. return this._cachedTextureMatrix;
  23587. }
  23588. this._cachedUOffset = this.uOffset;
  23589. this._cachedVOffset = this.vOffset;
  23590. this._cachedUScale = this.uScale;
  23591. this._cachedVScale = this.vScale;
  23592. this._cachedUAng = this.uAng;
  23593. this._cachedVAng = this.vAng;
  23594. this._cachedWAng = this.wAng;
  23595. if (!this._cachedTextureMatrix) {
  23596. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23597. this._rowGenerationMatrix = new BABYLON.Matrix();
  23598. this._t0 = BABYLON.Vector3.Zero();
  23599. this._t1 = BABYLON.Vector3.Zero();
  23600. this._t2 = BABYLON.Vector3.Zero();
  23601. }
  23602. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23603. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23604. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23605. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23606. this._t1.subtractInPlace(this._t0);
  23607. this._t2.subtractInPlace(this._t0);
  23608. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23609. this._cachedTextureMatrix.m[0] = this._t1.x;
  23610. this._cachedTextureMatrix.m[1] = this._t1.y;
  23611. this._cachedTextureMatrix.m[2] = this._t1.z;
  23612. this._cachedTextureMatrix.m[4] = this._t2.x;
  23613. this._cachedTextureMatrix.m[5] = this._t2.y;
  23614. this._cachedTextureMatrix.m[6] = this._t2.z;
  23615. this._cachedTextureMatrix.m[8] = this._t0.x;
  23616. this._cachedTextureMatrix.m[9] = this._t0.y;
  23617. this._cachedTextureMatrix.m[10] = this._t0.z;
  23618. return this._cachedTextureMatrix;
  23619. };
  23620. Texture.prototype.getReflectionTextureMatrix = function () {
  23621. if (this.uOffset === this._cachedUOffset &&
  23622. this.vOffset === this._cachedVOffset &&
  23623. this.uScale === this._cachedUScale &&
  23624. this.vScale === this._cachedVScale &&
  23625. this.coordinatesMode === this._cachedCoordinatesMode) {
  23626. return this._cachedTextureMatrix;
  23627. }
  23628. if (!this._cachedTextureMatrix) {
  23629. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23630. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23631. }
  23632. this._cachedCoordinatesMode = this.coordinatesMode;
  23633. switch (this.coordinatesMode) {
  23634. case Texture.PLANAR_MODE:
  23635. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23636. this._cachedTextureMatrix[0] = this.uScale;
  23637. this._cachedTextureMatrix[5] = this.vScale;
  23638. this._cachedTextureMatrix[12] = this.uOffset;
  23639. this._cachedTextureMatrix[13] = this.vOffset;
  23640. break;
  23641. case Texture.PROJECTION_MODE:
  23642. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23643. this._projectionModeMatrix.m[0] = 0.5;
  23644. this._projectionModeMatrix.m[5] = -0.5;
  23645. this._projectionModeMatrix.m[10] = 0.0;
  23646. this._projectionModeMatrix.m[12] = 0.5;
  23647. this._projectionModeMatrix.m[13] = 0.5;
  23648. this._projectionModeMatrix.m[14] = 1.0;
  23649. this._projectionModeMatrix.m[15] = 1.0;
  23650. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23651. break;
  23652. default:
  23653. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23654. break;
  23655. }
  23656. return this._cachedTextureMatrix;
  23657. };
  23658. Texture.prototype.clone = function () {
  23659. var _this = this;
  23660. return BABYLON.SerializationHelper.Clone(function () {
  23661. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23662. }, this);
  23663. };
  23664. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23665. get: function () {
  23666. if (!this._onLoadObservarble) {
  23667. this._onLoadObservarble = new BABYLON.Observable();
  23668. }
  23669. return this._onLoadObservarble;
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. // Statics
  23675. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23676. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23677. if (onLoad === void 0) { onLoad = null; }
  23678. if (onError === void 0) { onError = null; }
  23679. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23680. };
  23681. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23682. if (parsedTexture.customType) {
  23683. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23684. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23685. }
  23686. if (parsedTexture.isCube) {
  23687. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23688. }
  23689. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23690. return null;
  23691. }
  23692. var texture = BABYLON.SerializationHelper.Parse(function () {
  23693. if (parsedTexture.mirrorPlane) {
  23694. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23695. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23696. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23697. return mirrorTexture;
  23698. }
  23699. else if (parsedTexture.isRenderTarget) {
  23700. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23701. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23702. return renderTargetTexture;
  23703. }
  23704. else {
  23705. var texture;
  23706. if (parsedTexture.base64String) {
  23707. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23708. }
  23709. else {
  23710. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23711. }
  23712. return texture;
  23713. }
  23714. }, parsedTexture, scene);
  23715. // Animations
  23716. if (parsedTexture.animations) {
  23717. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23718. var parsedAnimation = parsedTexture.animations[animationIndex];
  23719. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23720. }
  23721. }
  23722. return texture;
  23723. };
  23724. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23725. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23726. if (noMipmap === void 0) { noMipmap = false; }
  23727. if (invertY === void 0) { invertY = true; }
  23728. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23729. if (onLoad === void 0) { onLoad = null; }
  23730. if (onError === void 0) { onError = null; }
  23731. if (name.substr(0, 5) !== "data:") {
  23732. name = "data:" + name;
  23733. }
  23734. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23735. };
  23736. return Texture;
  23737. }(BABYLON.BaseTexture));
  23738. // Constants
  23739. Texture.NEAREST_SAMPLINGMODE = 1;
  23740. Texture.BILINEAR_SAMPLINGMODE = 2;
  23741. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23742. Texture.EXPLICIT_MODE = 0;
  23743. Texture.SPHERICAL_MODE = 1;
  23744. Texture.PLANAR_MODE = 2;
  23745. Texture.CUBIC_MODE = 3;
  23746. Texture.PROJECTION_MODE = 4;
  23747. Texture.SKYBOX_MODE = 5;
  23748. Texture.INVCUBIC_MODE = 6;
  23749. Texture.EQUIRECTANGULAR_MODE = 7;
  23750. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23751. Texture.CLAMP_ADDRESSMODE = 0;
  23752. Texture.WRAP_ADDRESSMODE = 1;
  23753. Texture.MIRROR_ADDRESSMODE = 2;
  23754. __decorate([
  23755. BABYLON.serialize()
  23756. ], Texture.prototype, "url", void 0);
  23757. __decorate([
  23758. BABYLON.serialize()
  23759. ], Texture.prototype, "uOffset", void 0);
  23760. __decorate([
  23761. BABYLON.serialize()
  23762. ], Texture.prototype, "vOffset", void 0);
  23763. __decorate([
  23764. BABYLON.serialize()
  23765. ], Texture.prototype, "uScale", void 0);
  23766. __decorate([
  23767. BABYLON.serialize()
  23768. ], Texture.prototype, "vScale", void 0);
  23769. __decorate([
  23770. BABYLON.serialize()
  23771. ], Texture.prototype, "uAng", void 0);
  23772. __decorate([
  23773. BABYLON.serialize()
  23774. ], Texture.prototype, "vAng", void 0);
  23775. __decorate([
  23776. BABYLON.serialize()
  23777. ], Texture.prototype, "wAng", void 0);
  23778. BABYLON.Texture = Texture;
  23779. })(BABYLON || (BABYLON = {}));
  23780. //# sourceMappingURL=babylon.texture.js.map
  23781. var BABYLON;
  23782. (function (BABYLON) {
  23783. var CubeTexture = (function (_super) {
  23784. __extends(CubeTexture, _super);
  23785. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23786. if (onLoad === void 0) { onLoad = null; }
  23787. if (onError === void 0) { onError = null; }
  23788. var _this = _super.call(this, scene) || this;
  23789. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23790. _this.name = rootUrl;
  23791. _this.url = rootUrl;
  23792. _this._noMipmap = noMipmap;
  23793. _this.hasAlpha = false;
  23794. if (!rootUrl && !files) {
  23795. return _this;
  23796. }
  23797. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  23798. if (!files) {
  23799. if (!extensions) {
  23800. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23801. }
  23802. files = [];
  23803. for (var index = 0; index < extensions.length; index++) {
  23804. files.push(rootUrl + extensions[index]);
  23805. }
  23806. _this._extensions = extensions;
  23807. }
  23808. _this._files = files;
  23809. if (!_this._texture) {
  23810. if (!scene.useDelayedTextureLoading) {
  23811. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23812. }
  23813. else {
  23814. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23815. }
  23816. }
  23817. else if (onLoad) {
  23818. if (_this._texture.isReady) {
  23819. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23820. }
  23821. else {
  23822. _this._texture.onLoadedCallbacks.push(onLoad);
  23823. }
  23824. }
  23825. _this.isCube = true;
  23826. _this._textureMatrix = BABYLON.Matrix.Identity();
  23827. return _this;
  23828. }
  23829. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23830. return new CubeTexture("", scene, null, noMipmap, files);
  23831. };
  23832. // Methods
  23833. CubeTexture.prototype.delayLoad = function () {
  23834. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23835. return;
  23836. }
  23837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23838. this._texture = this._getFromCache(this.url, this._noMipmap);
  23839. if (!this._texture) {
  23840. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23841. }
  23842. };
  23843. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23844. return this._textureMatrix;
  23845. };
  23846. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23847. var texture = BABYLON.SerializationHelper.Parse(function () {
  23848. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23849. }, parsedTexture, scene);
  23850. // Animations
  23851. if (parsedTexture.animations) {
  23852. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23853. var parsedAnimation = parsedTexture.animations[animationIndex];
  23854. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23855. }
  23856. }
  23857. return texture;
  23858. };
  23859. CubeTexture.prototype.clone = function () {
  23860. var _this = this;
  23861. return BABYLON.SerializationHelper.Clone(function () {
  23862. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23863. }, this);
  23864. };
  23865. return CubeTexture;
  23866. }(BABYLON.BaseTexture));
  23867. BABYLON.CubeTexture = CubeTexture;
  23868. })(BABYLON || (BABYLON = {}));
  23869. //# sourceMappingURL=babylon.cubeTexture.js.map
  23870. var BABYLON;
  23871. (function (BABYLON) {
  23872. var RenderTargetTexture = (function (_super) {
  23873. __extends(RenderTargetTexture, _super);
  23874. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23875. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23876. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23877. if (isCube === void 0) { isCube = false; }
  23878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23879. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23880. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23881. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  23882. _this.isCube = isCube;
  23883. /**
  23884. * Use this list to define the list of mesh you want to render.
  23885. */
  23886. _this.renderList = new Array();
  23887. _this.renderParticles = true;
  23888. _this.renderSprites = false;
  23889. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23890. // Events
  23891. /**
  23892. * An event triggered when the texture is unbind.
  23893. * @type {BABYLON.Observable}
  23894. */
  23895. _this.onAfterUnbindObservable = new BABYLON.Observable();
  23896. /**
  23897. * An event triggered before rendering the texture
  23898. * @type {BABYLON.Observable}
  23899. */
  23900. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23901. /**
  23902. * An event triggered after rendering the texture
  23903. * @type {BABYLON.Observable}
  23904. */
  23905. _this.onAfterRenderObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered after the texture clear
  23908. * @type {BABYLON.Observable}
  23909. */
  23910. _this.onClearObservable = new BABYLON.Observable();
  23911. _this._currentRefreshId = -1;
  23912. _this._refreshRate = 1;
  23913. _this.name = name;
  23914. _this.isRenderTarget = true;
  23915. _this._size = size;
  23916. _this._generateMipMaps = generateMipMaps;
  23917. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23918. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23919. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23920. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23921. }
  23922. if (isCube) {
  23923. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23924. generateMipMaps: generateMipMaps,
  23925. samplingMode: samplingMode,
  23926. generateDepthBuffer: generateDepthBuffer,
  23927. generateStencilBuffer: generateStencilBuffer
  23928. });
  23929. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23930. _this._textureMatrix = BABYLON.Matrix.Identity();
  23931. }
  23932. else {
  23933. _this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23934. generateMipMaps: generateMipMaps,
  23935. type: type,
  23936. samplingMode: samplingMode,
  23937. generateDepthBuffer: generateDepthBuffer,
  23938. generateStencilBuffer: generateStencilBuffer
  23939. });
  23940. }
  23941. // Rendering groups
  23942. _this._renderingManager = new BABYLON.RenderingManager(scene);
  23943. return _this;
  23944. }
  23945. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23946. get: function () {
  23947. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23953. get: function () {
  23954. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23955. },
  23956. enumerable: true,
  23957. configurable: true
  23958. });
  23959. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23960. get: function () {
  23961. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23962. },
  23963. enumerable: true,
  23964. configurable: true
  23965. });
  23966. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23967. set: function (callback) {
  23968. if (this._onAfterUnbindObserver) {
  23969. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23970. }
  23971. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23977. set: function (callback) {
  23978. if (this._onBeforeRenderObserver) {
  23979. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23980. }
  23981. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23987. set: function (callback) {
  23988. if (this._onAfterRenderObserver) {
  23989. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23990. }
  23991. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23992. },
  23993. enumerable: true,
  23994. configurable: true
  23995. });
  23996. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23997. set: function (callback) {
  23998. if (this._onClearObserver) {
  23999. this.onClearObservable.remove(this._onClearObserver);
  24000. }
  24001. this._onClearObserver = this.onClearObservable.add(callback);
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24007. this._currentRefreshId = -1;
  24008. };
  24009. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24010. get: function () {
  24011. return this._refreshRate;
  24012. },
  24013. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24014. set: function (value) {
  24015. this._refreshRate = value;
  24016. this.resetRefreshCounter();
  24017. },
  24018. enumerable: true,
  24019. configurable: true
  24020. });
  24021. RenderTargetTexture.prototype._shouldRender = function () {
  24022. if (this._currentRefreshId === -1) {
  24023. this._currentRefreshId = 1;
  24024. return true;
  24025. }
  24026. if (this.refreshRate === this._currentRefreshId) {
  24027. this._currentRefreshId = 1;
  24028. return true;
  24029. }
  24030. this._currentRefreshId++;
  24031. return false;
  24032. };
  24033. RenderTargetTexture.prototype.isReady = function () {
  24034. if (!this.getScene().renderTargetsEnabled) {
  24035. return false;
  24036. }
  24037. return _super.prototype.isReady.call(this);
  24038. };
  24039. RenderTargetTexture.prototype.getRenderSize = function () {
  24040. return this._size;
  24041. };
  24042. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24043. get: function () {
  24044. return true;
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. RenderTargetTexture.prototype.scale = function (ratio) {
  24050. var newSize = this._size * ratio;
  24051. this.resize(newSize, this._generateMipMaps);
  24052. };
  24053. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24054. if (this.isCube) {
  24055. return this._textureMatrix;
  24056. }
  24057. return _super.prototype.getReflectionTextureMatrix.call(this);
  24058. };
  24059. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  24060. this.releaseInternalTexture();
  24061. if (this.isCube) {
  24062. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  24063. }
  24064. else {
  24065. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24066. }
  24067. };
  24068. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24069. var scene = this.getScene();
  24070. var engine = scene.getEngine();
  24071. if (this.useCameraPostProcesses !== undefined) {
  24072. useCameraPostProcess = this.useCameraPostProcesses;
  24073. }
  24074. if (this._waitingRenderList) {
  24075. this.renderList = [];
  24076. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24077. var id = this._waitingRenderList[index];
  24078. this.renderList.push(scene.getMeshByID(id));
  24079. }
  24080. delete this._waitingRenderList;
  24081. }
  24082. // Is predicate defined?
  24083. if (this.renderListPredicate) {
  24084. this.renderList.splice(0); // Clear previous renderList
  24085. var sceneMeshes = this.getScene().meshes;
  24086. for (var index = 0; index < sceneMeshes.length; index++) {
  24087. var mesh = sceneMeshes[index];
  24088. if (this.renderListPredicate(mesh)) {
  24089. this.renderList.push(mesh);
  24090. }
  24091. }
  24092. }
  24093. if (this.renderList && this.renderList.length === 0) {
  24094. return;
  24095. }
  24096. // Prepare renderingManager
  24097. this._renderingManager.reset();
  24098. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24099. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24100. var sceneRenderId = scene.getRenderId();
  24101. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24102. var mesh = currentRenderList[meshIndex];
  24103. if (mesh) {
  24104. if (!mesh.isReady()) {
  24105. // Reset _currentRefreshId
  24106. this.resetRefreshCounter();
  24107. continue;
  24108. }
  24109. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24110. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24111. mesh._activate(sceneRenderId);
  24112. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24113. var subMesh = mesh.subMeshes[subIndex];
  24114. scene._activeIndices.addCount(subMesh.indexCount, false);
  24115. this._renderingManager.dispatch(subMesh);
  24116. }
  24117. }
  24118. }
  24119. }
  24120. if (this.isCube) {
  24121. for (var face = 0; face < 6; face++) {
  24122. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24123. scene.incrementRenderId();
  24124. scene.resetCachedMaterial();
  24125. }
  24126. }
  24127. else {
  24128. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24129. }
  24130. this.onAfterUnbindObservable.notifyObservers(this);
  24131. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24132. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24133. }
  24134. engine.setViewport(scene.activeCamera.viewport);
  24135. scene.resetCachedMaterial();
  24136. };
  24137. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24138. var scene = this.getScene();
  24139. var engine = scene.getEngine();
  24140. // Bind
  24141. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24142. if (this.isCube) {
  24143. engine.bindFramebuffer(this._texture, faceIndex);
  24144. }
  24145. else {
  24146. engine.bindFramebuffer(this._texture);
  24147. }
  24148. }
  24149. // Set states for projection (this does not change accross faces)
  24150. if (!this.isCube || faceIndex === 0) {
  24151. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24152. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24153. }
  24154. else {
  24155. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24156. }
  24157. if (this.activeCamera) {
  24158. engine.setViewport(this.activeCamera.viewport);
  24159. }
  24160. else {
  24161. engine.setViewport(scene.activeCamera.viewport);
  24162. }
  24163. }
  24164. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24165. // Clear
  24166. if (this.onClearObservable.hasObservers()) {
  24167. this.onClearObservable.notifyObservers(engine);
  24168. }
  24169. else {
  24170. engine.clear(scene.clearColor, true, true, true);
  24171. }
  24172. if (!this._doNotChangeAspectRatio) {
  24173. scene.updateTransformMatrix(true);
  24174. }
  24175. // Render
  24176. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24177. if (useCameraPostProcess) {
  24178. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24179. }
  24180. if (!this._doNotChangeAspectRatio) {
  24181. scene.updateTransformMatrix(true);
  24182. }
  24183. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24184. // Dump ?
  24185. if (dumpForDebug) {
  24186. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24187. }
  24188. // Unbind
  24189. if (!this.isCube || faceIndex === 5) {
  24190. if (this.isCube) {
  24191. if (faceIndex === 5) {
  24192. engine.generateMipMapsForCubemap(this._texture);
  24193. }
  24194. }
  24195. engine.unBindFramebuffer(this._texture, this.isCube);
  24196. }
  24197. };
  24198. /**
  24199. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24200. * This allowed control for front to back rendering or reversly depending of the special needs.
  24201. *
  24202. * @param renderingGroupId The rendering group id corresponding to its index
  24203. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24204. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24205. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24206. */
  24207. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24208. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24209. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24210. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24211. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24212. };
  24213. /**
  24214. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24215. *
  24216. * @param renderingGroupId The rendering group id corresponding to its index
  24217. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24218. */
  24219. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24220. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24221. };
  24222. RenderTargetTexture.prototype.clone = function () {
  24223. var textureSize = this.getSize();
  24224. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24225. // Base texture
  24226. newTexture.hasAlpha = this.hasAlpha;
  24227. newTexture.level = this.level;
  24228. // RenderTarget Texture
  24229. newTexture.coordinatesMode = this.coordinatesMode;
  24230. newTexture.renderList = this.renderList.slice(0);
  24231. return newTexture;
  24232. };
  24233. RenderTargetTexture.prototype.serialize = function () {
  24234. if (!this.name) {
  24235. return null;
  24236. }
  24237. var serializationObject = _super.prototype.serialize.call(this);
  24238. serializationObject.renderTargetSize = this.getRenderSize();
  24239. serializationObject.renderList = [];
  24240. for (var index = 0; index < this.renderList.length; index++) {
  24241. serializationObject.renderList.push(this.renderList[index].id);
  24242. }
  24243. return serializationObject;
  24244. };
  24245. return RenderTargetTexture;
  24246. }(BABYLON.Texture));
  24247. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24248. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24249. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24250. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24251. })(BABYLON || (BABYLON = {}));
  24252. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24253. var BABYLON;
  24254. (function (BABYLON) {
  24255. var ProceduralTexture = (function (_super) {
  24256. __extends(ProceduralTexture, _super);
  24257. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24258. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24259. if (isCube === void 0) { isCube = false; }
  24260. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24261. _this.isCube = isCube;
  24262. _this.isEnabled = true;
  24263. _this._currentRefreshId = -1;
  24264. _this._refreshRate = 1;
  24265. _this._vertexBuffers = {};
  24266. _this._uniforms = new Array();
  24267. _this._samplers = new Array();
  24268. _this._textures = new Array();
  24269. _this._floats = new Array();
  24270. _this._floatsArrays = {};
  24271. _this._colors3 = new Array();
  24272. _this._colors4 = new Array();
  24273. _this._vectors2 = new Array();
  24274. _this._vectors3 = new Array();
  24275. _this._matrices = new Array();
  24276. _this._fallbackTextureUsed = false;
  24277. scene._proceduralTextures.push(_this);
  24278. _this.name = name;
  24279. _this.isRenderTarget = true;
  24280. _this._size = size;
  24281. _this._generateMipMaps = generateMipMaps;
  24282. _this.setFragment(fragment);
  24283. _this._fallbackTexture = fallbackTexture;
  24284. var engine = scene.getEngine();
  24285. if (isCube) {
  24286. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24287. _this.setFloat("face", 0);
  24288. }
  24289. else {
  24290. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24291. }
  24292. // VBO
  24293. var vertices = [];
  24294. vertices.push(1, 1);
  24295. vertices.push(-1, 1);
  24296. vertices.push(-1, -1);
  24297. vertices.push(1, -1);
  24298. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24299. // Indices
  24300. var indices = [];
  24301. indices.push(0);
  24302. indices.push(1);
  24303. indices.push(2);
  24304. indices.push(0);
  24305. indices.push(2);
  24306. indices.push(3);
  24307. _this._indexBuffer = engine.createIndexBuffer(indices);
  24308. return _this;
  24309. }
  24310. ProceduralTexture.prototype.reset = function () {
  24311. if (this._effect === undefined) {
  24312. return;
  24313. }
  24314. var engine = this.getScene().getEngine();
  24315. engine._releaseEffect(this._effect);
  24316. };
  24317. ProceduralTexture.prototype.isReady = function () {
  24318. var _this = this;
  24319. var engine = this.getScene().getEngine();
  24320. var shaders;
  24321. if (!this._fragment) {
  24322. return false;
  24323. }
  24324. if (this._fallbackTextureUsed) {
  24325. return true;
  24326. }
  24327. if (this._fragment.fragmentElement !== undefined) {
  24328. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24329. }
  24330. else {
  24331. shaders = { vertex: "procedural", fragment: this._fragment };
  24332. }
  24333. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24334. _this.releaseInternalTexture();
  24335. if (_this._fallbackTexture) {
  24336. _this._texture = _this._fallbackTexture._texture;
  24337. _this._texture.references++;
  24338. }
  24339. _this._fallbackTextureUsed = true;
  24340. });
  24341. return this._effect.isReady();
  24342. };
  24343. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24344. this._currentRefreshId = -1;
  24345. };
  24346. ProceduralTexture.prototype.setFragment = function (fragment) {
  24347. this._fragment = fragment;
  24348. };
  24349. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24350. get: function () {
  24351. return this._refreshRate;
  24352. },
  24353. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24354. set: function (value) {
  24355. this._refreshRate = value;
  24356. this.resetRefreshCounter();
  24357. },
  24358. enumerable: true,
  24359. configurable: true
  24360. });
  24361. ProceduralTexture.prototype._shouldRender = function () {
  24362. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24363. return false;
  24364. }
  24365. if (this._fallbackTextureUsed) {
  24366. return false;
  24367. }
  24368. if (this._currentRefreshId === -1) {
  24369. this._currentRefreshId = 1;
  24370. return true;
  24371. }
  24372. if (this.refreshRate === this._currentRefreshId) {
  24373. this._currentRefreshId = 1;
  24374. return true;
  24375. }
  24376. this._currentRefreshId++;
  24377. return false;
  24378. };
  24379. ProceduralTexture.prototype.getRenderSize = function () {
  24380. return this._size;
  24381. };
  24382. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24383. if (this._fallbackTextureUsed) {
  24384. return;
  24385. }
  24386. this.releaseInternalTexture();
  24387. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24388. };
  24389. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24390. if (this._uniforms.indexOf(uniformName) === -1) {
  24391. this._uniforms.push(uniformName);
  24392. }
  24393. };
  24394. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24395. if (this._samplers.indexOf(name) === -1) {
  24396. this._samplers.push(name);
  24397. }
  24398. this._textures[name] = texture;
  24399. return this;
  24400. };
  24401. ProceduralTexture.prototype.setFloat = function (name, value) {
  24402. this._checkUniform(name);
  24403. this._floats[name] = value;
  24404. return this;
  24405. };
  24406. ProceduralTexture.prototype.setFloats = function (name, value) {
  24407. this._checkUniform(name);
  24408. this._floatsArrays[name] = value;
  24409. return this;
  24410. };
  24411. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24412. this._checkUniform(name);
  24413. this._colors3[name] = value;
  24414. return this;
  24415. };
  24416. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24417. this._checkUniform(name);
  24418. this._colors4[name] = value;
  24419. return this;
  24420. };
  24421. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24422. this._checkUniform(name);
  24423. this._vectors2[name] = value;
  24424. return this;
  24425. };
  24426. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24427. this._checkUniform(name);
  24428. this._vectors3[name] = value;
  24429. return this;
  24430. };
  24431. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24432. this._checkUniform(name);
  24433. this._matrices[name] = value;
  24434. return this;
  24435. };
  24436. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24437. var scene = this.getScene();
  24438. var engine = scene.getEngine();
  24439. // Render
  24440. engine.enableEffect(this._effect);
  24441. engine.setState(false);
  24442. // Texture
  24443. for (var name in this._textures) {
  24444. this._effect.setTexture(name, this._textures[name]);
  24445. }
  24446. // Float
  24447. for (name in this._floats) {
  24448. this._effect.setFloat(name, this._floats[name]);
  24449. }
  24450. // Floats
  24451. for (name in this._floatsArrays) {
  24452. this._effect.setArray(name, this._floatsArrays[name]);
  24453. }
  24454. // Color3
  24455. for (name in this._colors3) {
  24456. this._effect.setColor3(name, this._colors3[name]);
  24457. }
  24458. // Color4
  24459. for (name in this._colors4) {
  24460. var color = this._colors4[name];
  24461. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24462. }
  24463. // Vector2
  24464. for (name in this._vectors2) {
  24465. this._effect.setVector2(name, this._vectors2[name]);
  24466. }
  24467. // Vector3
  24468. for (name in this._vectors3) {
  24469. this._effect.setVector3(name, this._vectors3[name]);
  24470. }
  24471. // Matrix
  24472. for (name in this._matrices) {
  24473. this._effect.setMatrix(name, this._matrices[name]);
  24474. }
  24475. // VBOs
  24476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24477. if (this.isCube) {
  24478. for (var face = 0; face < 6; face++) {
  24479. engine.bindFramebuffer(this._texture, face);
  24480. this._effect.setFloat("face", face);
  24481. // Clear
  24482. engine.clear(scene.clearColor, true, true, true);
  24483. // Draw order
  24484. engine.draw(true, 0, 6);
  24485. // Mipmaps
  24486. if (face === 5) {
  24487. engine.generateMipMapsForCubemap(this._texture);
  24488. }
  24489. }
  24490. }
  24491. else {
  24492. engine.bindFramebuffer(this._texture);
  24493. // Clear
  24494. engine.clear(scene.clearColor, true, true, true);
  24495. // Draw order
  24496. engine.draw(true, 0, 6);
  24497. }
  24498. // Unbind
  24499. engine.unBindFramebuffer(this._texture, this.isCube);
  24500. if (this.onGenerated) {
  24501. this.onGenerated();
  24502. }
  24503. };
  24504. ProceduralTexture.prototype.clone = function () {
  24505. var textureSize = this.getSize();
  24506. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24507. // Base texture
  24508. newTexture.hasAlpha = this.hasAlpha;
  24509. newTexture.level = this.level;
  24510. // RenderTarget Texture
  24511. newTexture.coordinatesMode = this.coordinatesMode;
  24512. return newTexture;
  24513. };
  24514. ProceduralTexture.prototype.dispose = function () {
  24515. var index = this.getScene()._proceduralTextures.indexOf(this);
  24516. if (index >= 0) {
  24517. this.getScene()._proceduralTextures.splice(index, 1);
  24518. }
  24519. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24520. if (vertexBuffer) {
  24521. vertexBuffer.dispose();
  24522. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24523. }
  24524. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24525. this._indexBuffer = null;
  24526. }
  24527. _super.prototype.dispose.call(this);
  24528. };
  24529. return ProceduralTexture;
  24530. }(BABYLON.Texture));
  24531. BABYLON.ProceduralTexture = ProceduralTexture;
  24532. })(BABYLON || (BABYLON = {}));
  24533. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24534. var BABYLON;
  24535. (function (BABYLON) {
  24536. var MirrorTexture = (function (_super) {
  24537. __extends(MirrorTexture, _super);
  24538. function MirrorTexture(name, size, scene, generateMipMaps) {
  24539. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  24540. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24541. _this._transformMatrix = BABYLON.Matrix.Zero();
  24542. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  24543. _this.onBeforeRenderObservable.add(function () {
  24544. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24545. _this._savedViewMatrix = scene.getViewMatrix();
  24546. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24547. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24548. scene.clipPlane = _this.mirrorPlane;
  24549. scene.getEngine().cullBackFaces = false;
  24550. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24551. });
  24552. _this.onAfterRenderObservable.add(function () {
  24553. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24554. scene.getEngine().cullBackFaces = true;
  24555. scene._mirroredCameraPosition = null;
  24556. delete scene.clipPlane;
  24557. });
  24558. return _this;
  24559. }
  24560. MirrorTexture.prototype.clone = function () {
  24561. var textureSize = this.getSize();
  24562. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24563. // Base texture
  24564. newTexture.hasAlpha = this.hasAlpha;
  24565. newTexture.level = this.level;
  24566. // Mirror Texture
  24567. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24568. newTexture.renderList = this.renderList.slice(0);
  24569. return newTexture;
  24570. };
  24571. MirrorTexture.prototype.serialize = function () {
  24572. if (!this.name) {
  24573. return null;
  24574. }
  24575. var serializationObject = _super.prototype.serialize.call(this);
  24576. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24577. return serializationObject;
  24578. };
  24579. return MirrorTexture;
  24580. }(BABYLON.RenderTargetTexture));
  24581. BABYLON.MirrorTexture = MirrorTexture;
  24582. })(BABYLON || (BABYLON = {}));
  24583. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24584. var BABYLON;
  24585. (function (BABYLON) {
  24586. /**
  24587. * Creates a refraction texture used by refraction channel of the standard material.
  24588. * @param name the texture name
  24589. * @param size size of the underlying texture
  24590. * @param scene root scene
  24591. */
  24592. var RefractionTexture = (function (_super) {
  24593. __extends(RefractionTexture, _super);
  24594. function RefractionTexture(name, size, scene, generateMipMaps) {
  24595. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  24596. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24597. _this.depth = 2.0;
  24598. _this.onBeforeRenderObservable.add(function () {
  24599. scene.clipPlane = _this.refractionPlane;
  24600. });
  24601. _this.onAfterRenderObservable.add(function () {
  24602. delete scene.clipPlane;
  24603. });
  24604. return _this;
  24605. }
  24606. RefractionTexture.prototype.clone = function () {
  24607. var textureSize = this.getSize();
  24608. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24609. // Base texture
  24610. newTexture.hasAlpha = this.hasAlpha;
  24611. newTexture.level = this.level;
  24612. // Refraction Texture
  24613. newTexture.refractionPlane = this.refractionPlane.clone();
  24614. newTexture.renderList = this.renderList.slice(0);
  24615. newTexture.depth = this.depth;
  24616. return newTexture;
  24617. };
  24618. RefractionTexture.prototype.serialize = function () {
  24619. if (!this.name) {
  24620. return null;
  24621. }
  24622. var serializationObject = _super.prototype.serialize.call(this);
  24623. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24624. serializationObject.depth = this.depth;
  24625. return serializationObject;
  24626. };
  24627. return RefractionTexture;
  24628. }(BABYLON.RenderTargetTexture));
  24629. BABYLON.RefractionTexture = RefractionTexture;
  24630. })(BABYLON || (BABYLON = {}));
  24631. //# sourceMappingURL=babylon.refractionTexture.js.map
  24632. var BABYLON;
  24633. (function (BABYLON) {
  24634. var DynamicTexture = (function (_super) {
  24635. __extends(DynamicTexture, _super);
  24636. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24638. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24639. _this.name = name;
  24640. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24641. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24642. _this._generateMipMaps = generateMipMaps;
  24643. if (options.getContext) {
  24644. _this._canvas = options;
  24645. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24646. }
  24647. else {
  24648. _this._canvas = document.createElement("canvas");
  24649. if (options.width) {
  24650. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24651. }
  24652. else {
  24653. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24654. }
  24655. }
  24656. var textureSize = _this.getSize();
  24657. _this._canvas.width = textureSize.width;
  24658. _this._canvas.height = textureSize.height;
  24659. _this._context = _this._canvas.getContext("2d");
  24660. return _this;
  24661. }
  24662. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24663. get: function () {
  24664. return true;
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. DynamicTexture.prototype.scale = function (ratio) {
  24670. var textureSize = this.getSize();
  24671. textureSize.width *= ratio;
  24672. textureSize.height *= ratio;
  24673. this._canvas.width = textureSize.width;
  24674. this._canvas.height = textureSize.height;
  24675. this.releaseInternalTexture();
  24676. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24677. };
  24678. DynamicTexture.prototype.getContext = function () {
  24679. return this._context;
  24680. };
  24681. DynamicTexture.prototype.clear = function () {
  24682. var size = this.getSize();
  24683. this._context.fillRect(0, 0, size.width, size.height);
  24684. };
  24685. DynamicTexture.prototype.update = function (invertY) {
  24686. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24687. };
  24688. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24689. if (update === void 0) { update = true; }
  24690. var size = this.getSize();
  24691. if (clearColor) {
  24692. this._context.fillStyle = clearColor;
  24693. this._context.fillRect(0, 0, size.width, size.height);
  24694. }
  24695. this._context.font = font;
  24696. if (x === null) {
  24697. var textSize = this._context.measureText(text);
  24698. x = (size.width - textSize.width) / 2;
  24699. }
  24700. this._context.fillStyle = color;
  24701. this._context.fillText(text, x, y);
  24702. if (update) {
  24703. this.update(invertY);
  24704. }
  24705. };
  24706. DynamicTexture.prototype.clone = function () {
  24707. var textureSize = this.getSize();
  24708. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24709. // Base texture
  24710. newTexture.hasAlpha = this.hasAlpha;
  24711. newTexture.level = this.level;
  24712. // Dynamic Texture
  24713. newTexture.wrapU = this.wrapU;
  24714. newTexture.wrapV = this.wrapV;
  24715. return newTexture;
  24716. };
  24717. return DynamicTexture;
  24718. }(BABYLON.Texture));
  24719. BABYLON.DynamicTexture = DynamicTexture;
  24720. })(BABYLON || (BABYLON = {}));
  24721. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24722. var BABYLON;
  24723. (function (BABYLON) {
  24724. var VideoTexture = (function (_super) {
  24725. __extends(VideoTexture, _super);
  24726. /**
  24727. * Creates a video texture.
  24728. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24729. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24730. * @param {BABYLON.Scene} scene is obviously the current scene.
  24731. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24732. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24733. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24734. */
  24735. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24736. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24737. if (invertY === void 0) { invertY = false; }
  24738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24739. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  24740. _this._autoLaunch = true;
  24741. var urls;
  24742. _this.name = name;
  24743. if (urlsOrVideo instanceof HTMLVideoElement) {
  24744. _this.video = urlsOrVideo;
  24745. }
  24746. else {
  24747. urls = urlsOrVideo;
  24748. _this.video = document.createElement("video");
  24749. _this.video.autoplay = false;
  24750. _this.video.loop = true;
  24751. }
  24752. _this._generateMipMaps = generateMipMaps;
  24753. _this._samplingMode = samplingMode;
  24754. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  24755. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24756. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24757. }
  24758. else {
  24759. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24760. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24761. _this._generateMipMaps = false;
  24762. }
  24763. if (urls) {
  24764. _this.video.addEventListener("canplaythrough", function () {
  24765. _this._createTexture();
  24766. });
  24767. urls.forEach(function (url) {
  24768. var source = document.createElement("source");
  24769. source.src = url;
  24770. _this.video.appendChild(source);
  24771. });
  24772. }
  24773. else {
  24774. _this._createTexture();
  24775. }
  24776. _this._lastUpdate = BABYLON.Tools.Now;
  24777. return _this;
  24778. }
  24779. VideoTexture.prototype._createTexture = function () {
  24780. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24781. this._texture.isReady = true;
  24782. };
  24783. VideoTexture.prototype.update = function () {
  24784. if (this._autoLaunch) {
  24785. this._autoLaunch = false;
  24786. this.video.play();
  24787. }
  24788. var now = BABYLON.Tools.Now;
  24789. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24790. return false;
  24791. }
  24792. this._lastUpdate = now;
  24793. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24794. return true;
  24795. };
  24796. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  24797. var video = document.createElement("video");
  24798. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  24799. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  24800. if (navigator.getUserMedia) {
  24801. navigator.getUserMedia({
  24802. video: {
  24803. width: {
  24804. min: (constraints && constraints.minWidth) || 256,
  24805. max: (constraints && constraints.maxWidth) || 640
  24806. },
  24807. height: {
  24808. min: (constraints && constraints.minHeight) || 256,
  24809. max: (constraints && constraints.maxHeight) || 480
  24810. }
  24811. }
  24812. }, function (stream) {
  24813. if (video.mozSrcObject !== undefined) {
  24814. video.mozSrcObject = stream;
  24815. }
  24816. else {
  24817. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  24818. }
  24819. video.play();
  24820. if (onReady) {
  24821. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  24822. }
  24823. }, function (e) {
  24824. BABYLON.Tools.Error(e.name);
  24825. });
  24826. }
  24827. };
  24828. return VideoTexture;
  24829. }(BABYLON.Texture));
  24830. BABYLON.VideoTexture = VideoTexture;
  24831. })(BABYLON || (BABYLON = {}));
  24832. //# sourceMappingURL=babylon.videoTexture.js.map
  24833. var BABYLON;
  24834. (function (BABYLON) {
  24835. var CustomProceduralTexture = (function (_super) {
  24836. __extends(CustomProceduralTexture, _super);
  24837. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24838. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  24839. _this._animate = true;
  24840. _this._time = 0;
  24841. _this._texturePath = texturePath;
  24842. //Try to load json
  24843. _this.loadJson(texturePath);
  24844. _this.refreshRate = 1;
  24845. return _this;
  24846. }
  24847. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24848. var _this = this;
  24849. var that = this;
  24850. function noConfigFile() {
  24851. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24852. try {
  24853. that.setFragment(that._texturePath);
  24854. }
  24855. catch (ex) {
  24856. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24857. }
  24858. }
  24859. var configFileUrl = jsonUrl + "/config.json";
  24860. var xhr = new XMLHttpRequest();
  24861. xhr.open("GET", configFileUrl, true);
  24862. xhr.addEventListener("load", function () {
  24863. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24864. try {
  24865. _this._config = JSON.parse(xhr.response);
  24866. _this.updateShaderUniforms();
  24867. _this.updateTextures();
  24868. _this.setFragment(_this._texturePath + "/custom");
  24869. _this._animate = _this._config.animate;
  24870. _this.refreshRate = _this._config.refreshrate;
  24871. }
  24872. catch (ex) {
  24873. noConfigFile();
  24874. }
  24875. }
  24876. else {
  24877. noConfigFile();
  24878. }
  24879. }, false);
  24880. xhr.addEventListener("error", function () {
  24881. noConfigFile();
  24882. }, false);
  24883. try {
  24884. xhr.send();
  24885. }
  24886. catch (ex) {
  24887. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24888. }
  24889. };
  24890. CustomProceduralTexture.prototype.isReady = function () {
  24891. if (!_super.prototype.isReady.call(this)) {
  24892. return false;
  24893. }
  24894. for (var name in this._textures) {
  24895. var texture = this._textures[name];
  24896. if (!texture.isReady()) {
  24897. return false;
  24898. }
  24899. }
  24900. return true;
  24901. };
  24902. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24903. if (this._animate) {
  24904. this._time += this.getScene().getAnimationRatio() * 0.03;
  24905. this.updateShaderUniforms();
  24906. }
  24907. _super.prototype.render.call(this, useCameraPostProcess);
  24908. };
  24909. CustomProceduralTexture.prototype.updateTextures = function () {
  24910. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24911. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24912. }
  24913. };
  24914. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24915. if (this._config) {
  24916. for (var j = 0; j < this._config.uniforms.length; j++) {
  24917. var uniform = this._config.uniforms[j];
  24918. switch (uniform.type) {
  24919. case "float":
  24920. this.setFloat(uniform.name, uniform.value);
  24921. break;
  24922. case "color3":
  24923. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24924. break;
  24925. case "color4":
  24926. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24927. break;
  24928. case "vector2":
  24929. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24930. break;
  24931. case "vector3":
  24932. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24933. break;
  24934. }
  24935. }
  24936. }
  24937. this.setFloat("time", this._time);
  24938. };
  24939. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24940. get: function () {
  24941. return this._animate;
  24942. },
  24943. set: function (value) {
  24944. this._animate = value;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. return CustomProceduralTexture;
  24950. }(BABYLON.ProceduralTexture));
  24951. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24952. })(BABYLON || (BABYLON = {}));
  24953. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  24954. var BABYLON;
  24955. (function (BABYLON) {
  24956. var EffectFallbacks = (function () {
  24957. function EffectFallbacks() {
  24958. this._defines = {};
  24959. this._currentRank = 32;
  24960. this._maxRank = -1;
  24961. }
  24962. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24963. if (!this._defines[rank]) {
  24964. if (rank < this._currentRank) {
  24965. this._currentRank = rank;
  24966. }
  24967. if (rank > this._maxRank) {
  24968. this._maxRank = rank;
  24969. }
  24970. this._defines[rank] = new Array();
  24971. }
  24972. this._defines[rank].push(define);
  24973. };
  24974. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24975. this._meshRank = rank;
  24976. this._mesh = mesh;
  24977. if (rank > this._maxRank) {
  24978. this._maxRank = rank;
  24979. }
  24980. };
  24981. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24982. get: function () {
  24983. return this._currentRank <= this._maxRank;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24989. var currentFallbacks = this._defines[this._currentRank];
  24990. for (var index = 0; index < currentFallbacks.length; index++) {
  24991. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24992. }
  24993. if (this._mesh && this._currentRank === this._meshRank) {
  24994. this._mesh.computeBonesUsingShaders = false;
  24995. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24996. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24997. }
  24998. this._currentRank++;
  24999. return currentDefines;
  25000. };
  25001. return EffectFallbacks;
  25002. }());
  25003. BABYLON.EffectFallbacks = EffectFallbacks;
  25004. var Effect = (function () {
  25005. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25006. var _this = this;
  25007. this._isReady = false;
  25008. this._compilationError = "";
  25009. this._valueCache = {};
  25010. this._engine = engine;
  25011. this.name = baseName;
  25012. this.defines = defines;
  25013. this._uniformsNames = uniformsNames.concat(samplers);
  25014. this._samplers = samplers;
  25015. this._attributesNames = attributesNames;
  25016. this.onError = onError;
  25017. this.onCompiled = onCompiled;
  25018. this._indexParameters = indexParameters;
  25019. var vertexSource;
  25020. var fragmentSource;
  25021. if (baseName.vertexElement) {
  25022. vertexSource = document.getElementById(baseName.vertexElement);
  25023. if (!vertexSource) {
  25024. vertexSource = baseName.vertexElement;
  25025. }
  25026. }
  25027. else {
  25028. vertexSource = baseName.vertex || baseName;
  25029. }
  25030. if (baseName.fragmentElement) {
  25031. fragmentSource = document.getElementById(baseName.fragmentElement);
  25032. if (!fragmentSource) {
  25033. fragmentSource = baseName.fragmentElement;
  25034. }
  25035. }
  25036. else {
  25037. fragmentSource = baseName.fragment || baseName;
  25038. }
  25039. this._loadVertexShader(vertexSource, function (vertexCode) {
  25040. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25041. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25042. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25043. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  25044. });
  25045. });
  25046. });
  25047. });
  25048. }
  25049. // Properties
  25050. Effect.prototype.isReady = function () {
  25051. return this._isReady;
  25052. };
  25053. Effect.prototype.getProgram = function () {
  25054. return this._program;
  25055. };
  25056. Effect.prototype.getAttributesNames = function () {
  25057. return this._attributesNames;
  25058. };
  25059. Effect.prototype.getAttributeLocation = function (index) {
  25060. return this._attributes[index];
  25061. };
  25062. Effect.prototype.getAttributeLocationByName = function (name) {
  25063. var index = this._attributesNames.indexOf(name);
  25064. return this._attributes[index];
  25065. };
  25066. Effect.prototype.getAttributesCount = function () {
  25067. return this._attributes.length;
  25068. };
  25069. Effect.prototype.getUniformIndex = function (uniformName) {
  25070. return this._uniformsNames.indexOf(uniformName);
  25071. };
  25072. Effect.prototype.getUniform = function (uniformName) {
  25073. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25074. };
  25075. Effect.prototype.getSamplers = function () {
  25076. return this._samplers;
  25077. };
  25078. Effect.prototype.getCompilationError = function () {
  25079. return this._compilationError;
  25080. };
  25081. Effect.prototype.getVertexShaderSource = function () {
  25082. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25083. };
  25084. Effect.prototype.getFragmentShaderSource = function () {
  25085. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25086. };
  25087. // Methods
  25088. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25089. // DOM element ?
  25090. if (vertex instanceof HTMLElement) {
  25091. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25092. callback(vertexCode);
  25093. return;
  25094. }
  25095. // Base64 encoded ?
  25096. if (vertex.substr(0, 7) === "base64:") {
  25097. var vertexBinary = window.atob(vertex.substr(7));
  25098. callback(vertexBinary);
  25099. return;
  25100. }
  25101. // Is in local store ?
  25102. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25103. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25104. return;
  25105. }
  25106. var vertexShaderUrl;
  25107. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25108. vertexShaderUrl = vertex;
  25109. }
  25110. else {
  25111. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25112. }
  25113. // Vertex shader
  25114. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25115. };
  25116. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25117. // DOM element ?
  25118. if (fragment instanceof HTMLElement) {
  25119. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25120. callback(fragmentCode);
  25121. return;
  25122. }
  25123. // Base64 encoded ?
  25124. if (fragment.substr(0, 7) === "base64:") {
  25125. var fragmentBinary = window.atob(fragment.substr(7));
  25126. callback(fragmentBinary);
  25127. return;
  25128. }
  25129. // Is in local store ?
  25130. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25131. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25132. return;
  25133. }
  25134. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25135. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25136. return;
  25137. }
  25138. var fragmentShaderUrl;
  25139. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25140. fragmentShaderUrl = fragment;
  25141. }
  25142. else {
  25143. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25144. }
  25145. // Fragment shader
  25146. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25147. };
  25148. Effect.prototype._dumpShadersName = function () {
  25149. if (this.name.vertexElement) {
  25150. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25151. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25152. }
  25153. else if (this.name.vertex) {
  25154. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25155. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25156. }
  25157. else {
  25158. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25159. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25160. }
  25161. };
  25162. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25163. var _this = this;
  25164. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25165. var match = regex.exec(sourceCode);
  25166. var returnValue = new String(sourceCode);
  25167. while (match != null) {
  25168. var includeFile = match[1];
  25169. if (Effect.IncludesShadersStore[includeFile]) {
  25170. // Substitution
  25171. var includeContent = Effect.IncludesShadersStore[includeFile];
  25172. if (match[2]) {
  25173. var splits = match[3].split(",");
  25174. for (var index = 0; index < splits.length; index += 2) {
  25175. var source = new RegExp(splits[index], "g");
  25176. var dest = splits[index + 1];
  25177. includeContent = includeContent.replace(source, dest);
  25178. }
  25179. }
  25180. if (match[4]) {
  25181. var indexString = match[5];
  25182. if (indexString.indexOf("..") !== -1) {
  25183. var indexSplits = indexString.split("..");
  25184. var minIndex = parseInt(indexSplits[0]);
  25185. var maxIndex = parseInt(indexSplits[1]);
  25186. var sourceIncludeContent = includeContent.slice(0);
  25187. includeContent = "";
  25188. if (isNaN(maxIndex)) {
  25189. maxIndex = this._indexParameters[indexSplits[1]];
  25190. }
  25191. for (var i = minIndex; i <= maxIndex; i++) {
  25192. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25193. }
  25194. }
  25195. else {
  25196. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25197. }
  25198. }
  25199. // Replace
  25200. returnValue = returnValue.replace(match[0], includeContent);
  25201. }
  25202. else {
  25203. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25204. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25205. Effect.IncludesShadersStore[includeFile] = fileContent;
  25206. _this._processIncludes(returnValue, callback);
  25207. });
  25208. return;
  25209. }
  25210. match = regex.exec(sourceCode);
  25211. }
  25212. callback(returnValue);
  25213. };
  25214. Effect.prototype._processPrecision = function (source) {
  25215. if (source.indexOf("precision highp float") === -1) {
  25216. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25217. source = "precision mediump float;\n" + source;
  25218. }
  25219. else {
  25220. source = "precision highp float;\n" + source;
  25221. }
  25222. }
  25223. else {
  25224. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25225. source = source.replace("precision highp float", "precision mediump float");
  25226. }
  25227. }
  25228. return source;
  25229. };
  25230. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25231. try {
  25232. var engine = this._engine;
  25233. // Precision
  25234. vertexSourceCode = this._processPrecision(vertexSourceCode);
  25235. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  25236. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25237. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25238. this._attributes = engine.getAttributes(this._program, attributesNames);
  25239. var index;
  25240. for (index = 0; index < this._samplers.length; index++) {
  25241. var sampler = this.getUniform(this._samplers[index]);
  25242. if (sampler == null) {
  25243. this._samplers.splice(index, 1);
  25244. index--;
  25245. }
  25246. }
  25247. engine.bindSamplers(this);
  25248. this._compilationError = "";
  25249. this._isReady = true;
  25250. if (this.onCompiled) {
  25251. this.onCompiled(this);
  25252. }
  25253. }
  25254. catch (e) {
  25255. this._compilationError = e.message;
  25256. // Let's go through fallbacks then
  25257. BABYLON.Tools.Error("Unable to compile effect: ");
  25258. BABYLON.Tools.Error("Defines: " + defines);
  25259. BABYLON.Tools.Error("Error: " + this._compilationError);
  25260. this._dumpShadersName();
  25261. if (fallbacks && fallbacks.isMoreFallbacks) {
  25262. BABYLON.Tools.Error("Trying next fallback.");
  25263. defines = fallbacks.reduce(defines);
  25264. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25265. }
  25266. else {
  25267. if (this.onError) {
  25268. this.onError(this, this._compilationError);
  25269. }
  25270. }
  25271. }
  25272. };
  25273. Object.defineProperty(Effect.prototype, "isSupported", {
  25274. get: function () {
  25275. return this._compilationError === "";
  25276. },
  25277. enumerable: true,
  25278. configurable: true
  25279. });
  25280. Effect.prototype._bindTexture = function (channel, texture) {
  25281. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25282. };
  25283. Effect.prototype.setTexture = function (channel, texture) {
  25284. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25285. };
  25286. Effect.prototype.setTextureArray = function (channel, textures) {
  25287. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25288. var initialPos = this._samplers.indexOf(channel);
  25289. for (var index = 1; index < textures.length; index++) {
  25290. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25291. }
  25292. }
  25293. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25294. };
  25295. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25296. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25297. };
  25298. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25299. var changed = false;
  25300. var cache = this._valueCache[uniformName];
  25301. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25302. changed = true;
  25303. cache = new BABYLON.Matrix();
  25304. }
  25305. var tm = cache.m;
  25306. var om = matrix.m;
  25307. for (var index = 0; index < 16; index++) {
  25308. if (tm[index] !== om[index]) {
  25309. tm[index] = om[index];
  25310. changed = true;
  25311. }
  25312. }
  25313. this._valueCache[uniformName] = cache;
  25314. return changed;
  25315. };
  25316. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25317. var cache = this._valueCache[uniformName];
  25318. if (!cache) {
  25319. cache = [x, y];
  25320. this._valueCache[uniformName] = cache;
  25321. return true;
  25322. }
  25323. var changed = false;
  25324. if (cache[0] !== x) {
  25325. cache[0] = x;
  25326. changed = true;
  25327. }
  25328. if (cache[1] !== y) {
  25329. cache[1] = y;
  25330. changed = true;
  25331. }
  25332. return changed;
  25333. };
  25334. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25335. var cache = this._valueCache[uniformName];
  25336. if (!cache) {
  25337. cache = [x, y, z];
  25338. this._valueCache[uniformName] = cache;
  25339. return true;
  25340. }
  25341. var changed = false;
  25342. if (cache[0] !== x) {
  25343. cache[0] = x;
  25344. changed = true;
  25345. }
  25346. if (cache[1] !== y) {
  25347. cache[1] = y;
  25348. changed = true;
  25349. }
  25350. if (cache[2] !== z) {
  25351. cache[2] = z;
  25352. changed = true;
  25353. }
  25354. return changed;
  25355. };
  25356. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25357. var cache = this._valueCache[uniformName];
  25358. if (!cache) {
  25359. cache = [x, y, z, w];
  25360. this._valueCache[uniformName] = cache;
  25361. return true;
  25362. }
  25363. var changed = false;
  25364. if (cache[0] !== x) {
  25365. cache[0] = x;
  25366. changed = true;
  25367. }
  25368. if (cache[1] !== y) {
  25369. cache[1] = y;
  25370. changed = true;
  25371. }
  25372. if (cache[2] !== z) {
  25373. cache[2] = z;
  25374. changed = true;
  25375. }
  25376. if (cache[3] !== w) {
  25377. cache[3] = w;
  25378. changed = true;
  25379. }
  25380. return changed;
  25381. };
  25382. Effect.prototype.setIntArray = function (uniformName, array) {
  25383. this._valueCache[uniformName] = null;
  25384. this._engine.setIntArray(this.getUniform(uniformName), array);
  25385. return this;
  25386. };
  25387. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25388. this._valueCache[uniformName] = null;
  25389. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25390. return this;
  25391. };
  25392. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25393. this._valueCache[uniformName] = null;
  25394. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25395. return this;
  25396. };
  25397. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25398. this._valueCache[uniformName] = null;
  25399. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25400. return this;
  25401. };
  25402. Effect.prototype.setFloatArray = function (uniformName, array) {
  25403. this._valueCache[uniformName] = null;
  25404. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25405. return this;
  25406. };
  25407. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25408. this._valueCache[uniformName] = null;
  25409. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25410. return this;
  25411. };
  25412. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25413. this._valueCache[uniformName] = null;
  25414. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25415. return this;
  25416. };
  25417. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25418. this._valueCache[uniformName] = null;
  25419. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25420. return this;
  25421. };
  25422. Effect.prototype.setArray = function (uniformName, array) {
  25423. this._valueCache[uniformName] = null;
  25424. this._engine.setArray(this.getUniform(uniformName), array);
  25425. return this;
  25426. };
  25427. Effect.prototype.setArray2 = function (uniformName, array) {
  25428. this._valueCache[uniformName] = null;
  25429. this._engine.setArray2(this.getUniform(uniformName), array);
  25430. return this;
  25431. };
  25432. Effect.prototype.setArray3 = function (uniformName, array) {
  25433. this._valueCache[uniformName] = null;
  25434. this._engine.setArray3(this.getUniform(uniformName), array);
  25435. return this;
  25436. };
  25437. Effect.prototype.setArray4 = function (uniformName, array) {
  25438. this._valueCache[uniformName] = null;
  25439. this._engine.setArray4(this.getUniform(uniformName), array);
  25440. return this;
  25441. };
  25442. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25443. this._valueCache[uniformName] = null;
  25444. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25445. return this;
  25446. };
  25447. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25448. if (this._cacheMatrix(uniformName, matrix)) {
  25449. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25450. }
  25451. return this;
  25452. };
  25453. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25454. this._valueCache[uniformName] = null;
  25455. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25456. return this;
  25457. };
  25458. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25459. this._valueCache[uniformName] = null;
  25460. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25461. return this;
  25462. };
  25463. Effect.prototype.setFloat = function (uniformName, value) {
  25464. var cache = this._valueCache[uniformName];
  25465. if (cache !== undefined && cache === value)
  25466. return this;
  25467. this._valueCache[uniformName] = value;
  25468. this._engine.setFloat(this.getUniform(uniformName), value);
  25469. return this;
  25470. };
  25471. Effect.prototype.setBool = function (uniformName, bool) {
  25472. var cache = this._valueCache[uniformName];
  25473. if (cache !== undefined && cache === bool)
  25474. return this;
  25475. this._valueCache[uniformName] = bool;
  25476. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25477. return this;
  25478. };
  25479. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25480. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25481. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25482. }
  25483. return this;
  25484. };
  25485. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25486. if (this._cacheFloat2(uniformName, x, y)) {
  25487. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25488. }
  25489. return this;
  25490. };
  25491. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25492. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25493. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25494. }
  25495. return this;
  25496. };
  25497. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25498. if (this._cacheFloat3(uniformName, x, y, z)) {
  25499. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25500. }
  25501. return this;
  25502. };
  25503. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25504. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25505. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25506. }
  25507. return this;
  25508. };
  25509. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25510. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25511. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25512. }
  25513. return this;
  25514. };
  25515. Effect.prototype.setColor3 = function (uniformName, color3) {
  25516. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25517. this._engine.setColor3(this.getUniform(uniformName), color3);
  25518. }
  25519. return this;
  25520. };
  25521. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25522. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25523. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25524. }
  25525. return this;
  25526. };
  25527. Effect.prototype._recombineShader = function (node) {
  25528. if (node.define) {
  25529. if (node.condition) {
  25530. var defineIndex = this.defines.indexOf("#define " + node.define);
  25531. if (defineIndex === -1) {
  25532. return null;
  25533. }
  25534. var nextComma = this.defines.indexOf("\n", defineIndex);
  25535. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  25536. var condition = defineValue + node.condition;
  25537. if (!eval(condition)) {
  25538. return null;
  25539. }
  25540. }
  25541. else if (node.ndef) {
  25542. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25543. return null;
  25544. }
  25545. }
  25546. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25547. return null;
  25548. }
  25549. }
  25550. var result = "";
  25551. for (var index = 0; index < node.children.length; index++) {
  25552. var line = node.children[index];
  25553. if (line.children) {
  25554. var combined = this._recombineShader(line);
  25555. if (combined !== null) {
  25556. result += combined + "\r\n";
  25557. }
  25558. continue;
  25559. }
  25560. if (line.length > 0) {
  25561. result += line + "\r\n";
  25562. }
  25563. }
  25564. return result;
  25565. };
  25566. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25567. var root = {
  25568. children: []
  25569. };
  25570. var currentNode = root;
  25571. var lines = shaderString.split("\n");
  25572. for (var index = 0; index < lines.length; index++) {
  25573. var line = lines[index].trim();
  25574. // #ifdef
  25575. var pos = line.indexOf("#ifdef ");
  25576. if (pos !== -1) {
  25577. var define = line.substr(pos + 7);
  25578. var newNode = {
  25579. condition: null,
  25580. ndef: false,
  25581. define: define,
  25582. children: [],
  25583. parent: currentNode
  25584. };
  25585. currentNode.children.push(newNode);
  25586. currentNode = newNode;
  25587. continue;
  25588. }
  25589. // #ifndef
  25590. var pos = line.indexOf("#ifndef ");
  25591. if (pos !== -1) {
  25592. var define = line.substr(pos + 8);
  25593. newNode = {
  25594. condition: null,
  25595. define: define,
  25596. ndef: true,
  25597. children: [],
  25598. parent: currentNode
  25599. };
  25600. currentNode.children.push(newNode);
  25601. currentNode = newNode;
  25602. continue;
  25603. }
  25604. // #if
  25605. var pos = line.indexOf("#if ");
  25606. if (pos !== -1) {
  25607. var define = line.substr(pos + 4).trim();
  25608. var conditionPos = define.indexOf(" ");
  25609. newNode = {
  25610. condition: define.substr(conditionPos + 1),
  25611. define: define.substr(0, conditionPos),
  25612. ndef: false,
  25613. children: [],
  25614. parent: currentNode
  25615. };
  25616. currentNode.children.push(newNode);
  25617. currentNode = newNode;
  25618. continue;
  25619. }
  25620. // #endif
  25621. pos = line.indexOf("#endif");
  25622. if (pos !== -1) {
  25623. currentNode = currentNode.parent;
  25624. continue;
  25625. }
  25626. currentNode.children.push(line);
  25627. }
  25628. // Recombine
  25629. return this._recombineShader(root);
  25630. };
  25631. return Effect;
  25632. }());
  25633. // Statics
  25634. Effect.ShadersStore = {};
  25635. Effect.IncludesShadersStore = {};
  25636. BABYLON.Effect = Effect;
  25637. })(BABYLON || (BABYLON = {}));
  25638. //# sourceMappingURL=babylon.effect.js.map
  25639. var BABYLON;
  25640. (function (BABYLON) {
  25641. var MaterialHelper = (function () {
  25642. function MaterialHelper() {
  25643. }
  25644. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25645. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25646. var lightIndex = 0;
  25647. var needNormals = false;
  25648. var needRebuild = false;
  25649. var needShadows = false;
  25650. var lightmapMode = false;
  25651. for (var index = 0; index < scene.lights.length; index++) {
  25652. var light = scene.lights[index];
  25653. if (!light.isEnabled()) {
  25654. continue;
  25655. }
  25656. // Excluded check
  25657. if (light._excludedMeshesIds.length > 0) {
  25658. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25659. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25660. if (excludedMesh) {
  25661. light.excludedMeshes.push(excludedMesh);
  25662. }
  25663. }
  25664. light._excludedMeshesIds = [];
  25665. }
  25666. // Included check
  25667. if (light._includedOnlyMeshesIds.length > 0) {
  25668. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25669. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25670. if (includedOnlyMesh) {
  25671. light.includedOnlyMeshes.push(includedOnlyMesh);
  25672. }
  25673. }
  25674. light._includedOnlyMeshesIds = [];
  25675. }
  25676. if (!light.canAffectMesh(mesh)) {
  25677. continue;
  25678. }
  25679. needNormals = true;
  25680. if (defines["LIGHT" + lightIndex] === undefined) {
  25681. needRebuild = true;
  25682. }
  25683. defines["LIGHT" + lightIndex] = true;
  25684. var type;
  25685. if (light instanceof BABYLON.SpotLight) {
  25686. type = "SPOTLIGHT" + lightIndex;
  25687. }
  25688. else if (light instanceof BABYLON.HemisphericLight) {
  25689. type = "HEMILIGHT" + lightIndex;
  25690. }
  25691. else if (light instanceof BABYLON.PointLight) {
  25692. type = "POINTLIGHT" + lightIndex;
  25693. }
  25694. else {
  25695. type = "DIRLIGHT" + lightIndex;
  25696. }
  25697. if (defines[type] === undefined) {
  25698. needRebuild = true;
  25699. }
  25700. defines[type] = true;
  25701. // Specular
  25702. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25703. defines["SPECULARTERM"] = true;
  25704. }
  25705. // Shadows
  25706. if (scene.shadowsEnabled) {
  25707. var shadowGenerator = light.getShadowGenerator();
  25708. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25709. if (defines["SHADOW" + lightIndex] === undefined) {
  25710. needRebuild = true;
  25711. }
  25712. defines["SHADOW" + lightIndex] = true;
  25713. defines["SHADOWS"] = true;
  25714. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25715. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25716. needRebuild = true;
  25717. }
  25718. defines["SHADOWVSM" + lightIndex] = true;
  25719. }
  25720. if (shadowGenerator.usePoissonSampling) {
  25721. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25722. needRebuild = true;
  25723. }
  25724. defines["SHADOWPCF" + lightIndex] = true;
  25725. }
  25726. needShadows = true;
  25727. }
  25728. }
  25729. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25730. lightmapMode = true;
  25731. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25732. needRebuild = true;
  25733. }
  25734. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25735. needRebuild = true;
  25736. }
  25737. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25738. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25739. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25740. }
  25741. }
  25742. lightIndex++;
  25743. if (lightIndex === maxSimultaneousLights)
  25744. break;
  25745. }
  25746. var caps = scene.getEngine().getCaps();
  25747. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25748. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25749. needRebuild = true;
  25750. }
  25751. defines["SHADOWFULLFLOAT"] = true;
  25752. }
  25753. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25754. needRebuild = true;
  25755. }
  25756. if (lightmapMode) {
  25757. defines["LIGHTMAPEXCLUDED"] = true;
  25758. }
  25759. if (needRebuild) {
  25760. defines.rebuild();
  25761. }
  25762. return needNormals;
  25763. };
  25764. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25765. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25766. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25767. if (!defines["LIGHT" + lightIndex]) {
  25768. break;
  25769. }
  25770. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25771. samplersList.push("shadowSampler" + lightIndex);
  25772. }
  25773. };
  25774. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25775. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25776. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25777. if (!defines["LIGHT" + lightIndex]) {
  25778. break;
  25779. }
  25780. if (lightIndex > 0) {
  25781. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25782. }
  25783. if (defines["SHADOW" + lightIndex]) {
  25784. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25785. }
  25786. if (defines["SHADOWPCF" + lightIndex]) {
  25787. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25788. }
  25789. if (defines["SHADOWVSM" + lightIndex]) {
  25790. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25791. }
  25792. }
  25793. };
  25794. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25795. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25796. fallbacks.addCPUSkinningFallback(0, mesh);
  25797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25799. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25800. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25801. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25802. }
  25803. }
  25804. };
  25805. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25806. if (defines["INSTANCES"]) {
  25807. attribs.push("world0");
  25808. attribs.push("world1");
  25809. attribs.push("world2");
  25810. attribs.push("world3");
  25811. }
  25812. };
  25813. // Bindings
  25814. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25815. var shadowGenerator = light.getShadowGenerator();
  25816. if (mesh.receiveShadows && shadowGenerator) {
  25817. if (!light.needCube()) {
  25818. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25819. }
  25820. else {
  25821. if (!depthValuesAlreadySet) {
  25822. depthValuesAlreadySet = true;
  25823. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25824. }
  25825. }
  25826. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25827. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25828. }
  25829. return depthValuesAlreadySet;
  25830. };
  25831. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25832. if (light instanceof BABYLON.PointLight) {
  25833. // Point Light
  25834. light.transferToEffect(effect, "vLightData" + lightIndex);
  25835. }
  25836. else if (light instanceof BABYLON.DirectionalLight) {
  25837. // Directional Light
  25838. light.transferToEffect(effect, "vLightData" + lightIndex);
  25839. }
  25840. else if (light instanceof BABYLON.SpotLight) {
  25841. // Spot Light
  25842. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25843. }
  25844. else if (light instanceof BABYLON.HemisphericLight) {
  25845. // Hemispheric Light
  25846. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25847. }
  25848. };
  25849. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25850. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25851. var lightIndex = 0;
  25852. var depthValuesAlreadySet = false;
  25853. for (var index = 0; index < scene.lights.length; index++) {
  25854. var light = scene.lights[index];
  25855. if (!light.isEnabled()) {
  25856. continue;
  25857. }
  25858. if (!light.canAffectMesh(mesh)) {
  25859. continue;
  25860. }
  25861. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25862. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25863. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25864. if (defines["SPECULARTERM"]) {
  25865. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25866. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25867. }
  25868. // Shadows
  25869. if (scene.shadowsEnabled) {
  25870. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25871. }
  25872. lightIndex++;
  25873. if (lightIndex === maxSimultaneousLights)
  25874. break;
  25875. }
  25876. };
  25877. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25878. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25879. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25880. effect.setColor3("vFogColor", scene.fogColor);
  25881. }
  25882. };
  25883. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25884. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25885. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25886. if (matrices) {
  25887. effect.setMatrices("mBones", matrices);
  25888. }
  25889. }
  25890. };
  25891. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25892. if (defines["LOGARITHMICDEPTH"]) {
  25893. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25894. }
  25895. };
  25896. MaterialHelper.BindClipPlane = function (effect, scene) {
  25897. if (scene.clipPlane) {
  25898. var clipPlane = scene.clipPlane;
  25899. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25900. }
  25901. };
  25902. return MaterialHelper;
  25903. }());
  25904. BABYLON.MaterialHelper = MaterialHelper;
  25905. })(BABYLON || (BABYLON = {}));
  25906. //# sourceMappingURL=babylon.materialHelper.js.map
  25907. var BABYLON;
  25908. (function (BABYLON) {
  25909. var FresnelParameters = (function () {
  25910. function FresnelParameters() {
  25911. this.isEnabled = true;
  25912. this.leftColor = BABYLON.Color3.White();
  25913. this.rightColor = BABYLON.Color3.Black();
  25914. this.bias = 0;
  25915. this.power = 1;
  25916. }
  25917. FresnelParameters.prototype.clone = function () {
  25918. var newFresnelParameters = new FresnelParameters();
  25919. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25920. return newFresnelParameters;
  25921. };
  25922. FresnelParameters.prototype.serialize = function () {
  25923. var serializationObject = {};
  25924. serializationObject.isEnabled = this.isEnabled;
  25925. serializationObject.leftColor = this.leftColor;
  25926. serializationObject.rightColor = this.rightColor;
  25927. serializationObject.bias = this.bias;
  25928. serializationObject.power = this.power;
  25929. return serializationObject;
  25930. };
  25931. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25932. var fresnelParameters = new FresnelParameters();
  25933. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25934. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25935. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25936. fresnelParameters.bias = parsedFresnelParameters.bias;
  25937. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25938. return fresnelParameters;
  25939. };
  25940. return FresnelParameters;
  25941. }());
  25942. BABYLON.FresnelParameters = FresnelParameters;
  25943. })(BABYLON || (BABYLON = {}));
  25944. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25945. var BABYLON;
  25946. (function (BABYLON) {
  25947. var MaterialDefines = (function () {
  25948. function MaterialDefines() {
  25949. }
  25950. MaterialDefines.prototype.rebuild = function () {
  25951. if (this._keys) {
  25952. delete this._keys;
  25953. }
  25954. this._keys = Object.keys(this);
  25955. };
  25956. MaterialDefines.prototype.isEqual = function (other) {
  25957. if (this._keys.length !== other._keys.length) {
  25958. return false;
  25959. }
  25960. for (var index = 0; index < this._keys.length; index++) {
  25961. var prop = this._keys[index];
  25962. if (this[prop] !== other[prop]) {
  25963. return false;
  25964. }
  25965. }
  25966. return true;
  25967. };
  25968. MaterialDefines.prototype.cloneTo = function (other) {
  25969. if (this._keys.length !== other._keys.length) {
  25970. other._keys = this._keys.slice(0);
  25971. }
  25972. for (var index = 0; index < this._keys.length; index++) {
  25973. var prop = this._keys[index];
  25974. other[prop] = this[prop];
  25975. }
  25976. };
  25977. MaterialDefines.prototype.reset = function () {
  25978. for (var index = 0; index < this._keys.length; index++) {
  25979. var prop = this._keys[index];
  25980. if (typeof (this[prop]) === "number") {
  25981. this[prop] = 0;
  25982. }
  25983. else {
  25984. this[prop] = false;
  25985. }
  25986. }
  25987. };
  25988. MaterialDefines.prototype.toString = function () {
  25989. var result = "";
  25990. for (var index = 0; index < this._keys.length; index++) {
  25991. var prop = this._keys[index];
  25992. if (typeof (this[prop]) === "number") {
  25993. result += "#define " + prop + " " + this[prop] + "\n";
  25994. }
  25995. else if (this[prop]) {
  25996. result += "#define " + prop + "\n";
  25997. }
  25998. }
  25999. return result;
  26000. };
  26001. return MaterialDefines;
  26002. }());
  26003. BABYLON.MaterialDefines = MaterialDefines;
  26004. var Material = (function () {
  26005. function Material(name, scene, doNotAdd) {
  26006. this.checkReadyOnEveryCall = false;
  26007. this.checkReadyOnlyOnce = false;
  26008. this.state = "";
  26009. this.alpha = 1.0;
  26010. this.backFaceCulling = true;
  26011. this.doNotSerialize = false;
  26012. /**
  26013. * An event triggered when the material is disposed.
  26014. * @type {BABYLON.Observable}
  26015. */
  26016. this.onDisposeObservable = new BABYLON.Observable();
  26017. /**
  26018. * An event triggered when the material is bound.
  26019. * @type {BABYLON.Observable}
  26020. */
  26021. this.onBindObservable = new BABYLON.Observable();
  26022. /**
  26023. * An event triggered when the material is unbound.
  26024. * @type {BABYLON.Observable}
  26025. */
  26026. this.onUnBindObservable = new BABYLON.Observable();
  26027. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26028. this.disableDepthWrite = false;
  26029. this.fogEnabled = true;
  26030. this.pointSize = 1.0;
  26031. this.zOffset = 0;
  26032. this._wasPreviouslyReady = false;
  26033. this._fillMode = Material.TriangleFillMode;
  26034. this.name = name;
  26035. this.id = name;
  26036. this._scene = scene;
  26037. if (scene.useRightHandedSystem) {
  26038. this.sideOrientation = Material.ClockWiseSideOrientation;
  26039. }
  26040. else {
  26041. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26042. }
  26043. if (!doNotAdd) {
  26044. scene.materials.push(this);
  26045. }
  26046. }
  26047. Object.defineProperty(Material, "TriangleFillMode", {
  26048. get: function () {
  26049. return Material._TriangleFillMode;
  26050. },
  26051. enumerable: true,
  26052. configurable: true
  26053. });
  26054. Object.defineProperty(Material, "WireFrameFillMode", {
  26055. get: function () {
  26056. return Material._WireFrameFillMode;
  26057. },
  26058. enumerable: true,
  26059. configurable: true
  26060. });
  26061. Object.defineProperty(Material, "PointFillMode", {
  26062. get: function () {
  26063. return Material._PointFillMode;
  26064. },
  26065. enumerable: true,
  26066. configurable: true
  26067. });
  26068. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26069. get: function () {
  26070. return Material._ClockWiseSideOrientation;
  26071. },
  26072. enumerable: true,
  26073. configurable: true
  26074. });
  26075. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26076. get: function () {
  26077. return Material._CounterClockWiseSideOrientation;
  26078. },
  26079. enumerable: true,
  26080. configurable: true
  26081. });
  26082. Object.defineProperty(Material.prototype, "onDispose", {
  26083. set: function (callback) {
  26084. if (this._onDisposeObserver) {
  26085. this.onDisposeObservable.remove(this._onDisposeObserver);
  26086. }
  26087. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26088. },
  26089. enumerable: true,
  26090. configurable: true
  26091. });
  26092. Object.defineProperty(Material.prototype, "onBind", {
  26093. set: function (callback) {
  26094. if (this._onBindObserver) {
  26095. this.onBindObservable.remove(this._onBindObserver);
  26096. }
  26097. this._onBindObserver = this.onBindObservable.add(callback);
  26098. },
  26099. enumerable: true,
  26100. configurable: true
  26101. });
  26102. Object.defineProperty(Material.prototype, "wireframe", {
  26103. get: function () {
  26104. return this._fillMode === Material.WireFrameFillMode;
  26105. },
  26106. set: function (value) {
  26107. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26108. },
  26109. enumerable: true,
  26110. configurable: true
  26111. });
  26112. Object.defineProperty(Material.prototype, "pointsCloud", {
  26113. get: function () {
  26114. return this._fillMode === Material.PointFillMode;
  26115. },
  26116. set: function (value) {
  26117. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26118. },
  26119. enumerable: true,
  26120. configurable: true
  26121. });
  26122. Object.defineProperty(Material.prototype, "fillMode", {
  26123. get: function () {
  26124. return this._fillMode;
  26125. },
  26126. set: function (value) {
  26127. this._fillMode = value;
  26128. },
  26129. enumerable: true,
  26130. configurable: true
  26131. });
  26132. /**
  26133. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26134. * subclasses should override adding information pertainent to themselves
  26135. */
  26136. Material.prototype.toString = function (fullDetails) {
  26137. var ret = "Name: " + this.name;
  26138. if (fullDetails) {
  26139. }
  26140. return ret;
  26141. };
  26142. Material.prototype.getClassName = function () {
  26143. return "Material";
  26144. };
  26145. Object.defineProperty(Material.prototype, "isFrozen", {
  26146. get: function () {
  26147. return this.checkReadyOnlyOnce;
  26148. },
  26149. enumerable: true,
  26150. configurable: true
  26151. });
  26152. Material.prototype.freeze = function () {
  26153. this.checkReadyOnlyOnce = true;
  26154. };
  26155. Material.prototype.unfreeze = function () {
  26156. this.checkReadyOnlyOnce = false;
  26157. };
  26158. Material.prototype.isReady = function (mesh, useInstances) {
  26159. return true;
  26160. };
  26161. Material.prototype.getEffect = function () {
  26162. return this._effect;
  26163. };
  26164. Material.prototype.getScene = function () {
  26165. return this._scene;
  26166. };
  26167. Material.prototype.needAlphaBlending = function () {
  26168. return (this.alpha < 1.0);
  26169. };
  26170. Material.prototype.needAlphaTesting = function () {
  26171. return false;
  26172. };
  26173. Material.prototype.getAlphaTestTexture = function () {
  26174. return null;
  26175. };
  26176. Material.prototype.markDirty = function () {
  26177. this._wasPreviouslyReady = false;
  26178. };
  26179. Material.prototype._preBind = function () {
  26180. var engine = this._scene.getEngine();
  26181. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26182. engine.enableEffect(this._effect);
  26183. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26184. };
  26185. Material.prototype.bind = function (world, mesh) {
  26186. this._scene._cachedMaterial = this;
  26187. this.onBindObservable.notifyObservers(mesh);
  26188. if (this.disableDepthWrite) {
  26189. var engine = this._scene.getEngine();
  26190. this._cachedDepthWriteState = engine.getDepthWrite();
  26191. engine.setDepthWrite(false);
  26192. }
  26193. };
  26194. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26195. };
  26196. Material.prototype.unbind = function () {
  26197. this.onUnBindObservable.notifyObservers(this);
  26198. if (this.disableDepthWrite) {
  26199. var engine = this._scene.getEngine();
  26200. engine.setDepthWrite(this._cachedDepthWriteState);
  26201. }
  26202. };
  26203. Material.prototype.clone = function (name) {
  26204. return null;
  26205. };
  26206. Material.prototype.getBindedMeshes = function () {
  26207. var result = new Array();
  26208. for (var index = 0; index < this._scene.meshes.length; index++) {
  26209. var mesh = this._scene.meshes[index];
  26210. if (mesh.material === this) {
  26211. result.push(mesh);
  26212. }
  26213. }
  26214. return result;
  26215. };
  26216. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26217. // Animations
  26218. this.getScene().stopAnimation(this);
  26219. // Remove from scene
  26220. var index = this._scene.materials.indexOf(this);
  26221. if (index >= 0) {
  26222. this._scene.materials.splice(index, 1);
  26223. }
  26224. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26225. if (forceDisposeEffect && this._effect) {
  26226. this._scene.getEngine()._releaseEffect(this._effect);
  26227. this._effect = null;
  26228. }
  26229. // Remove from meshes
  26230. for (index = 0; index < this._scene.meshes.length; index++) {
  26231. var mesh = this._scene.meshes[index];
  26232. if (mesh.material === this) {
  26233. mesh.material = null;
  26234. }
  26235. }
  26236. // Callback
  26237. this.onDisposeObservable.notifyObservers(this);
  26238. this.onDisposeObservable.clear();
  26239. this.onBindObservable.clear();
  26240. this.onUnBindObservable.clear();
  26241. };
  26242. Material.prototype.serialize = function () {
  26243. return BABYLON.SerializationHelper.Serialize(this);
  26244. };
  26245. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26246. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26247. multiMaterial.id = parsedMultiMaterial.id;
  26248. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26249. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26250. var subMatId = parsedMultiMaterial.materials[matIndex];
  26251. if (subMatId) {
  26252. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26253. }
  26254. else {
  26255. multiMaterial.subMaterials.push(null);
  26256. }
  26257. }
  26258. return multiMaterial;
  26259. };
  26260. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26261. if (!parsedMaterial.customType) {
  26262. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26263. }
  26264. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26265. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26266. ;
  26267. };
  26268. return Material;
  26269. }());
  26270. Material._TriangleFillMode = 0;
  26271. Material._WireFrameFillMode = 1;
  26272. Material._PointFillMode = 2;
  26273. Material._ClockWiseSideOrientation = 0;
  26274. Material._CounterClockWiseSideOrientation = 1;
  26275. __decorate([
  26276. BABYLON.serialize()
  26277. ], Material.prototype, "id", void 0);
  26278. __decorate([
  26279. BABYLON.serialize()
  26280. ], Material.prototype, "name", void 0);
  26281. __decorate([
  26282. BABYLON.serialize()
  26283. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26284. __decorate([
  26285. BABYLON.serialize()
  26286. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26287. __decorate([
  26288. BABYLON.serialize()
  26289. ], Material.prototype, "state", void 0);
  26290. __decorate([
  26291. BABYLON.serialize()
  26292. ], Material.prototype, "alpha", void 0);
  26293. __decorate([
  26294. BABYLON.serialize()
  26295. ], Material.prototype, "backFaceCulling", void 0);
  26296. __decorate([
  26297. BABYLON.serialize()
  26298. ], Material.prototype, "sideOrientation", void 0);
  26299. __decorate([
  26300. BABYLON.serialize()
  26301. ], Material.prototype, "alphaMode", void 0);
  26302. __decorate([
  26303. BABYLON.serialize()
  26304. ], Material.prototype, "disableDepthWrite", void 0);
  26305. __decorate([
  26306. BABYLON.serialize()
  26307. ], Material.prototype, "fogEnabled", void 0);
  26308. __decorate([
  26309. BABYLON.serialize()
  26310. ], Material.prototype, "pointSize", void 0);
  26311. __decorate([
  26312. BABYLON.serialize()
  26313. ], Material.prototype, "zOffset", void 0);
  26314. __decorate([
  26315. BABYLON.serialize()
  26316. ], Material.prototype, "wireframe", null);
  26317. __decorate([
  26318. BABYLON.serialize()
  26319. ], Material.prototype, "pointsCloud", null);
  26320. __decorate([
  26321. BABYLON.serialize()
  26322. ], Material.prototype, "fillMode", null);
  26323. BABYLON.Material = Material;
  26324. })(BABYLON || (BABYLON = {}));
  26325. //# sourceMappingURL=babylon.material.js.map
  26326. var BABYLON;
  26327. (function (BABYLON) {
  26328. var StandardMaterialDefines = (function (_super) {
  26329. __extends(StandardMaterialDefines, _super);
  26330. function StandardMaterialDefines() {
  26331. var _this = _super.call(this) || this;
  26332. _this.DIFFUSE = false;
  26333. _this.AMBIENT = false;
  26334. _this.OPACITY = false;
  26335. _this.OPACITYRGB = false;
  26336. _this.REFLECTION = false;
  26337. _this.EMISSIVE = false;
  26338. _this.SPECULAR = false;
  26339. _this.BUMP = false;
  26340. _this.PARALLAX = false;
  26341. _this.PARALLAXOCCLUSION = false;
  26342. _this.SPECULAROVERALPHA = false;
  26343. _this.CLIPPLANE = false;
  26344. _this.ALPHATEST = false;
  26345. _this.ALPHAFROMDIFFUSE = false;
  26346. _this.POINTSIZE = false;
  26347. _this.FOG = false;
  26348. _this.SPECULARTERM = false;
  26349. _this.DIFFUSEFRESNEL = false;
  26350. _this.OPACITYFRESNEL = false;
  26351. _this.REFLECTIONFRESNEL = false;
  26352. _this.REFRACTIONFRESNEL = false;
  26353. _this.EMISSIVEFRESNEL = false;
  26354. _this.FRESNEL = false;
  26355. _this.NORMAL = false;
  26356. _this.UV1 = false;
  26357. _this.UV2 = false;
  26358. _this.VERTEXCOLOR = false;
  26359. _this.VERTEXALPHA = false;
  26360. _this.NUM_BONE_INFLUENCERS = 0;
  26361. _this.BonesPerMesh = 0;
  26362. _this.INSTANCES = false;
  26363. _this.GLOSSINESS = false;
  26364. _this.ROUGHNESS = false;
  26365. _this.EMISSIVEASILLUMINATION = false;
  26366. _this.LINKEMISSIVEWITHDIFFUSE = false;
  26367. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  26368. _this.LIGHTMAP = false;
  26369. _this.USELIGHTMAPASSHADOWMAP = false;
  26370. _this.REFLECTIONMAP_3D = false;
  26371. _this.REFLECTIONMAP_SPHERICAL = false;
  26372. _this.REFLECTIONMAP_PLANAR = false;
  26373. _this.REFLECTIONMAP_CUBIC = false;
  26374. _this.REFLECTIONMAP_PROJECTION = false;
  26375. _this.REFLECTIONMAP_SKYBOX = false;
  26376. _this.REFLECTIONMAP_EXPLICIT = false;
  26377. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26378. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26379. _this.INVERTCUBICMAP = false;
  26380. _this.LOGARITHMICDEPTH = false;
  26381. _this.REFRACTION = false;
  26382. _this.REFRACTIONMAP_3D = false;
  26383. _this.REFLECTIONOVERALPHA = false;
  26384. _this.INVERTNORMALMAPX = false;
  26385. _this.INVERTNORMALMAPY = false;
  26386. _this.SHADOWFULLFLOAT = false;
  26387. _this.CAMERACOLORGRADING = false;
  26388. _this.CAMERACOLORCURVES = false;
  26389. _this.rebuild();
  26390. return _this;
  26391. }
  26392. return StandardMaterialDefines;
  26393. }(BABYLON.MaterialDefines));
  26394. var StandardMaterial = (function (_super) {
  26395. __extends(StandardMaterial, _super);
  26396. function StandardMaterial(name, scene) {
  26397. var _this = _super.call(this, name, scene) || this;
  26398. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26399. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26400. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  26401. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26402. _this.specularPower = 64;
  26403. _this.useAlphaFromDiffuseTexture = false;
  26404. _this.useEmissiveAsIllumination = false;
  26405. _this.linkEmissiveWithDiffuse = false;
  26406. _this.useReflectionFresnelFromSpecular = false;
  26407. _this.useSpecularOverAlpha = false;
  26408. _this.useReflectionOverAlpha = false;
  26409. _this.disableLighting = false;
  26410. _this.useParallax = false;
  26411. _this.useParallaxOcclusion = false;
  26412. _this.parallaxScaleBias = 0.05;
  26413. _this.roughness = 0;
  26414. _this.indexOfRefraction = 0.98;
  26415. _this.invertRefractionY = true;
  26416. _this.useLightmapAsShadowmap = false;
  26417. _this.useGlossinessFromSpecularMapAlpha = false;
  26418. _this.maxSimultaneousLights = 4;
  26419. /**
  26420. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26421. */
  26422. _this.invertNormalMapX = false;
  26423. /**
  26424. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26425. */
  26426. _this.invertNormalMapY = false;
  26427. /**
  26428. * Color Grading 2D Lookup Texture.
  26429. * This allows special effects like sepia, black and white to sixties rendering style.
  26430. */
  26431. _this.cameraColorGradingTexture = null;
  26432. /**
  26433. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26434. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26435. * 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;
  26436. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26437. */
  26438. _this.cameraColorCurves = null;
  26439. _this._renderTargets = new BABYLON.SmartArray(16);
  26440. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26441. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26442. _this._defines = new StandardMaterialDefines();
  26443. _this._cachedDefines = new StandardMaterialDefines();
  26444. _this._cachedDefines.BonesPerMesh = -1;
  26445. _this.getRenderTargetTextures = function () {
  26446. _this._renderTargets.reset();
  26447. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26448. _this._renderTargets.push(_this.reflectionTexture);
  26449. }
  26450. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26451. _this._renderTargets.push(_this.refractionTexture);
  26452. }
  26453. return _this._renderTargets;
  26454. };
  26455. return _this;
  26456. }
  26457. StandardMaterial.prototype.getClassName = function () {
  26458. return "StandardMaterial";
  26459. };
  26460. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26461. get: function () {
  26462. return this._useLogarithmicDepth;
  26463. },
  26464. set: function (value) {
  26465. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26466. },
  26467. enumerable: true,
  26468. configurable: true
  26469. });
  26470. StandardMaterial.prototype.needAlphaBlending = function () {
  26471. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26472. };
  26473. StandardMaterial.prototype.needAlphaTesting = function () {
  26474. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26475. };
  26476. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26477. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26478. };
  26479. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26480. return this.diffuseTexture;
  26481. };
  26482. // Methods
  26483. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26484. if (!mesh) {
  26485. return true;
  26486. }
  26487. if (this._defines.INSTANCES !== useInstances) {
  26488. return false;
  26489. }
  26490. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26491. return true;
  26492. }
  26493. return false;
  26494. };
  26495. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26496. if (this.isFrozen) {
  26497. if (this._wasPreviouslyReady) {
  26498. return true;
  26499. }
  26500. }
  26501. var scene = this.getScene();
  26502. var engine = scene.getEngine();
  26503. var needUVs = false;
  26504. var needNormals = false;
  26505. this._defines.reset();
  26506. // Lights
  26507. if (scene.lightsEnabled && !this.disableLighting) {
  26508. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26509. }
  26510. if (!this.checkReadyOnEveryCall) {
  26511. if (this._renderId === scene.getRenderId()) {
  26512. if (this._checkCache(scene, mesh, useInstances)) {
  26513. return true;
  26514. }
  26515. }
  26516. }
  26517. // Textures
  26518. if (scene.texturesEnabled) {
  26519. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26520. if (!this.diffuseTexture.isReady()) {
  26521. return false;
  26522. }
  26523. else {
  26524. needUVs = true;
  26525. this._defines.DIFFUSE = true;
  26526. }
  26527. }
  26528. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26529. if (!this.ambientTexture.isReady()) {
  26530. return false;
  26531. }
  26532. else {
  26533. needUVs = true;
  26534. this._defines.AMBIENT = true;
  26535. }
  26536. }
  26537. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26538. if (!this.opacityTexture.isReady()) {
  26539. return false;
  26540. }
  26541. else {
  26542. needUVs = true;
  26543. this._defines.OPACITY = true;
  26544. if (this.opacityTexture.getAlphaFromRGB) {
  26545. this._defines.OPACITYRGB = true;
  26546. }
  26547. }
  26548. }
  26549. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26550. if (!this.reflectionTexture.isReady()) {
  26551. return false;
  26552. }
  26553. else {
  26554. needNormals = true;
  26555. this._defines.REFLECTION = true;
  26556. if (this.roughness > 0) {
  26557. this._defines.ROUGHNESS = true;
  26558. }
  26559. if (this.useReflectionOverAlpha) {
  26560. this._defines.REFLECTIONOVERALPHA = true;
  26561. }
  26562. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26563. this._defines.INVERTCUBICMAP = true;
  26564. }
  26565. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26566. switch (this.reflectionTexture.coordinatesMode) {
  26567. case BABYLON.Texture.CUBIC_MODE:
  26568. case BABYLON.Texture.INVCUBIC_MODE:
  26569. this._defines.REFLECTIONMAP_CUBIC = true;
  26570. break;
  26571. case BABYLON.Texture.EXPLICIT_MODE:
  26572. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26573. break;
  26574. case BABYLON.Texture.PLANAR_MODE:
  26575. this._defines.REFLECTIONMAP_PLANAR = true;
  26576. break;
  26577. case BABYLON.Texture.PROJECTION_MODE:
  26578. this._defines.REFLECTIONMAP_PROJECTION = true;
  26579. break;
  26580. case BABYLON.Texture.SKYBOX_MODE:
  26581. this._defines.REFLECTIONMAP_SKYBOX = true;
  26582. break;
  26583. case BABYLON.Texture.SPHERICAL_MODE:
  26584. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26585. break;
  26586. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26587. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26588. break;
  26589. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26590. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26591. break;
  26592. }
  26593. }
  26594. }
  26595. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26596. if (!this.emissiveTexture.isReady()) {
  26597. return false;
  26598. }
  26599. else {
  26600. needUVs = true;
  26601. this._defines.EMISSIVE = true;
  26602. }
  26603. }
  26604. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26605. if (!this.lightmapTexture.isReady()) {
  26606. return false;
  26607. }
  26608. else {
  26609. needUVs = true;
  26610. this._defines.LIGHTMAP = true;
  26611. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26612. }
  26613. }
  26614. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26615. if (!this.specularTexture.isReady()) {
  26616. return false;
  26617. }
  26618. else {
  26619. needUVs = true;
  26620. this._defines.SPECULAR = true;
  26621. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26622. }
  26623. }
  26624. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26625. if (!this.bumpTexture.isReady()) {
  26626. return false;
  26627. }
  26628. else {
  26629. needUVs = true;
  26630. this._defines.BUMP = true;
  26631. if (this.useParallax) {
  26632. this._defines.PARALLAX = true;
  26633. if (this.useParallaxOcclusion) {
  26634. this._defines.PARALLAXOCCLUSION = true;
  26635. }
  26636. }
  26637. if (this.invertNormalMapX) {
  26638. this._defines.INVERTNORMALMAPX = true;
  26639. }
  26640. if (this.invertNormalMapY) {
  26641. this._defines.INVERTNORMALMAPY = true;
  26642. }
  26643. }
  26644. }
  26645. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26646. if (!this.refractionTexture.isReady()) {
  26647. return false;
  26648. }
  26649. else {
  26650. needUVs = true;
  26651. this._defines.REFRACTION = true;
  26652. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26653. }
  26654. }
  26655. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26656. if (!this.cameraColorGradingTexture.isReady()) {
  26657. return false;
  26658. }
  26659. else {
  26660. this._defines.CAMERACOLORGRADING = true;
  26661. }
  26662. }
  26663. }
  26664. // Effect
  26665. if (scene.clipPlane) {
  26666. this._defines.CLIPPLANE = true;
  26667. }
  26668. if (engine.getAlphaTesting()) {
  26669. this._defines.ALPHATEST = true;
  26670. }
  26671. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26672. this._defines.ALPHAFROMDIFFUSE = true;
  26673. }
  26674. if (this.useEmissiveAsIllumination) {
  26675. this._defines.EMISSIVEASILLUMINATION = true;
  26676. }
  26677. if (this.linkEmissiveWithDiffuse) {
  26678. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26679. }
  26680. if (this.useLogarithmicDepth) {
  26681. this._defines.LOGARITHMICDEPTH = true;
  26682. }
  26683. if (this.cameraColorCurves) {
  26684. this._defines.CAMERACOLORCURVES = true;
  26685. }
  26686. // Point size
  26687. if (this.pointsCloud || scene.forcePointsCloud) {
  26688. this._defines.POINTSIZE = true;
  26689. }
  26690. // Fog
  26691. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26692. this._defines.FOG = true;
  26693. }
  26694. if (StandardMaterial.FresnelEnabled) {
  26695. // Fresnel
  26696. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26697. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26698. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26699. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26700. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26701. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26702. this._defines.DIFFUSEFRESNEL = true;
  26703. }
  26704. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26705. this._defines.OPACITYFRESNEL = true;
  26706. }
  26707. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26708. this._defines.REFLECTIONFRESNEL = true;
  26709. if (this.useReflectionFresnelFromSpecular) {
  26710. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26711. }
  26712. }
  26713. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26714. this._defines.REFRACTIONFRESNEL = true;
  26715. }
  26716. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26717. this._defines.EMISSIVEFRESNEL = true;
  26718. }
  26719. needNormals = true;
  26720. this._defines.FRESNEL = true;
  26721. }
  26722. }
  26723. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26724. this._defines.SPECULAROVERALPHA = true;
  26725. }
  26726. // Attribs
  26727. if (mesh) {
  26728. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26729. this._defines.NORMAL = true;
  26730. }
  26731. if (needUVs) {
  26732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26733. this._defines.UV1 = true;
  26734. }
  26735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26736. this._defines.UV2 = true;
  26737. }
  26738. }
  26739. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26740. this._defines.VERTEXCOLOR = true;
  26741. if (mesh.hasVertexAlpha) {
  26742. this._defines.VERTEXALPHA = true;
  26743. }
  26744. }
  26745. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26746. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26747. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26748. }
  26749. // Instances
  26750. if (useInstances) {
  26751. this._defines.INSTANCES = true;
  26752. }
  26753. }
  26754. // Get correct effect
  26755. if (!this._defines.isEqual(this._cachedDefines)) {
  26756. this._defines.cloneTo(this._cachedDefines);
  26757. scene.resetCachedMaterial();
  26758. // Fallbacks
  26759. var fallbacks = new BABYLON.EffectFallbacks();
  26760. if (this._defines.REFLECTION) {
  26761. fallbacks.addFallback(0, "REFLECTION");
  26762. }
  26763. if (this._defines.SPECULAR) {
  26764. fallbacks.addFallback(0, "SPECULAR");
  26765. }
  26766. if (this._defines.BUMP) {
  26767. fallbacks.addFallback(0, "BUMP");
  26768. }
  26769. if (this._defines.PARALLAX) {
  26770. fallbacks.addFallback(1, "PARALLAX");
  26771. }
  26772. if (this._defines.PARALLAXOCCLUSION) {
  26773. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26774. }
  26775. if (this._defines.SPECULAROVERALPHA) {
  26776. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26777. }
  26778. if (this._defines.FOG) {
  26779. fallbacks.addFallback(1, "FOG");
  26780. }
  26781. if (this._defines.POINTSIZE) {
  26782. fallbacks.addFallback(0, "POINTSIZE");
  26783. }
  26784. if (this._defines.LOGARITHMICDEPTH) {
  26785. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26786. }
  26787. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26788. if (this._defines.SPECULARTERM) {
  26789. fallbacks.addFallback(0, "SPECULARTERM");
  26790. }
  26791. if (this._defines.DIFFUSEFRESNEL) {
  26792. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26793. }
  26794. if (this._defines.OPACITYFRESNEL) {
  26795. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26796. }
  26797. if (this._defines.REFLECTIONFRESNEL) {
  26798. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26799. }
  26800. if (this._defines.EMISSIVEFRESNEL) {
  26801. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26802. }
  26803. if (this._defines.FRESNEL) {
  26804. fallbacks.addFallback(4, "FRESNEL");
  26805. }
  26806. //Attributes
  26807. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26808. if (this._defines.NORMAL) {
  26809. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26810. }
  26811. if (this._defines.UV1) {
  26812. attribs.push(BABYLON.VertexBuffer.UVKind);
  26813. }
  26814. if (this._defines.UV2) {
  26815. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26816. }
  26817. if (this._defines.VERTEXCOLOR) {
  26818. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26819. }
  26820. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26821. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26822. var shaderName = "default";
  26823. var join = this._defines.toString();
  26824. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26825. "vFogInfos", "vFogColor", "pointSize",
  26826. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26827. "mBones",
  26828. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26829. "depthValues",
  26830. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26831. "logarithmicDepthConstant"
  26832. ];
  26833. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26834. if (this._defines.CAMERACOLORCURVES) {
  26835. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26836. }
  26837. if (this._defines.CAMERACOLORGRADING) {
  26838. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26839. }
  26840. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26841. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26842. }
  26843. if (!this._effect.isReady()) {
  26844. return false;
  26845. }
  26846. this._renderId = scene.getRenderId();
  26847. this._wasPreviouslyReady = true;
  26848. if (mesh) {
  26849. if (!mesh._materialDefines) {
  26850. mesh._materialDefines = new StandardMaterialDefines();
  26851. }
  26852. this._defines.cloneTo(mesh._materialDefines);
  26853. }
  26854. return true;
  26855. };
  26856. StandardMaterial.prototype.unbind = function () {
  26857. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26858. this._effect.setTexture("reflection2DSampler", null);
  26859. }
  26860. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26861. this._effect.setTexture("refraction2DSampler", null);
  26862. }
  26863. _super.prototype.unbind.call(this);
  26864. };
  26865. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26866. this._effect.setMatrix("world", world);
  26867. };
  26868. StandardMaterial.prototype.bind = function (world, mesh) {
  26869. var scene = this.getScene();
  26870. // Matrices
  26871. this.bindOnlyWorldMatrix(world);
  26872. // Bones
  26873. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26874. if (scene.getCachedMaterial() !== this) {
  26875. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26876. if (StandardMaterial.FresnelEnabled) {
  26877. // Fresnel
  26878. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26879. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26880. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26881. }
  26882. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26883. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26884. }
  26885. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26886. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26887. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26888. }
  26889. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26890. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26891. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26892. }
  26893. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26894. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26895. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26896. }
  26897. }
  26898. // Textures
  26899. if (scene.texturesEnabled) {
  26900. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26901. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26902. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26903. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26904. }
  26905. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26906. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26907. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26908. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26909. }
  26910. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26911. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26912. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26913. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26914. }
  26915. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26916. if (this.reflectionTexture.isCube) {
  26917. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26918. }
  26919. else {
  26920. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26921. }
  26922. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26923. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26924. }
  26925. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26926. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26927. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26928. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26929. }
  26930. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26931. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26932. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26933. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26934. }
  26935. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26936. this._effect.setTexture("specularSampler", this.specularTexture);
  26937. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26938. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26939. }
  26940. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26941. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26942. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26943. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26944. }
  26945. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26946. var depth = 1.0;
  26947. if (this.refractionTexture.isCube) {
  26948. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26949. }
  26950. else {
  26951. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26952. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26953. if (this.refractionTexture.depth) {
  26954. depth = this.refractionTexture.depth;
  26955. }
  26956. }
  26957. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26958. }
  26959. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26960. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26961. }
  26962. }
  26963. // Clip plane
  26964. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26965. // Point size
  26966. if (this.pointsCloud) {
  26967. this._effect.setFloat("pointSize", this.pointSize);
  26968. }
  26969. // Colors
  26970. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26971. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26972. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26973. if (this._defines.SPECULARTERM) {
  26974. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26975. }
  26976. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26977. }
  26978. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26979. // Diffuse
  26980. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26981. // Lights
  26982. if (scene.lightsEnabled && !this.disableLighting) {
  26983. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26984. }
  26985. // View
  26986. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26987. this._effect.setMatrix("view", scene.getViewMatrix());
  26988. }
  26989. // Fog
  26990. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26991. // Log. depth
  26992. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26993. // Color Curves
  26994. if (this.cameraColorCurves) {
  26995. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26996. }
  26997. }
  26998. _super.prototype.bind.call(this, world, mesh);
  26999. };
  27000. StandardMaterial.prototype.getAnimatables = function () {
  27001. var results = [];
  27002. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27003. results.push(this.diffuseTexture);
  27004. }
  27005. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27006. results.push(this.ambientTexture);
  27007. }
  27008. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27009. results.push(this.opacityTexture);
  27010. }
  27011. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27012. results.push(this.reflectionTexture);
  27013. }
  27014. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27015. results.push(this.emissiveTexture);
  27016. }
  27017. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27018. results.push(this.specularTexture);
  27019. }
  27020. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27021. results.push(this.bumpTexture);
  27022. }
  27023. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27024. results.push(this.lightmapTexture);
  27025. }
  27026. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27027. results.push(this.refractionTexture);
  27028. }
  27029. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27030. results.push(this.cameraColorGradingTexture);
  27031. }
  27032. return results;
  27033. };
  27034. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27035. if (forceDisposeTextures) {
  27036. if (this.diffuseTexture) {
  27037. this.diffuseTexture.dispose();
  27038. }
  27039. if (this.ambientTexture) {
  27040. this.ambientTexture.dispose();
  27041. }
  27042. if (this.opacityTexture) {
  27043. this.opacityTexture.dispose();
  27044. }
  27045. if (this.reflectionTexture) {
  27046. this.reflectionTexture.dispose();
  27047. }
  27048. if (this.emissiveTexture) {
  27049. this.emissiveTexture.dispose();
  27050. }
  27051. if (this.specularTexture) {
  27052. this.specularTexture.dispose();
  27053. }
  27054. if (this.bumpTexture) {
  27055. this.bumpTexture.dispose();
  27056. }
  27057. if (this.lightmapTexture) {
  27058. this.lightmapTexture.dispose();
  27059. }
  27060. if (this.refractionTexture) {
  27061. this.refractionTexture.dispose();
  27062. }
  27063. if (this.cameraColorGradingTexture) {
  27064. this.cameraColorGradingTexture.dispose();
  27065. }
  27066. }
  27067. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27068. };
  27069. StandardMaterial.prototype.clone = function (name) {
  27070. var _this = this;
  27071. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27072. };
  27073. StandardMaterial.prototype.serialize = function () {
  27074. return BABYLON.SerializationHelper.Serialize(this);
  27075. };
  27076. // Statics
  27077. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27078. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27079. };
  27080. return StandardMaterial;
  27081. }(BABYLON.Material));
  27082. // Flags used to enable or disable a type of texture for all Standard Materials
  27083. StandardMaterial.DiffuseTextureEnabled = true;
  27084. StandardMaterial.AmbientTextureEnabled = true;
  27085. StandardMaterial.OpacityTextureEnabled = true;
  27086. StandardMaterial.ReflectionTextureEnabled = true;
  27087. StandardMaterial.EmissiveTextureEnabled = true;
  27088. StandardMaterial.SpecularTextureEnabled = true;
  27089. StandardMaterial.BumpTextureEnabled = true;
  27090. StandardMaterial.FresnelEnabled = true;
  27091. StandardMaterial.LightmapTextureEnabled = true;
  27092. StandardMaterial.RefractionTextureEnabled = true;
  27093. StandardMaterial.ColorGradingTextureEnabled = true;
  27094. __decorate([
  27095. BABYLON.serializeAsTexture()
  27096. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27097. __decorate([
  27098. BABYLON.serializeAsTexture()
  27099. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27100. __decorate([
  27101. BABYLON.serializeAsTexture()
  27102. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27103. __decorate([
  27104. BABYLON.serializeAsTexture()
  27105. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27106. __decorate([
  27107. BABYLON.serializeAsTexture()
  27108. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27109. __decorate([
  27110. BABYLON.serializeAsTexture()
  27111. ], StandardMaterial.prototype, "specularTexture", void 0);
  27112. __decorate([
  27113. BABYLON.serializeAsTexture()
  27114. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27115. __decorate([
  27116. BABYLON.serializeAsTexture()
  27117. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27118. __decorate([
  27119. BABYLON.serializeAsTexture()
  27120. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27121. __decorate([
  27122. BABYLON.serializeAsColor3("ambient")
  27123. ], StandardMaterial.prototype, "ambientColor", void 0);
  27124. __decorate([
  27125. BABYLON.serializeAsColor3("diffuse")
  27126. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27127. __decorate([
  27128. BABYLON.serializeAsColor3("specular")
  27129. ], StandardMaterial.prototype, "specularColor", void 0);
  27130. __decorate([
  27131. BABYLON.serializeAsColor3("emissive")
  27132. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27133. __decorate([
  27134. BABYLON.serialize()
  27135. ], StandardMaterial.prototype, "specularPower", void 0);
  27136. __decorate([
  27137. BABYLON.serialize()
  27138. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27139. __decorate([
  27140. BABYLON.serialize()
  27141. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27142. __decorate([
  27143. BABYLON.serialize()
  27144. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27145. __decorate([
  27146. BABYLON.serialize()
  27147. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27148. __decorate([
  27149. BABYLON.serialize()
  27150. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27151. __decorate([
  27152. BABYLON.serialize()
  27153. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27154. __decorate([
  27155. BABYLON.serialize()
  27156. ], StandardMaterial.prototype, "disableLighting", void 0);
  27157. __decorate([
  27158. BABYLON.serialize()
  27159. ], StandardMaterial.prototype, "useParallax", void 0);
  27160. __decorate([
  27161. BABYLON.serialize()
  27162. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27163. __decorate([
  27164. BABYLON.serialize()
  27165. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27166. __decorate([
  27167. BABYLON.serialize()
  27168. ], StandardMaterial.prototype, "roughness", void 0);
  27169. __decorate([
  27170. BABYLON.serialize()
  27171. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27172. __decorate([
  27173. BABYLON.serialize()
  27174. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27175. __decorate([
  27176. BABYLON.serialize()
  27177. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27178. __decorate([
  27179. BABYLON.serializeAsFresnelParameters()
  27180. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27181. __decorate([
  27182. BABYLON.serializeAsFresnelParameters()
  27183. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27184. __decorate([
  27185. BABYLON.serializeAsFresnelParameters()
  27186. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27187. __decorate([
  27188. BABYLON.serializeAsFresnelParameters()
  27189. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27190. __decorate([
  27191. BABYLON.serializeAsFresnelParameters()
  27192. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27193. __decorate([
  27194. BABYLON.serialize()
  27195. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27199. __decorate([
  27200. BABYLON.serialize()
  27201. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27205. __decorate([
  27206. BABYLON.serializeAsTexture()
  27207. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27208. __decorate([
  27209. BABYLON.serializeAsColorCurves()
  27210. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27211. __decorate([
  27212. BABYLON.serialize()
  27213. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27214. BABYLON.StandardMaterial = StandardMaterial;
  27215. })(BABYLON || (BABYLON = {}));
  27216. //# sourceMappingURL=babylon.standardMaterial.js.map
  27217. var BABYLON;
  27218. (function (BABYLON) {
  27219. var MultiMaterial = (function (_super) {
  27220. __extends(MultiMaterial, _super);
  27221. function MultiMaterial(name, scene) {
  27222. var _this = _super.call(this, name, scene, true) || this;
  27223. _this.subMaterials = new Array();
  27224. scene.multiMaterials.push(_this);
  27225. return _this;
  27226. }
  27227. // Properties
  27228. MultiMaterial.prototype.getSubMaterial = function (index) {
  27229. if (index < 0 || index >= this.subMaterials.length) {
  27230. return this.getScene().defaultMaterial;
  27231. }
  27232. return this.subMaterials[index];
  27233. };
  27234. // Methods
  27235. MultiMaterial.prototype.getClassName = function () {
  27236. return "MultiMaterial";
  27237. };
  27238. MultiMaterial.prototype.isReady = function (mesh) {
  27239. for (var index = 0; index < this.subMaterials.length; index++) {
  27240. var subMaterial = this.subMaterials[index];
  27241. if (subMaterial) {
  27242. if (!this.subMaterials[index].isReady(mesh)) {
  27243. return false;
  27244. }
  27245. }
  27246. }
  27247. return true;
  27248. };
  27249. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27250. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27251. for (var index = 0; index < this.subMaterials.length; index++) {
  27252. var subMaterial = null;
  27253. if (cloneChildren) {
  27254. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27255. }
  27256. else {
  27257. subMaterial = this.subMaterials[index];
  27258. }
  27259. newMultiMaterial.subMaterials.push(subMaterial);
  27260. }
  27261. return newMultiMaterial;
  27262. };
  27263. MultiMaterial.prototype.serialize = function () {
  27264. var serializationObject = {};
  27265. serializationObject.name = this.name;
  27266. serializationObject.id = this.id;
  27267. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27268. serializationObject.materials = [];
  27269. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27270. var subMat = this.subMaterials[matIndex];
  27271. if (subMat) {
  27272. serializationObject.materials.push(subMat.id);
  27273. }
  27274. else {
  27275. serializationObject.materials.push(null);
  27276. }
  27277. }
  27278. return serializationObject;
  27279. };
  27280. return MultiMaterial;
  27281. }(BABYLON.Material));
  27282. BABYLON.MultiMaterial = MultiMaterial;
  27283. })(BABYLON || (BABYLON = {}));
  27284. //# sourceMappingURL=babylon.multiMaterial.js.map
  27285. var BABYLON;
  27286. (function (BABYLON) {
  27287. var SceneLoader = (function () {
  27288. function SceneLoader() {
  27289. }
  27290. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27291. get: function () {
  27292. return 0;
  27293. },
  27294. enumerable: true,
  27295. configurable: true
  27296. });
  27297. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27298. get: function () {
  27299. return 1;
  27300. },
  27301. enumerable: true,
  27302. configurable: true
  27303. });
  27304. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27305. get: function () {
  27306. return 2;
  27307. },
  27308. enumerable: true,
  27309. configurable: true
  27310. });
  27311. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27312. get: function () {
  27313. return 3;
  27314. },
  27315. enumerable: true,
  27316. configurable: true
  27317. });
  27318. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27319. get: function () {
  27320. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27321. },
  27322. set: function (value) {
  27323. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27324. },
  27325. enumerable: true,
  27326. configurable: true
  27327. });
  27328. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27329. get: function () {
  27330. return SceneLoader._ShowLoadingScreen;
  27331. },
  27332. set: function (value) {
  27333. SceneLoader._ShowLoadingScreen = value;
  27334. },
  27335. enumerable: true,
  27336. configurable: true
  27337. });
  27338. Object.defineProperty(SceneLoader, "loggingLevel", {
  27339. get: function () {
  27340. return SceneLoader._loggingLevel;
  27341. },
  27342. set: function (value) {
  27343. SceneLoader._loggingLevel = value;
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. SceneLoader._getDefaultPlugin = function () {
  27349. return SceneLoader._registeredPlugins[".babylon"];
  27350. };
  27351. SceneLoader._getPluginForExtension = function (extension) {
  27352. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27353. if (registeredPlugin) {
  27354. return registeredPlugin;
  27355. }
  27356. return SceneLoader._getDefaultPlugin();
  27357. };
  27358. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27359. if (sceneFilename.name) {
  27360. sceneFilename = sceneFilename.name;
  27361. }
  27362. var dotPosition = sceneFilename.lastIndexOf(".");
  27363. var queryStringPosition = sceneFilename.indexOf("?");
  27364. if (queryStringPosition === -1) {
  27365. queryStringPosition = sceneFilename.length;
  27366. }
  27367. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27368. return SceneLoader._getPluginForExtension(extension);
  27369. };
  27370. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27371. SceneLoader._getDirectLoad = function (sceneFilename) {
  27372. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27373. return sceneFilename.substr(5);
  27374. }
  27375. return null;
  27376. };
  27377. // Public functions
  27378. SceneLoader.GetPluginForExtension = function (extension) {
  27379. return SceneLoader._getPluginForExtension(extension).plugin;
  27380. };
  27381. SceneLoader.RegisterPlugin = function (plugin) {
  27382. if (typeof plugin.extensions === "string") {
  27383. var extension = plugin.extensions;
  27384. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27385. plugin: plugin,
  27386. isBinary: false
  27387. };
  27388. }
  27389. else {
  27390. var extensions = plugin.extensions;
  27391. Object.keys(extensions).forEach(function (extension) {
  27392. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27393. plugin: plugin,
  27394. isBinary: extensions[extension].isBinary
  27395. };
  27396. });
  27397. }
  27398. };
  27399. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27400. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27401. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27402. return;
  27403. }
  27404. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27405. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27406. return;
  27407. }
  27408. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27409. var loadingToken = {};
  27410. scene._addPendingData(loadingToken);
  27411. var manifestChecked = function (success) {
  27412. scene.database = database;
  27413. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27414. var plugin = registeredPlugin.plugin;
  27415. var useArrayBuffer = registeredPlugin.isBinary;
  27416. var importMeshFromData = function (data) {
  27417. var meshes = [];
  27418. var particleSystems = [];
  27419. var skeletons = [];
  27420. try {
  27421. if (plugin.importMesh) {
  27422. var syncedPlugin = plugin;
  27423. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27424. if (onerror) {
  27425. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27426. }
  27427. scene._removePendingData(loadingToken);
  27428. return;
  27429. }
  27430. if (onsuccess) {
  27431. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27432. onsuccess(meshes, particleSystems, skeletons);
  27433. scene._removePendingData(loadingToken);
  27434. }
  27435. }
  27436. else {
  27437. var asyncedPlugin = plugin;
  27438. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27439. if (onsuccess) {
  27440. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27441. onsuccess(meshes, particleSystems, skeletons);
  27442. scene._removePendingData(loadingToken);
  27443. }
  27444. }, function () {
  27445. if (onerror) {
  27446. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27447. }
  27448. scene._removePendingData(loadingToken);
  27449. });
  27450. }
  27451. }
  27452. catch (e) {
  27453. if (onerror) {
  27454. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27455. }
  27456. scene._removePendingData(loadingToken);
  27457. }
  27458. };
  27459. if (directLoad) {
  27460. importMeshFromData(directLoad);
  27461. return;
  27462. }
  27463. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27464. importMeshFromData(data);
  27465. }, progressCallBack, database, useArrayBuffer);
  27466. };
  27467. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27468. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27469. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27470. }
  27471. else {
  27472. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27473. manifestChecked(true);
  27474. }
  27475. };
  27476. /**
  27477. * Load a scene
  27478. * @param rootUrl a string that defines the root url for scene and resources
  27479. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27480. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27481. */
  27482. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27483. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27484. };
  27485. /**
  27486. * Append a scene
  27487. * @param rootUrl a string that defines the root url for scene and resources
  27488. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27489. * @param scene is the instance of BABYLON.Scene to append to
  27490. */
  27491. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27492. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27493. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27494. return;
  27495. }
  27496. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27497. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27498. var plugin = registeredPlugin.plugin;
  27499. var useArrayBuffer = registeredPlugin.isBinary;
  27500. var database;
  27501. var loadingToken = {};
  27502. scene._addPendingData(loadingToken);
  27503. if (SceneLoader.ShowLoadingScreen) {
  27504. scene.getEngine().displayLoadingUI();
  27505. }
  27506. var loadSceneFromData = function (data) {
  27507. scene.database = database;
  27508. if (plugin.load) {
  27509. var syncedPlugin = plugin;
  27510. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27511. if (onerror) {
  27512. onerror(scene);
  27513. }
  27514. scene._removePendingData(loadingToken);
  27515. scene.getEngine().hideLoadingUI();
  27516. return;
  27517. }
  27518. if (onsuccess) {
  27519. onsuccess(scene);
  27520. }
  27521. scene._removePendingData(loadingToken);
  27522. }
  27523. else {
  27524. var asyncedPlugin = plugin;
  27525. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27526. if (onsuccess) {
  27527. onsuccess(scene);
  27528. }
  27529. scene._removePendingData(loadingToken);
  27530. }, function () {
  27531. if (onerror) {
  27532. onerror(scene);
  27533. }
  27534. scene._removePendingData(loadingToken);
  27535. scene.getEngine().hideLoadingUI();
  27536. });
  27537. }
  27538. if (SceneLoader.ShowLoadingScreen) {
  27539. scene.executeWhenReady(function () {
  27540. scene.getEngine().hideLoadingUI();
  27541. });
  27542. }
  27543. };
  27544. var manifestChecked = function (success) {
  27545. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27546. };
  27547. if (directLoad) {
  27548. loadSceneFromData(directLoad);
  27549. return;
  27550. }
  27551. if (rootUrl.indexOf("file:") === -1) {
  27552. if (scene.getEngine().enableOfflineSupport) {
  27553. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27554. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27555. }
  27556. else {
  27557. manifestChecked(true);
  27558. }
  27559. }
  27560. else {
  27561. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27562. }
  27563. };
  27564. return SceneLoader;
  27565. }());
  27566. // Flags
  27567. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27568. SceneLoader._ShowLoadingScreen = true;
  27569. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27570. // Members
  27571. SceneLoader._registeredPlugins = {};
  27572. BABYLON.SceneLoader = SceneLoader;
  27573. ;
  27574. })(BABYLON || (BABYLON = {}));
  27575. //# sourceMappingURL=babylon.sceneLoader.js.map
  27576. var BABYLON;
  27577. (function (BABYLON) {
  27578. var Internals;
  27579. (function (Internals) {
  27580. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27581. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27582. var parsedMaterial = parsedData.materials[index];
  27583. if (parsedMaterial.id === id) {
  27584. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27585. }
  27586. }
  27587. return null;
  27588. };
  27589. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27590. names = (names instanceof Array) ? names : [names];
  27591. for (var i in names) {
  27592. if (mesh.name === names[i]) {
  27593. hierarchyIds.push(mesh.id);
  27594. return true;
  27595. }
  27596. }
  27597. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27598. hierarchyIds.push(mesh.id);
  27599. return true;
  27600. }
  27601. return false;
  27602. };
  27603. var logOperation = function (operation, producer) {
  27604. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27605. };
  27606. BABYLON.SceneLoader.RegisterPlugin({
  27607. extensions: ".babylon",
  27608. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27609. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27610. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27611. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27612. // and avoid problems with multiple concurrent .babylon loads.
  27613. var log = "importMesh has failed JSON parse";
  27614. try {
  27615. var parsedData = JSON.parse(data);
  27616. log = "";
  27617. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27618. var loadedSkeletonsIds = [];
  27619. var loadedMaterialsIds = [];
  27620. var hierarchyIds = [];
  27621. var index;
  27622. var cache;
  27623. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27624. var parsedMesh = parsedData.meshes[index];
  27625. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27626. if (meshesNames instanceof Array) {
  27627. // Remove found mesh name from list.
  27628. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27629. }
  27630. //Geometry?
  27631. if (parsedMesh.geometryId) {
  27632. //does the file contain geometries?
  27633. if (parsedData.geometries) {
  27634. //find the correct geometry and add it to the scene
  27635. var found = false;
  27636. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27637. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27638. return;
  27639. }
  27640. else {
  27641. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27642. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27643. switch (geometryType) {
  27644. case "boxes":
  27645. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27646. break;
  27647. case "spheres":
  27648. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27649. break;
  27650. case "cylinders":
  27651. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27652. break;
  27653. case "toruses":
  27654. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27655. break;
  27656. case "grounds":
  27657. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27658. break;
  27659. case "planes":
  27660. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27661. break;
  27662. case "torusKnots":
  27663. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27664. break;
  27665. case "vertexData":
  27666. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27667. break;
  27668. }
  27669. found = true;
  27670. }
  27671. });
  27672. }
  27673. });
  27674. if (!found) {
  27675. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27676. }
  27677. }
  27678. }
  27679. // Material ?
  27680. if (parsedMesh.materialId) {
  27681. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27682. if (!materialFound && parsedData.multiMaterials) {
  27683. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27684. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27685. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27686. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27687. var subMatId = parsedMultiMaterial.materials[matIndex];
  27688. loadedMaterialsIds.push(subMatId);
  27689. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27690. log += "\n\tMaterial " + mat.toString(fullDetails);
  27691. }
  27692. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27693. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27694. materialFound = true;
  27695. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27696. break;
  27697. }
  27698. }
  27699. }
  27700. if (!materialFound) {
  27701. loadedMaterialsIds.push(parsedMesh.materialId);
  27702. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27703. if (!mat) {
  27704. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27705. }
  27706. else {
  27707. log += "\n\tMaterial " + mat.toString(fullDetails);
  27708. }
  27709. }
  27710. }
  27711. // Skeleton ?
  27712. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27713. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27714. if (!skeletonAlreadyLoaded) {
  27715. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27716. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27717. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27718. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27719. skeletons.push(skeleton);
  27720. loadedSkeletonsIds.push(parsedSkeleton.id);
  27721. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27722. }
  27723. }
  27724. }
  27725. }
  27726. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27727. meshes.push(mesh);
  27728. log += "\n\tMesh " + mesh.toString(fullDetails);
  27729. }
  27730. }
  27731. // Connecting parents
  27732. var currentMesh;
  27733. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27734. currentMesh = scene.meshes[index];
  27735. if (currentMesh._waitingParentId) {
  27736. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27737. currentMesh._waitingParentId = undefined;
  27738. }
  27739. }
  27740. // freeze and compute world matrix application
  27741. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27742. currentMesh = scene.meshes[index];
  27743. if (currentMesh._waitingFreezeWorldMatrix) {
  27744. currentMesh.freezeWorldMatrix();
  27745. currentMesh._waitingFreezeWorldMatrix = undefined;
  27746. }
  27747. else {
  27748. currentMesh.computeWorldMatrix(true);
  27749. }
  27750. }
  27751. // Particles
  27752. if (parsedData.particleSystems) {
  27753. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27754. var parsedParticleSystem = parsedData.particleSystems[index];
  27755. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27756. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27757. }
  27758. }
  27759. }
  27760. return true;
  27761. }
  27762. catch (err) {
  27763. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27764. log = null;
  27765. throw err;
  27766. }
  27767. finally {
  27768. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27769. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27770. }
  27771. }
  27772. },
  27773. load: function (scene, data, rootUrl) {
  27774. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27775. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27776. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27777. // and avoid problems with multiple concurrent .babylon loads.
  27778. var log = "importScene has failed JSON parse";
  27779. try {
  27780. var parsedData = JSON.parse(data);
  27781. log = "";
  27782. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27783. // Scene
  27784. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27785. scene.autoClear = parsedData.autoClear;
  27786. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27787. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27788. if (parsedData.gravity) {
  27789. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27790. }
  27791. // Fog
  27792. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27793. scene.fogMode = parsedData.fogMode;
  27794. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27795. scene.fogStart = parsedData.fogStart;
  27796. scene.fogEnd = parsedData.fogEnd;
  27797. scene.fogDensity = parsedData.fogDensity;
  27798. log += "\tFog mode for scene: ";
  27799. switch (scene.fogMode) {
  27800. // getters not compiling, so using hardcoded
  27801. case 1:
  27802. log += "exp\n";
  27803. break;
  27804. case 2:
  27805. log += "exp2\n";
  27806. break;
  27807. case 3:
  27808. log += "linear\n";
  27809. break;
  27810. }
  27811. }
  27812. //Physics
  27813. if (parsedData.physicsEnabled) {
  27814. var physicsPlugin;
  27815. if (parsedData.physicsEngine === "cannon") {
  27816. physicsPlugin = new BABYLON.CannonJSPlugin();
  27817. }
  27818. else if (parsedData.physicsEngine === "oimo") {
  27819. physicsPlugin = new BABYLON.OimoJSPlugin();
  27820. }
  27821. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27822. //else - default engine, which is currently oimo
  27823. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27824. scene.enablePhysics(physicsGravity, physicsPlugin);
  27825. }
  27826. // Metadata
  27827. if (parsedData.metadata !== undefined) {
  27828. scene.metadata = parsedData.metadata;
  27829. }
  27830. //collisions, if defined. otherwise, default is true
  27831. if (parsedData.collisionsEnabled != undefined) {
  27832. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27833. }
  27834. scene.workerCollisions = !!parsedData.workerCollisions;
  27835. var index;
  27836. var cache;
  27837. // Lights
  27838. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27839. var parsedLight = parsedData.lights[index];
  27840. var light = BABYLON.Light.Parse(parsedLight, scene);
  27841. log += (index === 0 ? "\n\tLights:" : "");
  27842. log += "\n\t\t" + light.toString(fullDetails);
  27843. }
  27844. // Animations
  27845. if (parsedData.animations) {
  27846. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27847. var parsedAnimation = parsedData.animations[index];
  27848. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27849. scene.animations.push(animation);
  27850. log += (index === 0 ? "\n\tAnimations:" : "");
  27851. log += "\n\t\t" + animation.toString(fullDetails);
  27852. }
  27853. }
  27854. if (parsedData.autoAnimate) {
  27855. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27856. }
  27857. // Materials
  27858. if (parsedData.materials) {
  27859. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27860. var parsedMaterial = parsedData.materials[index];
  27861. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27862. log += (index === 0 ? "\n\tMaterials:" : "");
  27863. log += "\n\t\t" + mat.toString(fullDetails);
  27864. }
  27865. }
  27866. if (parsedData.multiMaterials) {
  27867. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27868. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27869. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27870. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27871. log += "\n\t\t" + mmat.toString(fullDetails);
  27872. }
  27873. }
  27874. // Skeletons
  27875. if (parsedData.skeletons) {
  27876. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27877. var parsedSkeleton = parsedData.skeletons[index];
  27878. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27879. log += (index === 0 ? "\n\tSkeletons:" : "");
  27880. log += "\n\t\t" + skeleton.toString(fullDetails);
  27881. }
  27882. }
  27883. // Geometries
  27884. var geometries = parsedData.geometries;
  27885. if (geometries) {
  27886. // Boxes
  27887. var boxes = geometries.boxes;
  27888. if (boxes) {
  27889. for (index = 0, cache = boxes.length; index < cache; index++) {
  27890. var parsedBox = boxes[index];
  27891. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27892. }
  27893. }
  27894. // Spheres
  27895. var spheres = geometries.spheres;
  27896. if (spheres) {
  27897. for (index = 0, cache = spheres.length; index < cache; index++) {
  27898. var parsedSphere = spheres[index];
  27899. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27900. }
  27901. }
  27902. // Cylinders
  27903. var cylinders = geometries.cylinders;
  27904. if (cylinders) {
  27905. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27906. var parsedCylinder = cylinders[index];
  27907. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27908. }
  27909. }
  27910. // Toruses
  27911. var toruses = geometries.toruses;
  27912. if (toruses) {
  27913. for (index = 0, cache = toruses.length; index < cache; index++) {
  27914. var parsedTorus = toruses[index];
  27915. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27916. }
  27917. }
  27918. // Grounds
  27919. var grounds = geometries.grounds;
  27920. if (grounds) {
  27921. for (index = 0, cache = grounds.length; index < cache; index++) {
  27922. var parsedGround = grounds[index];
  27923. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27924. }
  27925. }
  27926. // Planes
  27927. var planes = geometries.planes;
  27928. if (planes) {
  27929. for (index = 0, cache = planes.length; index < cache; index++) {
  27930. var parsedPlane = planes[index];
  27931. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27932. }
  27933. }
  27934. // TorusKnots
  27935. var torusKnots = geometries.torusKnots;
  27936. if (torusKnots) {
  27937. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27938. var parsedTorusKnot = torusKnots[index];
  27939. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27940. }
  27941. }
  27942. // VertexData
  27943. var vertexData = geometries.vertexData;
  27944. if (vertexData) {
  27945. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27946. var parsedVertexData = vertexData[index];
  27947. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27948. }
  27949. }
  27950. }
  27951. // Meshes
  27952. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27953. var parsedMesh = parsedData.meshes[index];
  27954. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27955. log += (index === 0 ? "\n\tMeshes:" : "");
  27956. log += "\n\t\t" + mesh.toString(fullDetails);
  27957. }
  27958. // Cameras
  27959. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27960. var parsedCamera = parsedData.cameras[index];
  27961. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27962. log += (index === 0 ? "\n\tCameras:" : "");
  27963. log += "\n\t\t" + camera.toString(fullDetails);
  27964. }
  27965. if (parsedData.activeCameraID) {
  27966. scene.setActiveCameraByID(parsedData.activeCameraID);
  27967. }
  27968. // Browsing all the graph to connect the dots
  27969. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27970. var camera = scene.cameras[index];
  27971. if (camera._waitingParentId) {
  27972. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27973. camera._waitingParentId = undefined;
  27974. }
  27975. }
  27976. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27977. var light = scene.lights[index];
  27978. if (light._waitingParentId) {
  27979. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27980. light._waitingParentId = undefined;
  27981. }
  27982. }
  27983. // Sounds
  27984. var loadedSounds = [];
  27985. var loadedSound;
  27986. if (BABYLON.AudioEngine && parsedData.sounds) {
  27987. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27988. var parsedSound = parsedData.sounds[index];
  27989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27990. if (!parsedSound.url)
  27991. parsedSound.url = parsedSound.name;
  27992. if (!loadedSounds[parsedSound.url]) {
  27993. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27994. loadedSounds[parsedSound.url] = loadedSound;
  27995. }
  27996. else {
  27997. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27998. }
  27999. }
  28000. else {
  28001. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28002. }
  28003. }
  28004. }
  28005. loadedSounds = [];
  28006. // Connect parents & children and parse actions
  28007. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28008. var mesh = scene.meshes[index];
  28009. if (mesh._waitingParentId) {
  28010. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28011. mesh._waitingParentId = undefined;
  28012. }
  28013. if (mesh._waitingActions) {
  28014. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28015. mesh._waitingActions = undefined;
  28016. }
  28017. }
  28018. // freeze world matrix application
  28019. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28020. var currentMesh = scene.meshes[index];
  28021. if (currentMesh._waitingFreezeWorldMatrix) {
  28022. currentMesh.freezeWorldMatrix();
  28023. currentMesh._waitingFreezeWorldMatrix = undefined;
  28024. }
  28025. else {
  28026. currentMesh.computeWorldMatrix(true);
  28027. }
  28028. }
  28029. // Particles Systems
  28030. if (parsedData.particleSystems) {
  28031. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28032. var parsedParticleSystem = parsedData.particleSystems[index];
  28033. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28034. }
  28035. }
  28036. // Lens flares
  28037. if (parsedData.lensFlareSystems) {
  28038. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28039. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28040. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28041. }
  28042. }
  28043. // Shadows
  28044. if (parsedData.shadowGenerators) {
  28045. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28046. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28047. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28048. }
  28049. }
  28050. // Actions (scene)
  28051. if (parsedData.actions) {
  28052. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28053. }
  28054. // Finish
  28055. return true;
  28056. }
  28057. catch (err) {
  28058. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28059. log = null;
  28060. throw err;
  28061. }
  28062. finally {
  28063. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28064. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28065. }
  28066. }
  28067. }
  28068. });
  28069. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28070. })(BABYLON || (BABYLON = {}));
  28071. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28072. var BABYLON;
  28073. (function (BABYLON) {
  28074. var SpriteManager = (function () {
  28075. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28076. if (epsilon === void 0) { epsilon = 0.01; }
  28077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28078. this.name = name;
  28079. this.sprites = new Array();
  28080. this.renderingGroupId = 0;
  28081. this.layerMask = 0x0FFFFFFF;
  28082. this.fogEnabled = true;
  28083. this.isPickable = false;
  28084. /**
  28085. * An event triggered when the manager is disposed.
  28086. * @type {BABYLON.Observable}
  28087. */
  28088. this.onDisposeObservable = new BABYLON.Observable();
  28089. this._vertexBuffers = {};
  28090. this._capacity = capacity;
  28091. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28092. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28093. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28094. if (cellSize.width && cellSize.height) {
  28095. this.cellWidth = cellSize.width;
  28096. this.cellHeight = cellSize.height;
  28097. }
  28098. else if (cellSize !== undefined) {
  28099. this.cellWidth = cellSize;
  28100. this.cellHeight = cellSize;
  28101. }
  28102. else {
  28103. return;
  28104. }
  28105. this._epsilon = epsilon;
  28106. this._scene = scene;
  28107. this._scene.spriteManagers.push(this);
  28108. var indices = [];
  28109. var index = 0;
  28110. for (var count = 0; count < capacity; count++) {
  28111. indices.push(index);
  28112. indices.push(index + 1);
  28113. indices.push(index + 2);
  28114. indices.push(index);
  28115. indices.push(index + 2);
  28116. indices.push(index + 3);
  28117. index += 4;
  28118. }
  28119. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28120. // VBO
  28121. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28122. this._vertexData = new Float32Array(capacity * 16 * 4);
  28123. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28124. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28125. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28126. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28127. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28129. this._vertexBuffers["options"] = options;
  28130. this._vertexBuffers["cellInfo"] = cellInfo;
  28131. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28132. // Effects
  28133. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28134. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28135. }
  28136. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28137. set: function (callback) {
  28138. if (this._onDisposeObserver) {
  28139. this.onDisposeObservable.remove(this._onDisposeObserver);
  28140. }
  28141. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28142. },
  28143. enumerable: true,
  28144. configurable: true
  28145. });
  28146. Object.defineProperty(SpriteManager.prototype, "texture", {
  28147. get: function () {
  28148. return this._spriteTexture;
  28149. },
  28150. set: function (value) {
  28151. this._spriteTexture = value;
  28152. },
  28153. enumerable: true,
  28154. configurable: true
  28155. });
  28156. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28157. var arrayOffset = index * 16;
  28158. if (offsetX === 0)
  28159. offsetX = this._epsilon;
  28160. else if (offsetX === 1)
  28161. offsetX = 1 - this._epsilon;
  28162. if (offsetY === 0)
  28163. offsetY = this._epsilon;
  28164. else if (offsetY === 1)
  28165. offsetY = 1 - this._epsilon;
  28166. this._vertexData[arrayOffset] = sprite.position.x;
  28167. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28168. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28169. this._vertexData[arrayOffset + 3] = sprite.angle;
  28170. this._vertexData[arrayOffset + 4] = sprite.width;
  28171. this._vertexData[arrayOffset + 5] = sprite.height;
  28172. this._vertexData[arrayOffset + 6] = offsetX;
  28173. this._vertexData[arrayOffset + 7] = offsetY;
  28174. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28175. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28176. var offset = (sprite.cellIndex / rowSize) >> 0;
  28177. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28178. this._vertexData[arrayOffset + 11] = offset;
  28179. // Color
  28180. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28181. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28182. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28183. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28184. };
  28185. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28186. var count = Math.min(this._capacity, this.sprites.length);
  28187. var min = BABYLON.Vector3.Zero();
  28188. var max = BABYLON.Vector3.Zero();
  28189. var distance = Number.MAX_VALUE;
  28190. var currentSprite;
  28191. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28192. var cameraView = camera.getViewMatrix();
  28193. for (var index = 0; index < count; index++) {
  28194. var sprite = this.sprites[index];
  28195. if (!sprite) {
  28196. continue;
  28197. }
  28198. if (predicate) {
  28199. if (!predicate(sprite)) {
  28200. continue;
  28201. }
  28202. }
  28203. else if (!sprite.isPickable) {
  28204. continue;
  28205. }
  28206. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28207. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28208. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28209. if (ray.intersectsBoxMinMax(min, max)) {
  28210. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28211. if (distance > currentDistance) {
  28212. distance = currentDistance;
  28213. currentSprite = sprite;
  28214. if (fastCheck) {
  28215. break;
  28216. }
  28217. }
  28218. }
  28219. }
  28220. if (currentSprite) {
  28221. var result = new BABYLON.PickingInfo();
  28222. result.hit = true;
  28223. result.pickedSprite = currentSprite;
  28224. result.distance = distance;
  28225. return result;
  28226. }
  28227. return null;
  28228. };
  28229. SpriteManager.prototype.render = function () {
  28230. // Check
  28231. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28232. return;
  28233. var engine = this._scene.getEngine();
  28234. var baseSize = this._spriteTexture.getBaseSize();
  28235. // Sprites
  28236. var deltaTime = engine.getDeltaTime();
  28237. var max = Math.min(this._capacity, this.sprites.length);
  28238. var rowSize = baseSize.width / this.cellWidth;
  28239. var offset = 0;
  28240. for (var index = 0; index < max; index++) {
  28241. var sprite = this.sprites[index];
  28242. if (!sprite) {
  28243. continue;
  28244. }
  28245. sprite._animate(deltaTime);
  28246. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28247. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28248. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28249. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28250. }
  28251. this._buffer.update(this._vertexData);
  28252. // Render
  28253. var effect = this._effectBase;
  28254. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28255. effect = this._effectFog;
  28256. }
  28257. engine.enableEffect(effect);
  28258. var viewMatrix = this._scene.getViewMatrix();
  28259. effect.setTexture("diffuseSampler", this._spriteTexture);
  28260. effect.setMatrix("view", viewMatrix);
  28261. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28262. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28263. // Fog
  28264. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28265. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28266. effect.setColor3("vFogColor", this._scene.fogColor);
  28267. }
  28268. // VBOs
  28269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28270. // Draw order
  28271. engine.setDepthFunctionToLessOrEqual();
  28272. effect.setBool("alphaTest", true);
  28273. engine.setColorWrite(false);
  28274. engine.draw(true, 0, max * 6);
  28275. engine.setColorWrite(true);
  28276. effect.setBool("alphaTest", false);
  28277. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28278. engine.draw(true, 0, max * 6);
  28279. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28280. };
  28281. SpriteManager.prototype.dispose = function () {
  28282. if (this._buffer) {
  28283. this._buffer.dispose();
  28284. this._buffer = null;
  28285. }
  28286. if (this._indexBuffer) {
  28287. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28288. this._indexBuffer = null;
  28289. }
  28290. if (this._spriteTexture) {
  28291. this._spriteTexture.dispose();
  28292. this._spriteTexture = null;
  28293. }
  28294. // Remove from scene
  28295. var index = this._scene.spriteManagers.indexOf(this);
  28296. this._scene.spriteManagers.splice(index, 1);
  28297. // Callback
  28298. this.onDisposeObservable.notifyObservers(this);
  28299. this.onDisposeObservable.clear();
  28300. };
  28301. return SpriteManager;
  28302. }());
  28303. BABYLON.SpriteManager = SpriteManager;
  28304. })(BABYLON || (BABYLON = {}));
  28305. //# sourceMappingURL=babylon.spriteManager.js.map
  28306. var BABYLON;
  28307. (function (BABYLON) {
  28308. var Sprite = (function () {
  28309. function Sprite(name, manager) {
  28310. this.name = name;
  28311. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28312. this.width = 1.0;
  28313. this.height = 1.0;
  28314. this.angle = 0;
  28315. this.cellIndex = 0;
  28316. this.invertU = 0;
  28317. this.invertV = 0;
  28318. this.animations = new Array();
  28319. this.isPickable = false;
  28320. this._animationStarted = false;
  28321. this._loopAnimation = false;
  28322. this._fromIndex = 0;
  28323. this._toIndex = 0;
  28324. this._delay = 0;
  28325. this._direction = 1;
  28326. this._frameCount = 0;
  28327. this._time = 0;
  28328. this._manager = manager;
  28329. this._manager.sprites.push(this);
  28330. this.position = BABYLON.Vector3.Zero();
  28331. }
  28332. Object.defineProperty(Sprite.prototype, "size", {
  28333. get: function () {
  28334. return this.width;
  28335. },
  28336. set: function (value) {
  28337. this.width = value;
  28338. this.height = value;
  28339. },
  28340. enumerable: true,
  28341. configurable: true
  28342. });
  28343. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28344. this._fromIndex = from;
  28345. this._toIndex = to;
  28346. this._loopAnimation = loop;
  28347. this._delay = delay;
  28348. this._animationStarted = true;
  28349. this._direction = from < to ? 1 : -1;
  28350. this.cellIndex = from;
  28351. this._time = 0;
  28352. this._onAnimationEnd = onAnimationEnd;
  28353. };
  28354. Sprite.prototype.stopAnimation = function () {
  28355. this._animationStarted = false;
  28356. };
  28357. Sprite.prototype._animate = function (deltaTime) {
  28358. if (!this._animationStarted)
  28359. return;
  28360. this._time += deltaTime;
  28361. if (this._time > this._delay) {
  28362. this._time = this._time % this._delay;
  28363. this.cellIndex += this._direction;
  28364. if (this.cellIndex === this._toIndex) {
  28365. if (this._loopAnimation) {
  28366. this.cellIndex = this._fromIndex;
  28367. }
  28368. else {
  28369. this._animationStarted = false;
  28370. if (this._onAnimationEnd) {
  28371. this._onAnimationEnd();
  28372. }
  28373. if (this.disposeWhenFinishedAnimating) {
  28374. this.dispose();
  28375. }
  28376. }
  28377. }
  28378. }
  28379. };
  28380. Sprite.prototype.dispose = function () {
  28381. for (var i = 0; i < this._manager.sprites.length; i++) {
  28382. if (this._manager.sprites[i] == this) {
  28383. this._manager.sprites.splice(i, 1);
  28384. }
  28385. }
  28386. };
  28387. return Sprite;
  28388. }());
  28389. BABYLON.Sprite = Sprite;
  28390. })(BABYLON || (BABYLON = {}));
  28391. //# sourceMappingURL=babylon.sprite.js.map
  28392. var BABYLON;
  28393. (function (BABYLON) {
  28394. var Layer = (function () {
  28395. function Layer(name, imgUrl, scene, isBackground, color) {
  28396. this.name = name;
  28397. this.scale = new BABYLON.Vector2(1, 1);
  28398. this.offset = new BABYLON.Vector2(0, 0);
  28399. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28400. this._vertexBuffers = {};
  28401. // Events
  28402. /**
  28403. * An event triggered when the layer is disposed.
  28404. * @type {BABYLON.Observable}
  28405. */
  28406. this.onDisposeObservable = new BABYLON.Observable();
  28407. /**
  28408. * An event triggered before rendering the scene
  28409. * @type {BABYLON.Observable}
  28410. */
  28411. this.onBeforeRenderObservable = new BABYLON.Observable();
  28412. /**
  28413. * An event triggered after rendering the scene
  28414. * @type {BABYLON.Observable}
  28415. */
  28416. this.onAfterRenderObservable = new BABYLON.Observable();
  28417. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28418. this.isBackground = isBackground === undefined ? true : isBackground;
  28419. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28420. this._scene = scene;
  28421. this._scene.layers.push(this);
  28422. var engine = scene.getEngine();
  28423. // VBO
  28424. var vertices = [];
  28425. vertices.push(1, 1);
  28426. vertices.push(-1, 1);
  28427. vertices.push(-1, -1);
  28428. vertices.push(1, -1);
  28429. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28430. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28431. // Indices
  28432. var indices = [];
  28433. indices.push(0);
  28434. indices.push(1);
  28435. indices.push(2);
  28436. indices.push(0);
  28437. indices.push(2);
  28438. indices.push(3);
  28439. this._indexBuffer = engine.createIndexBuffer(indices);
  28440. // Effects
  28441. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28442. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28443. }
  28444. Object.defineProperty(Layer.prototype, "onDispose", {
  28445. set: function (callback) {
  28446. if (this._onDisposeObserver) {
  28447. this.onDisposeObservable.remove(this._onDisposeObserver);
  28448. }
  28449. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28450. },
  28451. enumerable: true,
  28452. configurable: true
  28453. });
  28454. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28455. set: function (callback) {
  28456. if (this._onBeforeRenderObserver) {
  28457. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28458. }
  28459. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28460. },
  28461. enumerable: true,
  28462. configurable: true
  28463. });
  28464. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28465. set: function (callback) {
  28466. if (this._onAfterRenderObserver) {
  28467. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28468. }
  28469. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28470. },
  28471. enumerable: true,
  28472. configurable: true
  28473. });
  28474. Layer.prototype.render = function () {
  28475. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28476. // Check
  28477. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28478. return;
  28479. var engine = this._scene.getEngine();
  28480. this.onBeforeRenderObservable.notifyObservers(this);
  28481. // Render
  28482. engine.enableEffect(currentEffect);
  28483. engine.setState(false);
  28484. // Texture
  28485. currentEffect.setTexture("textureSampler", this.texture);
  28486. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28487. // Color
  28488. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28489. // Scale / offset
  28490. currentEffect.setVector2("offset", this.offset);
  28491. currentEffect.setVector2("scale", this.scale);
  28492. // VBOs
  28493. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28494. // Draw order
  28495. if (!this.alphaTest) {
  28496. engine.setAlphaMode(this.alphaBlendingMode);
  28497. engine.draw(true, 0, 6);
  28498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28499. }
  28500. else {
  28501. engine.draw(true, 0, 6);
  28502. }
  28503. this.onAfterRenderObservable.notifyObservers(this);
  28504. };
  28505. Layer.prototype.dispose = function () {
  28506. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28507. if (vertexBuffer) {
  28508. vertexBuffer.dispose();
  28509. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28510. }
  28511. if (this._indexBuffer) {
  28512. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28513. this._indexBuffer = null;
  28514. }
  28515. if (this.texture) {
  28516. this.texture.dispose();
  28517. this.texture = null;
  28518. }
  28519. // Remove from scene
  28520. var index = this._scene.layers.indexOf(this);
  28521. this._scene.layers.splice(index, 1);
  28522. // Callback
  28523. this.onDisposeObservable.notifyObservers(this);
  28524. this.onDisposeObservable.clear();
  28525. this.onAfterRenderObservable.clear();
  28526. this.onBeforeRenderObservable.clear();
  28527. };
  28528. return Layer;
  28529. }());
  28530. BABYLON.Layer = Layer;
  28531. })(BABYLON || (BABYLON = {}));
  28532. //# sourceMappingURL=babylon.layer.js.map
  28533. var BABYLON;
  28534. (function (BABYLON) {
  28535. var Particle = (function () {
  28536. function Particle() {
  28537. this.position = BABYLON.Vector3.Zero();
  28538. this.direction = BABYLON.Vector3.Zero();
  28539. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28540. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28541. this.lifeTime = 1.0;
  28542. this.age = 0;
  28543. this.size = 0;
  28544. this.angle = 0;
  28545. this.angularSpeed = 0;
  28546. }
  28547. Particle.prototype.copyTo = function (other) {
  28548. other.position.copyFrom(this.position);
  28549. other.direction.copyFrom(this.direction);
  28550. other.color.copyFrom(this.color);
  28551. other.colorStep.copyFrom(this.colorStep);
  28552. other.lifeTime = this.lifeTime;
  28553. other.age = this.age;
  28554. other.size = this.size;
  28555. other.angle = this.angle;
  28556. other.angularSpeed = this.angularSpeed;
  28557. };
  28558. return Particle;
  28559. }());
  28560. BABYLON.Particle = Particle;
  28561. })(BABYLON || (BABYLON = {}));
  28562. //# sourceMappingURL=babylon.particle.js.map
  28563. var BABYLON;
  28564. (function (BABYLON) {
  28565. var randomNumber = function (min, max) {
  28566. if (min === max) {
  28567. return (min);
  28568. }
  28569. var random = Math.random();
  28570. return ((random * (max - min)) + min);
  28571. };
  28572. var ParticleSystem = (function () {
  28573. function ParticleSystem(name, capacity, scene, customEffect) {
  28574. var _this = this;
  28575. this.name = name;
  28576. // Members
  28577. this.animations = [];
  28578. this.renderingGroupId = 0;
  28579. this.emitter = null;
  28580. this.emitRate = 10;
  28581. this.manualEmitCount = -1;
  28582. this.updateSpeed = 0.01;
  28583. this.targetStopDuration = 0;
  28584. this.disposeOnStop = false;
  28585. this.minEmitPower = 1;
  28586. this.maxEmitPower = 1;
  28587. this.minLifeTime = 1;
  28588. this.maxLifeTime = 1;
  28589. this.minSize = 1;
  28590. this.maxSize = 1;
  28591. this.minAngularSpeed = 0;
  28592. this.maxAngularSpeed = 0;
  28593. this.layerMask = 0x0FFFFFFF;
  28594. /**
  28595. * An event triggered when the system is disposed.
  28596. * @type {BABYLON.Observable}
  28597. */
  28598. this.onDisposeObservable = new BABYLON.Observable();
  28599. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28600. this.forceDepthWrite = false;
  28601. this.gravity = BABYLON.Vector3.Zero();
  28602. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28603. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28604. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28605. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28606. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28607. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28608. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28609. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28610. this.particles = new Array();
  28611. this._stockParticles = new Array();
  28612. this._newPartsExcess = 0;
  28613. this._vertexBuffers = {};
  28614. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28615. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28616. this._scaledDirection = BABYLON.Vector3.Zero();
  28617. this._scaledGravity = BABYLON.Vector3.Zero();
  28618. this._currentRenderId = -1;
  28619. this._started = false;
  28620. this._stopped = false;
  28621. this._actualFrame = 0;
  28622. this.id = name;
  28623. this._capacity = capacity;
  28624. this._scene = scene;
  28625. this._customEffect = customEffect;
  28626. scene.particleSystems.push(this);
  28627. var indices = [];
  28628. var index = 0;
  28629. for (var count = 0; count < capacity; count++) {
  28630. indices.push(index);
  28631. indices.push(index + 1);
  28632. indices.push(index + 2);
  28633. indices.push(index);
  28634. indices.push(index + 2);
  28635. indices.push(index + 3);
  28636. index += 4;
  28637. }
  28638. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28639. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28640. this._vertexData = new Float32Array(capacity * 11 * 4);
  28641. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28642. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28643. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28644. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28646. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28647. this._vertexBuffers["options"] = options;
  28648. // Default behaviors
  28649. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28650. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28651. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28652. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28653. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28654. };
  28655. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28656. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28657. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28658. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28659. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28660. };
  28661. this.updateFunction = function (particles) {
  28662. for (var index = 0; index < particles.length; index++) {
  28663. var particle = particles[index];
  28664. particle.age += _this._scaledUpdateSpeed;
  28665. if (particle.age >= particle.lifeTime) {
  28666. _this.recycleParticle(particle);
  28667. index--;
  28668. continue;
  28669. }
  28670. else {
  28671. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28672. particle.color.addInPlace(_this._scaledColorStep);
  28673. if (particle.color.a < 0)
  28674. particle.color.a = 0;
  28675. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28676. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28677. particle.position.addInPlace(_this._scaledDirection);
  28678. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28679. particle.direction.addInPlace(_this._scaledGravity);
  28680. }
  28681. }
  28682. };
  28683. }
  28684. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28685. set: function (callback) {
  28686. if (this._onDisposeObserver) {
  28687. this.onDisposeObservable.remove(this._onDisposeObserver);
  28688. }
  28689. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28690. },
  28691. enumerable: true,
  28692. configurable: true
  28693. });
  28694. ParticleSystem.prototype.recycleParticle = function (particle) {
  28695. var lastParticle = this.particles.pop();
  28696. if (lastParticle !== particle) {
  28697. lastParticle.copyTo(particle);
  28698. this._stockParticles.push(lastParticle);
  28699. }
  28700. };
  28701. ParticleSystem.prototype.getCapacity = function () {
  28702. return this._capacity;
  28703. };
  28704. ParticleSystem.prototype.isAlive = function () {
  28705. return this._alive;
  28706. };
  28707. ParticleSystem.prototype.isStarted = function () {
  28708. return this._started;
  28709. };
  28710. ParticleSystem.prototype.start = function () {
  28711. this._started = true;
  28712. this._stopped = false;
  28713. this._actualFrame = 0;
  28714. };
  28715. ParticleSystem.prototype.stop = function () {
  28716. this._stopped = true;
  28717. };
  28718. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28719. var offset = index * 11;
  28720. this._vertexData[offset] = particle.position.x;
  28721. this._vertexData[offset + 1] = particle.position.y;
  28722. this._vertexData[offset + 2] = particle.position.z;
  28723. this._vertexData[offset + 3] = particle.color.r;
  28724. this._vertexData[offset + 4] = particle.color.g;
  28725. this._vertexData[offset + 5] = particle.color.b;
  28726. this._vertexData[offset + 6] = particle.color.a;
  28727. this._vertexData[offset + 7] = particle.angle;
  28728. this._vertexData[offset + 8] = particle.size;
  28729. this._vertexData[offset + 9] = offsetX;
  28730. this._vertexData[offset + 10] = offsetY;
  28731. };
  28732. ParticleSystem.prototype._update = function (newParticles) {
  28733. // Update current
  28734. this._alive = this.particles.length > 0;
  28735. this.updateFunction(this.particles);
  28736. // Add new ones
  28737. var worldMatrix;
  28738. if (this.emitter.position) {
  28739. worldMatrix = this.emitter.getWorldMatrix();
  28740. }
  28741. else {
  28742. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28743. }
  28744. var particle;
  28745. for (var index = 0; index < newParticles; index++) {
  28746. if (this.particles.length === this._capacity) {
  28747. break;
  28748. }
  28749. if (this._stockParticles.length !== 0) {
  28750. particle = this._stockParticles.pop();
  28751. particle.age = 0;
  28752. }
  28753. else {
  28754. particle = new BABYLON.Particle();
  28755. }
  28756. this.particles.push(particle);
  28757. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28758. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28759. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28760. particle.size = randomNumber(this.minSize, this.maxSize);
  28761. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28762. this.startPositionFunction(worldMatrix, particle.position, particle);
  28763. var step = randomNumber(0, 1.0);
  28764. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28765. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28766. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28767. }
  28768. };
  28769. ParticleSystem.prototype._getEffect = function () {
  28770. if (this._customEffect) {
  28771. return this._customEffect;
  28772. }
  28773. ;
  28774. var defines = [];
  28775. if (this._scene.clipPlane) {
  28776. defines.push("#define CLIPPLANE");
  28777. }
  28778. // Effect
  28779. var join = defines.join("\n");
  28780. if (this._cachedDefines !== join) {
  28781. this._cachedDefines = join;
  28782. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28783. }
  28784. return this._effect;
  28785. };
  28786. ParticleSystem.prototype.animate = function () {
  28787. if (!this._started)
  28788. return;
  28789. var effect = this._getEffect();
  28790. // Check
  28791. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28792. return;
  28793. if (this._currentRenderId === this._scene.getRenderId()) {
  28794. return;
  28795. }
  28796. this._currentRenderId = this._scene.getRenderId();
  28797. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28798. // determine the number of particles we need to create
  28799. var newParticles;
  28800. if (this.manualEmitCount > -1) {
  28801. newParticles = this.manualEmitCount;
  28802. this._newPartsExcess = 0;
  28803. this.manualEmitCount = 0;
  28804. }
  28805. else {
  28806. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28807. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28808. }
  28809. if (this._newPartsExcess > 1.0) {
  28810. newParticles += this._newPartsExcess >> 0;
  28811. this._newPartsExcess -= this._newPartsExcess >> 0;
  28812. }
  28813. this._alive = false;
  28814. if (!this._stopped) {
  28815. this._actualFrame += this._scaledUpdateSpeed;
  28816. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28817. this.stop();
  28818. }
  28819. else {
  28820. newParticles = 0;
  28821. }
  28822. this._update(newParticles);
  28823. // Stopped?
  28824. if (this._stopped) {
  28825. if (!this._alive) {
  28826. this._started = false;
  28827. if (this.disposeOnStop) {
  28828. this._scene._toBeDisposed.push(this);
  28829. }
  28830. }
  28831. }
  28832. // Update VBO
  28833. var offset = 0;
  28834. for (var index = 0; index < this.particles.length; index++) {
  28835. var particle = this.particles[index];
  28836. this._appendParticleVertex(offset++, particle, 0, 0);
  28837. this._appendParticleVertex(offset++, particle, 1, 0);
  28838. this._appendParticleVertex(offset++, particle, 1, 1);
  28839. this._appendParticleVertex(offset++, particle, 0, 1);
  28840. }
  28841. this._vertexBuffer.update(this._vertexData);
  28842. };
  28843. ParticleSystem.prototype.render = function () {
  28844. var effect = this._getEffect();
  28845. // Check
  28846. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28847. return 0;
  28848. var engine = this._scene.getEngine();
  28849. // Render
  28850. engine.enableEffect(effect);
  28851. engine.setState(false);
  28852. var viewMatrix = this._scene.getViewMatrix();
  28853. effect.setTexture("diffuseSampler", this.particleTexture);
  28854. effect.setMatrix("view", viewMatrix);
  28855. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28856. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28857. if (this._scene.clipPlane) {
  28858. var clipPlane = this._scene.clipPlane;
  28859. var invView = viewMatrix.clone();
  28860. invView.invert();
  28861. effect.setMatrix("invView", invView);
  28862. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28863. }
  28864. // VBOs
  28865. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28866. // Draw order
  28867. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28868. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28869. }
  28870. else {
  28871. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28872. }
  28873. if (this.forceDepthWrite) {
  28874. engine.setDepthWrite(true);
  28875. }
  28876. engine.draw(true, 0, this.particles.length * 6);
  28877. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28878. return this.particles.length;
  28879. };
  28880. ParticleSystem.prototype.dispose = function () {
  28881. if (this._vertexBuffer) {
  28882. this._vertexBuffer.dispose();
  28883. this._vertexBuffer = null;
  28884. }
  28885. if (this._indexBuffer) {
  28886. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28887. this._indexBuffer = null;
  28888. }
  28889. if (this.particleTexture) {
  28890. this.particleTexture.dispose();
  28891. this.particleTexture = null;
  28892. }
  28893. // Remove from scene
  28894. var index = this._scene.particleSystems.indexOf(this);
  28895. this._scene.particleSystems.splice(index, 1);
  28896. // Callback
  28897. this.onDisposeObservable.notifyObservers(this);
  28898. this.onDisposeObservable.clear();
  28899. };
  28900. // Clone
  28901. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28902. var result = new ParticleSystem(name, this._capacity, this._scene);
  28903. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28904. if (newEmitter === undefined) {
  28905. newEmitter = this.emitter;
  28906. }
  28907. result.emitter = newEmitter;
  28908. if (this.particleTexture) {
  28909. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28910. }
  28911. result.start();
  28912. return result;
  28913. };
  28914. ParticleSystem.prototype.serialize = function () {
  28915. var serializationObject = {};
  28916. serializationObject.name = this.name;
  28917. serializationObject.id = this.id;
  28918. // Emitter
  28919. if (this.emitter.position) {
  28920. serializationObject.emitterId = this.emitter.id;
  28921. }
  28922. else {
  28923. serializationObject.emitter = this.emitter.asArray();
  28924. }
  28925. serializationObject.capacity = this.getCapacity();
  28926. if (this.particleTexture) {
  28927. serializationObject.textureName = this.particleTexture.name;
  28928. }
  28929. // Animations
  28930. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28931. // Particle system
  28932. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28933. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28934. serializationObject.minSize = this.minSize;
  28935. serializationObject.maxSize = this.maxSize;
  28936. serializationObject.minEmitPower = this.minEmitPower;
  28937. serializationObject.maxEmitPower = this.maxEmitPower;
  28938. serializationObject.minLifeTime = this.minLifeTime;
  28939. serializationObject.maxLifeTime = this.maxLifeTime;
  28940. serializationObject.emitRate = this.emitRate;
  28941. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28942. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28943. serializationObject.gravity = this.gravity.asArray();
  28944. serializationObject.direction1 = this.direction1.asArray();
  28945. serializationObject.direction2 = this.direction2.asArray();
  28946. serializationObject.color1 = this.color1.asArray();
  28947. serializationObject.color2 = this.color2.asArray();
  28948. serializationObject.colorDead = this.colorDead.asArray();
  28949. serializationObject.updateSpeed = this.updateSpeed;
  28950. serializationObject.targetStopDuration = this.targetStopDuration;
  28951. serializationObject.textureMask = this.textureMask.asArray();
  28952. serializationObject.blendMode = this.blendMode;
  28953. return serializationObject;
  28954. };
  28955. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28956. var name = parsedParticleSystem.name;
  28957. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28958. if (parsedParticleSystem.id) {
  28959. particleSystem.id = parsedParticleSystem.id;
  28960. }
  28961. // Texture
  28962. if (parsedParticleSystem.textureName) {
  28963. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28964. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28965. }
  28966. // Emitter
  28967. if (parsedParticleSystem.emitterId) {
  28968. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28969. }
  28970. else {
  28971. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28972. }
  28973. // Animations
  28974. if (parsedParticleSystem.animations) {
  28975. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28976. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28977. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28978. }
  28979. }
  28980. if (parsedParticleSystem.autoAnimate) {
  28981. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28982. }
  28983. // Particle system
  28984. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28985. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28986. particleSystem.minSize = parsedParticleSystem.minSize;
  28987. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28988. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28989. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28990. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28991. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28992. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28993. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28994. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28995. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28996. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28997. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28998. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28999. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29000. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29001. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29002. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29003. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29004. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29005. if (!parsedParticleSystem.preventAutoStart) {
  29006. particleSystem.start();
  29007. }
  29008. return particleSystem;
  29009. };
  29010. return ParticleSystem;
  29011. }());
  29012. // Statics
  29013. ParticleSystem.BLENDMODE_ONEONE = 0;
  29014. ParticleSystem.BLENDMODE_STANDARD = 1;
  29015. BABYLON.ParticleSystem = ParticleSystem;
  29016. })(BABYLON || (BABYLON = {}));
  29017. //# sourceMappingURL=babylon.particleSystem.js.map
  29018. var BABYLON;
  29019. (function (BABYLON) {
  29020. var AnimationRange = (function () {
  29021. function AnimationRange(name, from, to) {
  29022. this.name = name;
  29023. this.from = from;
  29024. this.to = to;
  29025. }
  29026. AnimationRange.prototype.clone = function () {
  29027. return new AnimationRange(this.name, this.from, this.to);
  29028. };
  29029. return AnimationRange;
  29030. }());
  29031. BABYLON.AnimationRange = AnimationRange;
  29032. /**
  29033. * Composed of a frame, and an action function
  29034. */
  29035. var AnimationEvent = (function () {
  29036. function AnimationEvent(frame, action, onlyOnce) {
  29037. this.frame = frame;
  29038. this.action = action;
  29039. this.onlyOnce = onlyOnce;
  29040. this.isDone = false;
  29041. }
  29042. return AnimationEvent;
  29043. }());
  29044. BABYLON.AnimationEvent = AnimationEvent;
  29045. var PathCursor = (function () {
  29046. function PathCursor(path) {
  29047. this.path = path;
  29048. this._onchange = new Array();
  29049. this.value = 0;
  29050. this.animations = new Array();
  29051. }
  29052. PathCursor.prototype.getPoint = function () {
  29053. var point = this.path.getPointAtLengthPosition(this.value);
  29054. return new BABYLON.Vector3(point.x, 0, point.y);
  29055. };
  29056. PathCursor.prototype.moveAhead = function (step) {
  29057. if (step === void 0) { step = 0.002; }
  29058. this.move(step);
  29059. return this;
  29060. };
  29061. PathCursor.prototype.moveBack = function (step) {
  29062. if (step === void 0) { step = 0.002; }
  29063. this.move(-step);
  29064. return this;
  29065. };
  29066. PathCursor.prototype.move = function (step) {
  29067. if (Math.abs(step) > 1) {
  29068. throw "step size should be less than 1.";
  29069. }
  29070. this.value += step;
  29071. this.ensureLimits();
  29072. this.raiseOnChange();
  29073. return this;
  29074. };
  29075. PathCursor.prototype.ensureLimits = function () {
  29076. while (this.value > 1) {
  29077. this.value -= 1;
  29078. }
  29079. while (this.value < 0) {
  29080. this.value += 1;
  29081. }
  29082. return this;
  29083. };
  29084. // used by animation engine
  29085. PathCursor.prototype.markAsDirty = function (propertyName) {
  29086. this.ensureLimits();
  29087. this.raiseOnChange();
  29088. return this;
  29089. };
  29090. PathCursor.prototype.raiseOnChange = function () {
  29091. var _this = this;
  29092. this._onchange.forEach(function (f) { return f(_this); });
  29093. return this;
  29094. };
  29095. PathCursor.prototype.onchange = function (f) {
  29096. this._onchange.push(f);
  29097. return this;
  29098. };
  29099. return PathCursor;
  29100. }());
  29101. BABYLON.PathCursor = PathCursor;
  29102. var Animation = (function () {
  29103. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29104. this.name = name;
  29105. this.targetProperty = targetProperty;
  29106. this.framePerSecond = framePerSecond;
  29107. this.dataType = dataType;
  29108. this.loopMode = loopMode;
  29109. this.enableBlending = enableBlending;
  29110. this._offsetsCache = {};
  29111. this._highLimitsCache = {};
  29112. this._stopped = false;
  29113. this._blendingFactor = 0;
  29114. // The set of event that will be linked to this animation
  29115. this._events = new Array();
  29116. this.allowMatricesInterpolation = false;
  29117. this.blendingSpeed = 0.01;
  29118. this._ranges = {};
  29119. this.targetPropertyPath = targetProperty.split(".");
  29120. this.dataType = dataType;
  29121. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29122. }
  29123. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29124. var dataType = undefined;
  29125. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29126. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29127. }
  29128. else if (from instanceof BABYLON.Quaternion) {
  29129. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29130. }
  29131. else if (from instanceof BABYLON.Vector3) {
  29132. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29133. }
  29134. else if (from instanceof BABYLON.Vector2) {
  29135. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29136. }
  29137. else if (from instanceof BABYLON.Color3) {
  29138. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29139. }
  29140. else if (from instanceof BABYLON.Size) {
  29141. dataType = Animation.ANIMATIONTYPE_SIZE;
  29142. }
  29143. if (dataType == undefined) {
  29144. return null;
  29145. }
  29146. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29147. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29148. animation.setKeys(keys);
  29149. if (easingFunction !== undefined) {
  29150. animation.setEasingFunction(easingFunction);
  29151. }
  29152. return animation;
  29153. };
  29154. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29155. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29156. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29157. };
  29158. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29159. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29160. node.animations.push(animation);
  29161. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29162. };
  29163. // Methods
  29164. /**
  29165. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29166. */
  29167. Animation.prototype.toString = function (fullDetails) {
  29168. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29169. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29170. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29171. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29172. if (fullDetails) {
  29173. ret += ", Ranges: {";
  29174. var first = true;
  29175. for (var name in this._ranges) {
  29176. if (first) {
  29177. ret += ", ";
  29178. first = false;
  29179. }
  29180. ret += name;
  29181. }
  29182. ret += "}";
  29183. }
  29184. return ret;
  29185. };
  29186. /**
  29187. * Add an event to this animation.
  29188. */
  29189. Animation.prototype.addEvent = function (event) {
  29190. this._events.push(event);
  29191. };
  29192. /**
  29193. * Remove all events found at the given frame
  29194. * @param frame
  29195. */
  29196. Animation.prototype.removeEvents = function (frame) {
  29197. for (var index = 0; index < this._events.length; index++) {
  29198. if (this._events[index].frame === frame) {
  29199. this._events.splice(index, 1);
  29200. index--;
  29201. }
  29202. }
  29203. };
  29204. Animation.prototype.createRange = function (name, from, to) {
  29205. // check name not already in use; could happen for bones after serialized
  29206. if (!this._ranges[name]) {
  29207. this._ranges[name] = new AnimationRange(name, from, to);
  29208. }
  29209. };
  29210. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29211. if (deleteFrames === void 0) { deleteFrames = true; }
  29212. if (this._ranges[name]) {
  29213. if (deleteFrames) {
  29214. var from = this._ranges[name].from;
  29215. var to = this._ranges[name].to;
  29216. // this loop MUST go high to low for multiple splices to work
  29217. for (var key = this._keys.length - 1; key >= 0; key--) {
  29218. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29219. this._keys.splice(key, 1);
  29220. }
  29221. }
  29222. }
  29223. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29224. }
  29225. };
  29226. Animation.prototype.getRange = function (name) {
  29227. return this._ranges[name];
  29228. };
  29229. Animation.prototype.reset = function () {
  29230. this._offsetsCache = {};
  29231. this._highLimitsCache = {};
  29232. this.currentFrame = 0;
  29233. this._blendingFactor = 0;
  29234. this._originalBlendValue = null;
  29235. };
  29236. Animation.prototype.isStopped = function () {
  29237. return this._stopped;
  29238. };
  29239. Animation.prototype.getKeys = function () {
  29240. return this._keys;
  29241. };
  29242. Animation.prototype.getHighestFrame = function () {
  29243. var ret = 0;
  29244. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29245. if (ret < this._keys[key].frame) {
  29246. ret = this._keys[key].frame;
  29247. }
  29248. }
  29249. return ret;
  29250. };
  29251. Animation.prototype.getEasingFunction = function () {
  29252. return this._easingFunction;
  29253. };
  29254. Animation.prototype.setEasingFunction = function (easingFunction) {
  29255. this._easingFunction = easingFunction;
  29256. };
  29257. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29258. return startValue + (endValue - startValue) * gradient;
  29259. };
  29260. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29261. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29262. };
  29263. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29264. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29265. };
  29266. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29267. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29268. };
  29269. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29270. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29271. };
  29272. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29273. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29274. };
  29275. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29276. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29277. };
  29278. Animation.prototype.clone = function () {
  29279. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29280. if (this._keys) {
  29281. clone.setKeys(this._keys);
  29282. }
  29283. if (this._ranges) {
  29284. clone._ranges = {};
  29285. for (var name in this._ranges) {
  29286. clone._ranges[name] = this._ranges[name].clone();
  29287. }
  29288. }
  29289. return clone;
  29290. };
  29291. Animation.prototype.setKeys = function (values) {
  29292. this._keys = values.slice(0);
  29293. this._offsetsCache = {};
  29294. this._highLimitsCache = {};
  29295. };
  29296. Animation.prototype._getKeyValue = function (value) {
  29297. if (typeof value === "function") {
  29298. return value();
  29299. }
  29300. return value;
  29301. };
  29302. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29303. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29304. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29305. }
  29306. this.currentFrame = currentFrame;
  29307. // Try to get a hash to find the right key
  29308. 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));
  29309. if (this._keys[startKey].frame >= currentFrame) {
  29310. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29311. startKey--;
  29312. }
  29313. }
  29314. for (var key = startKey; key < this._keys.length; key++) {
  29315. if (this._keys[key + 1].frame >= currentFrame) {
  29316. var startValue = this._getKeyValue(this._keys[key].value);
  29317. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29318. // gradient : percent of currentFrame between the frame inf and the frame sup
  29319. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29320. // check for easingFunction and correction of gradient
  29321. if (this._easingFunction != null) {
  29322. gradient = this._easingFunction.ease(gradient);
  29323. }
  29324. switch (this.dataType) {
  29325. // Float
  29326. case Animation.ANIMATIONTYPE_FLOAT:
  29327. switch (loopMode) {
  29328. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29329. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29330. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29331. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29332. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29333. }
  29334. break;
  29335. // Quaternion
  29336. case Animation.ANIMATIONTYPE_QUATERNION:
  29337. var quaternion = null;
  29338. switch (loopMode) {
  29339. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29340. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29341. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29342. break;
  29343. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29344. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29345. break;
  29346. }
  29347. return quaternion;
  29348. // Vector3
  29349. case Animation.ANIMATIONTYPE_VECTOR3:
  29350. switch (loopMode) {
  29351. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29352. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29353. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29354. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29355. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29356. }
  29357. // Vector2
  29358. case Animation.ANIMATIONTYPE_VECTOR2:
  29359. switch (loopMode) {
  29360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29362. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29363. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29364. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29365. }
  29366. // Size
  29367. case Animation.ANIMATIONTYPE_SIZE:
  29368. switch (loopMode) {
  29369. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29370. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29371. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29372. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29373. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29374. }
  29375. // Color3
  29376. case Animation.ANIMATIONTYPE_COLOR3:
  29377. switch (loopMode) {
  29378. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29379. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29380. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29381. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29382. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29383. }
  29384. // Matrix
  29385. case Animation.ANIMATIONTYPE_MATRIX:
  29386. switch (loopMode) {
  29387. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29388. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29389. if (this.allowMatricesInterpolation) {
  29390. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29391. }
  29392. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29393. return startValue;
  29394. }
  29395. default:
  29396. break;
  29397. }
  29398. break;
  29399. }
  29400. }
  29401. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29402. };
  29403. Animation.prototype.setValue = function (currentValue, blend) {
  29404. if (blend === void 0) { blend = false; }
  29405. // Set value
  29406. var path;
  29407. var destination;
  29408. if (this.targetPropertyPath.length > 1) {
  29409. var property = this._target[this.targetPropertyPath[0]];
  29410. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29411. property = property[this.targetPropertyPath[index]];
  29412. }
  29413. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29414. destination = property;
  29415. }
  29416. else {
  29417. path = this.targetPropertyPath[0];
  29418. destination = this._target;
  29419. }
  29420. // Blending
  29421. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29422. if (!this._originalBlendValue) {
  29423. if (destination[path].clone) {
  29424. this._originalBlendValue = destination[path].clone();
  29425. }
  29426. else {
  29427. this._originalBlendValue = destination[path];
  29428. }
  29429. }
  29430. if (this._originalBlendValue.prototype) {
  29431. if (this._originalBlendValue.prototype.Lerp) {
  29432. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29433. }
  29434. else {
  29435. destination[path] = currentValue;
  29436. }
  29437. }
  29438. else if (this._originalBlendValue.m) {
  29439. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29440. }
  29441. else {
  29442. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29443. }
  29444. this._blendingFactor += this.blendingSpeed;
  29445. }
  29446. else {
  29447. destination[path] = currentValue;
  29448. }
  29449. if (this._target.markAsDirty) {
  29450. this._target.markAsDirty(this.targetProperty);
  29451. }
  29452. };
  29453. Animation.prototype.goToFrame = function (frame) {
  29454. if (frame < this._keys[0].frame) {
  29455. frame = this._keys[0].frame;
  29456. }
  29457. else if (frame > this._keys[this._keys.length - 1].frame) {
  29458. frame = this._keys[this._keys.length - 1].frame;
  29459. }
  29460. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29461. this.setValue(currentValue);
  29462. };
  29463. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29464. if (blend === void 0) { blend = false; }
  29465. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29466. this._stopped = true;
  29467. return false;
  29468. }
  29469. var returnValue = true;
  29470. // Adding a start key at frame 0 if missing
  29471. if (this._keys[0].frame !== 0) {
  29472. var newKey = { frame: 0, value: this._keys[0].value };
  29473. this._keys.splice(0, 0, newKey);
  29474. }
  29475. // Check limits
  29476. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29477. from = this._keys[0].frame;
  29478. }
  29479. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29480. to = this._keys[this._keys.length - 1].frame;
  29481. }
  29482. //to and from cannot be the same key
  29483. if (from === to) {
  29484. from++;
  29485. }
  29486. // Compute ratio
  29487. var range = to - from;
  29488. var offsetValue;
  29489. // ratio represents the frame delta between from and to
  29490. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29491. var highLimitValue = 0;
  29492. if (ratio > range && !loop) {
  29493. returnValue = false;
  29494. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29495. }
  29496. else {
  29497. // Get max value if required
  29498. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29499. var keyOffset = to.toString() + from.toString();
  29500. if (!this._offsetsCache[keyOffset]) {
  29501. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29502. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29503. switch (this.dataType) {
  29504. // Float
  29505. case Animation.ANIMATIONTYPE_FLOAT:
  29506. this._offsetsCache[keyOffset] = toValue - fromValue;
  29507. break;
  29508. // Quaternion
  29509. case Animation.ANIMATIONTYPE_QUATERNION:
  29510. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29511. break;
  29512. // Vector3
  29513. case Animation.ANIMATIONTYPE_VECTOR3:
  29514. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29515. // Vector2
  29516. case Animation.ANIMATIONTYPE_VECTOR2:
  29517. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29518. // Size
  29519. case Animation.ANIMATIONTYPE_SIZE:
  29520. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29521. // Color3
  29522. case Animation.ANIMATIONTYPE_COLOR3:
  29523. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29524. default:
  29525. break;
  29526. }
  29527. this._highLimitsCache[keyOffset] = toValue;
  29528. }
  29529. highLimitValue = this._highLimitsCache[keyOffset];
  29530. offsetValue = this._offsetsCache[keyOffset];
  29531. }
  29532. }
  29533. if (offsetValue === undefined) {
  29534. switch (this.dataType) {
  29535. // Float
  29536. case Animation.ANIMATIONTYPE_FLOAT:
  29537. offsetValue = 0;
  29538. break;
  29539. // Quaternion
  29540. case Animation.ANIMATIONTYPE_QUATERNION:
  29541. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29542. break;
  29543. // Vector3
  29544. case Animation.ANIMATIONTYPE_VECTOR3:
  29545. offsetValue = BABYLON.Vector3.Zero();
  29546. break;
  29547. // Vector2
  29548. case Animation.ANIMATIONTYPE_VECTOR2:
  29549. offsetValue = BABYLON.Vector2.Zero();
  29550. break;
  29551. // Size
  29552. case Animation.ANIMATIONTYPE_SIZE:
  29553. offsetValue = BABYLON.Size.Zero();
  29554. break;
  29555. // Color3
  29556. case Animation.ANIMATIONTYPE_COLOR3:
  29557. offsetValue = BABYLON.Color3.Black();
  29558. }
  29559. }
  29560. // Compute value
  29561. var repeatCount = (ratio / range) >> 0;
  29562. var currentFrame = returnValue ? from + ratio % range : to;
  29563. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29564. // Set value
  29565. this.setValue(currentValue);
  29566. // Check events
  29567. for (var index = 0; index < this._events.length; index++) {
  29568. if (currentFrame >= this._events[index].frame) {
  29569. var event = this._events[index];
  29570. if (!event.isDone) {
  29571. // If event should be done only once, remove it.
  29572. if (event.onlyOnce) {
  29573. this._events.splice(index, 1);
  29574. index--;
  29575. }
  29576. event.isDone = true;
  29577. event.action();
  29578. } // Don't do anything if the event has already be done.
  29579. }
  29580. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29581. // reset event, the animation is looping
  29582. this._events[index].isDone = false;
  29583. }
  29584. }
  29585. if (!returnValue) {
  29586. this._stopped = true;
  29587. }
  29588. return returnValue;
  29589. };
  29590. Animation.prototype.serialize = function () {
  29591. var serializationObject = {};
  29592. serializationObject.name = this.name;
  29593. serializationObject.property = this.targetProperty;
  29594. serializationObject.framePerSecond = this.framePerSecond;
  29595. serializationObject.dataType = this.dataType;
  29596. serializationObject.loopBehavior = this.loopMode;
  29597. var dataType = this.dataType;
  29598. serializationObject.keys = [];
  29599. var keys = this.getKeys();
  29600. for (var index = 0; index < keys.length; index++) {
  29601. var animationKey = keys[index];
  29602. var key = {};
  29603. key.frame = animationKey.frame;
  29604. switch (dataType) {
  29605. case Animation.ANIMATIONTYPE_FLOAT:
  29606. key.values = [animationKey.value];
  29607. break;
  29608. case Animation.ANIMATIONTYPE_QUATERNION:
  29609. case Animation.ANIMATIONTYPE_MATRIX:
  29610. case Animation.ANIMATIONTYPE_VECTOR3:
  29611. case Animation.ANIMATIONTYPE_COLOR3:
  29612. key.values = animationKey.value.asArray();
  29613. break;
  29614. }
  29615. serializationObject.keys.push(key);
  29616. }
  29617. serializationObject.ranges = [];
  29618. for (var name in this._ranges) {
  29619. var range = {};
  29620. range.name = name;
  29621. range.from = this._ranges[name].from;
  29622. range.to = this._ranges[name].to;
  29623. serializationObject.ranges.push(range);
  29624. }
  29625. return serializationObject;
  29626. };
  29627. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29628. get: function () {
  29629. return Animation._ANIMATIONTYPE_FLOAT;
  29630. },
  29631. enumerable: true,
  29632. configurable: true
  29633. });
  29634. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29635. get: function () {
  29636. return Animation._ANIMATIONTYPE_VECTOR3;
  29637. },
  29638. enumerable: true,
  29639. configurable: true
  29640. });
  29641. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29642. get: function () {
  29643. return Animation._ANIMATIONTYPE_VECTOR2;
  29644. },
  29645. enumerable: true,
  29646. configurable: true
  29647. });
  29648. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29649. get: function () {
  29650. return Animation._ANIMATIONTYPE_SIZE;
  29651. },
  29652. enumerable: true,
  29653. configurable: true
  29654. });
  29655. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29656. get: function () {
  29657. return Animation._ANIMATIONTYPE_QUATERNION;
  29658. },
  29659. enumerable: true,
  29660. configurable: true
  29661. });
  29662. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29663. get: function () {
  29664. return Animation._ANIMATIONTYPE_MATRIX;
  29665. },
  29666. enumerable: true,
  29667. configurable: true
  29668. });
  29669. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29670. get: function () {
  29671. return Animation._ANIMATIONTYPE_COLOR3;
  29672. },
  29673. enumerable: true,
  29674. configurable: true
  29675. });
  29676. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29677. get: function () {
  29678. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29679. },
  29680. enumerable: true,
  29681. configurable: true
  29682. });
  29683. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29684. get: function () {
  29685. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29686. },
  29687. enumerable: true,
  29688. configurable: true
  29689. });
  29690. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29691. get: function () {
  29692. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29693. },
  29694. enumerable: true,
  29695. configurable: true
  29696. });
  29697. Animation.Parse = function (parsedAnimation) {
  29698. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29699. var dataType = parsedAnimation.dataType;
  29700. var keys = [];
  29701. var data;
  29702. var index;
  29703. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29704. var key = parsedAnimation.keys[index];
  29705. switch (dataType) {
  29706. case Animation.ANIMATIONTYPE_FLOAT:
  29707. data = key.values[0];
  29708. break;
  29709. case Animation.ANIMATIONTYPE_QUATERNION:
  29710. data = BABYLON.Quaternion.FromArray(key.values);
  29711. break;
  29712. case Animation.ANIMATIONTYPE_MATRIX:
  29713. data = BABYLON.Matrix.FromArray(key.values);
  29714. break;
  29715. case Animation.ANIMATIONTYPE_COLOR3:
  29716. data = BABYLON.Color3.FromArray(key.values);
  29717. break;
  29718. case Animation.ANIMATIONTYPE_VECTOR3:
  29719. default:
  29720. data = BABYLON.Vector3.FromArray(key.values);
  29721. break;
  29722. }
  29723. keys.push({
  29724. frame: key.frame,
  29725. value: data
  29726. });
  29727. }
  29728. animation.setKeys(keys);
  29729. if (parsedAnimation.ranges) {
  29730. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29731. data = parsedAnimation.ranges[index];
  29732. animation.createRange(data.name, data.from, data.to);
  29733. }
  29734. }
  29735. return animation;
  29736. };
  29737. Animation.AppendSerializedAnimations = function (source, destination) {
  29738. if (source.animations) {
  29739. destination.animations = [];
  29740. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29741. var animation = source.animations[animationIndex];
  29742. destination.animations.push(animation.serialize());
  29743. }
  29744. }
  29745. };
  29746. return Animation;
  29747. }());
  29748. // Statics
  29749. Animation._ANIMATIONTYPE_FLOAT = 0;
  29750. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29751. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29752. Animation._ANIMATIONTYPE_MATRIX = 3;
  29753. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29754. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29755. Animation._ANIMATIONTYPE_SIZE = 6;
  29756. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29757. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29758. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29759. BABYLON.Animation = Animation;
  29760. })(BABYLON || (BABYLON = {}));
  29761. //# sourceMappingURL=babylon.animation.js.map
  29762. var BABYLON;
  29763. (function (BABYLON) {
  29764. var Animatable = (function () {
  29765. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29766. if (fromFrame === void 0) { fromFrame = 0; }
  29767. if (toFrame === void 0) { toFrame = 100; }
  29768. if (loopAnimation === void 0) { loopAnimation = false; }
  29769. if (speedRatio === void 0) { speedRatio = 1.0; }
  29770. this.target = target;
  29771. this.fromFrame = fromFrame;
  29772. this.toFrame = toFrame;
  29773. this.loopAnimation = loopAnimation;
  29774. this.speedRatio = speedRatio;
  29775. this.onAnimationEnd = onAnimationEnd;
  29776. this._animations = new Array();
  29777. this._paused = false;
  29778. this.animationStarted = false;
  29779. if (animations) {
  29780. this.appendAnimations(target, animations);
  29781. }
  29782. this._scene = scene;
  29783. scene._activeAnimatables.push(this);
  29784. }
  29785. // Methods
  29786. Animatable.prototype.getAnimations = function () {
  29787. return this._animations;
  29788. };
  29789. Animatable.prototype.appendAnimations = function (target, animations) {
  29790. for (var index = 0; index < animations.length; index++) {
  29791. var animation = animations[index];
  29792. animation._target = target;
  29793. this._animations.push(animation);
  29794. }
  29795. };
  29796. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29797. var animations = this._animations;
  29798. for (var index = 0; index < animations.length; index++) {
  29799. if (animations[index].targetProperty === property) {
  29800. return animations[index];
  29801. }
  29802. }
  29803. return null;
  29804. };
  29805. Animatable.prototype.reset = function () {
  29806. var animations = this._animations;
  29807. for (var index = 0; index < animations.length; index++) {
  29808. animations[index].reset();
  29809. }
  29810. this._localDelayOffset = null;
  29811. this._pausedDelay = null;
  29812. };
  29813. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29814. var animations = this._animations;
  29815. for (var index = 0; index < animations.length; index++) {
  29816. animations[index].enableBlending = true;
  29817. animations[index].blendingSpeed = blendingSpeed;
  29818. }
  29819. };
  29820. Animatable.prototype.disableBlending = function () {
  29821. var animations = this._animations;
  29822. for (var index = 0; index < animations.length; index++) {
  29823. animations[index].enableBlending = false;
  29824. }
  29825. };
  29826. Animatable.prototype.goToFrame = function (frame) {
  29827. var animations = this._animations;
  29828. if (animations[0]) {
  29829. var fps = animations[0].framePerSecond;
  29830. var currentFrame = animations[0].currentFrame;
  29831. var adjustTime = frame - currentFrame;
  29832. var delay = adjustTime * 1000 / fps;
  29833. this._localDelayOffset -= delay;
  29834. }
  29835. for (var index = 0; index < animations.length; index++) {
  29836. animations[index].goToFrame(frame);
  29837. }
  29838. };
  29839. Animatable.prototype.pause = function () {
  29840. if (this._paused) {
  29841. return;
  29842. }
  29843. this._paused = true;
  29844. };
  29845. Animatable.prototype.restart = function () {
  29846. this._paused = false;
  29847. };
  29848. Animatable.prototype.stop = function (animationName) {
  29849. var index = this._scene._activeAnimatables.indexOf(this);
  29850. if (index > -1) {
  29851. var animations = this._animations;
  29852. var numberOfAnimationsStopped = 0;
  29853. for (var index = animations.length - 1; index >= 0; index--) {
  29854. if (typeof animationName === "string" && animations[index].name != animationName) {
  29855. continue;
  29856. }
  29857. animations[index].reset();
  29858. animations.splice(index, 1);
  29859. numberOfAnimationsStopped++;
  29860. }
  29861. if (animations.length == numberOfAnimationsStopped) {
  29862. this._scene._activeAnimatables.splice(index, 1);
  29863. if (this.onAnimationEnd) {
  29864. this.onAnimationEnd();
  29865. }
  29866. }
  29867. }
  29868. };
  29869. Animatable.prototype._animate = function (delay) {
  29870. if (this._paused) {
  29871. this.animationStarted = false;
  29872. if (!this._pausedDelay) {
  29873. this._pausedDelay = delay;
  29874. }
  29875. return true;
  29876. }
  29877. if (!this._localDelayOffset) {
  29878. this._localDelayOffset = delay;
  29879. }
  29880. else if (this._pausedDelay) {
  29881. this._localDelayOffset += delay - this._pausedDelay;
  29882. this._pausedDelay = null;
  29883. }
  29884. // Animating
  29885. var running = false;
  29886. var animations = this._animations;
  29887. var index;
  29888. for (index = 0; index < animations.length; index++) {
  29889. var animation = animations[index];
  29890. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29891. running = running || isRunning;
  29892. }
  29893. this.animationStarted = running;
  29894. if (!running) {
  29895. // Remove from active animatables
  29896. index = this._scene._activeAnimatables.indexOf(this);
  29897. this._scene._activeAnimatables.splice(index, 1);
  29898. }
  29899. if (!running && this.onAnimationEnd) {
  29900. this.onAnimationEnd();
  29901. this.onAnimationEnd = null;
  29902. }
  29903. return running;
  29904. };
  29905. return Animatable;
  29906. }());
  29907. BABYLON.Animatable = Animatable;
  29908. })(BABYLON || (BABYLON = {}));
  29909. //# sourceMappingURL=babylon.animatable.js.map
  29910. var BABYLON;
  29911. (function (BABYLON) {
  29912. var EasingFunction = (function () {
  29913. function EasingFunction() {
  29914. // Properties
  29915. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29916. }
  29917. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29918. get: function () {
  29919. return EasingFunction._EASINGMODE_EASEIN;
  29920. },
  29921. enumerable: true,
  29922. configurable: true
  29923. });
  29924. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29925. get: function () {
  29926. return EasingFunction._EASINGMODE_EASEOUT;
  29927. },
  29928. enumerable: true,
  29929. configurable: true
  29930. });
  29931. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29932. get: function () {
  29933. return EasingFunction._EASINGMODE_EASEINOUT;
  29934. },
  29935. enumerable: true,
  29936. configurable: true
  29937. });
  29938. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29939. var n = Math.min(Math.max(easingMode, 0), 2);
  29940. this._easingMode = n;
  29941. };
  29942. EasingFunction.prototype.getEasingMode = function () {
  29943. return this._easingMode;
  29944. };
  29945. EasingFunction.prototype.easeInCore = function (gradient) {
  29946. throw new Error('You must implement this method');
  29947. };
  29948. EasingFunction.prototype.ease = function (gradient) {
  29949. switch (this._easingMode) {
  29950. case EasingFunction.EASINGMODE_EASEIN:
  29951. return this.easeInCore(gradient);
  29952. case EasingFunction.EASINGMODE_EASEOUT:
  29953. return (1 - this.easeInCore(1 - gradient));
  29954. }
  29955. if (gradient >= 0.5) {
  29956. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29957. }
  29958. return (this.easeInCore(gradient * 2) * 0.5);
  29959. };
  29960. return EasingFunction;
  29961. }());
  29962. //Statics
  29963. EasingFunction._EASINGMODE_EASEIN = 0;
  29964. EasingFunction._EASINGMODE_EASEOUT = 1;
  29965. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29966. BABYLON.EasingFunction = EasingFunction;
  29967. var CircleEase = (function (_super) {
  29968. __extends(CircleEase, _super);
  29969. function CircleEase() {
  29970. return _super.apply(this, arguments) || this;
  29971. }
  29972. CircleEase.prototype.easeInCore = function (gradient) {
  29973. gradient = Math.max(0, Math.min(1, gradient));
  29974. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29975. };
  29976. return CircleEase;
  29977. }(EasingFunction));
  29978. BABYLON.CircleEase = CircleEase;
  29979. var BackEase = (function (_super) {
  29980. __extends(BackEase, _super);
  29981. function BackEase(amplitude) {
  29982. if (amplitude === void 0) { amplitude = 1; }
  29983. var _this = _super.call(this) || this;
  29984. _this.amplitude = amplitude;
  29985. return _this;
  29986. }
  29987. BackEase.prototype.easeInCore = function (gradient) {
  29988. var num = Math.max(0, this.amplitude);
  29989. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29990. };
  29991. return BackEase;
  29992. }(EasingFunction));
  29993. BABYLON.BackEase = BackEase;
  29994. var BounceEase = (function (_super) {
  29995. __extends(BounceEase, _super);
  29996. function BounceEase(bounces, bounciness) {
  29997. if (bounces === void 0) { bounces = 3; }
  29998. if (bounciness === void 0) { bounciness = 2; }
  29999. var _this = _super.call(this) || this;
  30000. _this.bounces = bounces;
  30001. _this.bounciness = bounciness;
  30002. return _this;
  30003. }
  30004. BounceEase.prototype.easeInCore = function (gradient) {
  30005. var y = Math.max(0.0, this.bounces);
  30006. var bounciness = this.bounciness;
  30007. if (bounciness <= 1.0) {
  30008. bounciness = 1.001;
  30009. }
  30010. var num9 = Math.pow(bounciness, y);
  30011. var num5 = 1.0 - bounciness;
  30012. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30013. var num15 = gradient * num4;
  30014. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30015. var num3 = Math.floor(num65);
  30016. var num13 = num3 + 1.0;
  30017. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30018. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30019. var num7 = (num8 + num12) * 0.5;
  30020. var num6 = gradient - num7;
  30021. var num2 = num7 - num8;
  30022. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30023. };
  30024. return BounceEase;
  30025. }(EasingFunction));
  30026. BABYLON.BounceEase = BounceEase;
  30027. var CubicEase = (function (_super) {
  30028. __extends(CubicEase, _super);
  30029. function CubicEase() {
  30030. return _super.apply(this, arguments) || this;
  30031. }
  30032. CubicEase.prototype.easeInCore = function (gradient) {
  30033. return (gradient * gradient * gradient);
  30034. };
  30035. return CubicEase;
  30036. }(EasingFunction));
  30037. BABYLON.CubicEase = CubicEase;
  30038. var ElasticEase = (function (_super) {
  30039. __extends(ElasticEase, _super);
  30040. function ElasticEase(oscillations, springiness) {
  30041. if (oscillations === void 0) { oscillations = 3; }
  30042. if (springiness === void 0) { springiness = 3; }
  30043. var _this = _super.call(this) || this;
  30044. _this.oscillations = oscillations;
  30045. _this.springiness = springiness;
  30046. return _this;
  30047. }
  30048. ElasticEase.prototype.easeInCore = function (gradient) {
  30049. var num2;
  30050. var num3 = Math.max(0.0, this.oscillations);
  30051. var num = Math.max(0.0, this.springiness);
  30052. if (num == 0) {
  30053. num2 = gradient;
  30054. }
  30055. else {
  30056. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30057. }
  30058. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30059. };
  30060. return ElasticEase;
  30061. }(EasingFunction));
  30062. BABYLON.ElasticEase = ElasticEase;
  30063. var ExponentialEase = (function (_super) {
  30064. __extends(ExponentialEase, _super);
  30065. function ExponentialEase(exponent) {
  30066. if (exponent === void 0) { exponent = 2; }
  30067. var _this = _super.call(this) || this;
  30068. _this.exponent = exponent;
  30069. return _this;
  30070. }
  30071. ExponentialEase.prototype.easeInCore = function (gradient) {
  30072. if (this.exponent <= 0) {
  30073. return gradient;
  30074. }
  30075. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30076. };
  30077. return ExponentialEase;
  30078. }(EasingFunction));
  30079. BABYLON.ExponentialEase = ExponentialEase;
  30080. var PowerEase = (function (_super) {
  30081. __extends(PowerEase, _super);
  30082. function PowerEase(power) {
  30083. if (power === void 0) { power = 2; }
  30084. var _this = _super.call(this) || this;
  30085. _this.power = power;
  30086. return _this;
  30087. }
  30088. PowerEase.prototype.easeInCore = function (gradient) {
  30089. var y = Math.max(0.0, this.power);
  30090. return Math.pow(gradient, y);
  30091. };
  30092. return PowerEase;
  30093. }(EasingFunction));
  30094. BABYLON.PowerEase = PowerEase;
  30095. var QuadraticEase = (function (_super) {
  30096. __extends(QuadraticEase, _super);
  30097. function QuadraticEase() {
  30098. return _super.apply(this, arguments) || this;
  30099. }
  30100. QuadraticEase.prototype.easeInCore = function (gradient) {
  30101. return (gradient * gradient);
  30102. };
  30103. return QuadraticEase;
  30104. }(EasingFunction));
  30105. BABYLON.QuadraticEase = QuadraticEase;
  30106. var QuarticEase = (function (_super) {
  30107. __extends(QuarticEase, _super);
  30108. function QuarticEase() {
  30109. return _super.apply(this, arguments) || this;
  30110. }
  30111. QuarticEase.prototype.easeInCore = function (gradient) {
  30112. return (gradient * gradient * gradient * gradient);
  30113. };
  30114. return QuarticEase;
  30115. }(EasingFunction));
  30116. BABYLON.QuarticEase = QuarticEase;
  30117. var QuinticEase = (function (_super) {
  30118. __extends(QuinticEase, _super);
  30119. function QuinticEase() {
  30120. return _super.apply(this, arguments) || this;
  30121. }
  30122. QuinticEase.prototype.easeInCore = function (gradient) {
  30123. return (gradient * gradient * gradient * gradient * gradient);
  30124. };
  30125. return QuinticEase;
  30126. }(EasingFunction));
  30127. BABYLON.QuinticEase = QuinticEase;
  30128. var SineEase = (function (_super) {
  30129. __extends(SineEase, _super);
  30130. function SineEase() {
  30131. return _super.apply(this, arguments) || this;
  30132. }
  30133. SineEase.prototype.easeInCore = function (gradient) {
  30134. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30135. };
  30136. return SineEase;
  30137. }(EasingFunction));
  30138. BABYLON.SineEase = SineEase;
  30139. var BezierCurveEase = (function (_super) {
  30140. __extends(BezierCurveEase, _super);
  30141. function BezierCurveEase(x1, y1, x2, y2) {
  30142. if (x1 === void 0) { x1 = 0; }
  30143. if (y1 === void 0) { y1 = 0; }
  30144. if (x2 === void 0) { x2 = 1; }
  30145. if (y2 === void 0) { y2 = 1; }
  30146. var _this = _super.call(this) || this;
  30147. _this.x1 = x1;
  30148. _this.y1 = y1;
  30149. _this.x2 = x2;
  30150. _this.y2 = y2;
  30151. return _this;
  30152. }
  30153. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30154. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30155. };
  30156. return BezierCurveEase;
  30157. }(EasingFunction));
  30158. BABYLON.BezierCurveEase = BezierCurveEase;
  30159. })(BABYLON || (BABYLON = {}));
  30160. //# sourceMappingURL=babylon.easing.js.map
  30161. var BABYLON;
  30162. (function (BABYLON) {
  30163. var Bone = (function (_super) {
  30164. __extends(Bone, _super);
  30165. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30166. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30167. _this.name = name;
  30168. _this.children = new Array();
  30169. _this.animations = new Array();
  30170. _this._worldTransform = new BABYLON.Matrix();
  30171. _this._absoluteTransform = new BABYLON.Matrix();
  30172. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30173. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30174. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30175. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30176. _this._scalingDeterminant = 1;
  30177. _this._syncScaleVector = function () {
  30178. var lm = this.getLocalMatrix();
  30179. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30180. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30181. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30182. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30183. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30184. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30185. this._scaleVector.x = xs * Math.sqrt(xsq);
  30186. this._scaleVector.y = ys * Math.sqrt(ysq);
  30187. this._scaleVector.z = zs * Math.sqrt(zsq);
  30188. if (this._parent) {
  30189. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30190. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30191. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30192. }
  30193. 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);
  30194. };
  30195. _this._skeleton = skeleton;
  30196. _this._matrix = matrix;
  30197. _this._baseMatrix = matrix;
  30198. _this._restPose = restPose ? restPose : matrix.clone();
  30199. skeleton.bones.push(_this);
  30200. if (parentBone) {
  30201. _this._parent = parentBone;
  30202. parentBone.children.push(_this);
  30203. }
  30204. else {
  30205. _this._parent = null;
  30206. }
  30207. _this._updateDifferenceMatrix();
  30208. if (_this.getAbsoluteTransform().determinant() < 0) {
  30209. _this._scalingDeterminant *= -1;
  30210. }
  30211. return _this;
  30212. }
  30213. // Members
  30214. Bone.prototype.getParent = function () {
  30215. return this._parent;
  30216. };
  30217. Bone.prototype.getLocalMatrix = function () {
  30218. return this._matrix;
  30219. };
  30220. Bone.prototype.getBaseMatrix = function () {
  30221. return this._baseMatrix;
  30222. };
  30223. Bone.prototype.getRestPose = function () {
  30224. return this._restPose;
  30225. };
  30226. Bone.prototype.returnToRest = function () {
  30227. this.updateMatrix(this._restPose.clone());
  30228. };
  30229. Bone.prototype.getWorldMatrix = function () {
  30230. return this._worldTransform;
  30231. };
  30232. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30233. return this._invertedAbsoluteTransform;
  30234. };
  30235. Bone.prototype.getAbsoluteTransform = function () {
  30236. return this._absoluteTransform;
  30237. };
  30238. // Methods
  30239. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30240. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30241. this._baseMatrix = matrix.clone();
  30242. this._matrix = matrix.clone();
  30243. this._skeleton._markAsDirty();
  30244. if (updateDifferenceMatrix) {
  30245. this._updateDifferenceMatrix();
  30246. }
  30247. };
  30248. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30249. if (!rootMatrix) {
  30250. rootMatrix = this._baseMatrix;
  30251. }
  30252. if (this._parent) {
  30253. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30254. }
  30255. else {
  30256. this._absoluteTransform.copyFrom(rootMatrix);
  30257. }
  30258. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30259. for (var index = 0; index < this.children.length; index++) {
  30260. this.children[index]._updateDifferenceMatrix();
  30261. }
  30262. };
  30263. Bone.prototype.markAsDirty = function () {
  30264. this._currentRenderId++;
  30265. this._skeleton._markAsDirty();
  30266. };
  30267. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30268. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30269. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30270. // all animation may be coming from a library skeleton, so may need to create animation
  30271. if (this.animations.length === 0) {
  30272. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30273. this.animations[0].setKeys([]);
  30274. }
  30275. // get animation info / verify there is such a range from the source bone
  30276. var sourceRange = source.animations[0].getRange(rangeName);
  30277. if (!sourceRange) {
  30278. return false;
  30279. }
  30280. var from = sourceRange.from;
  30281. var to = sourceRange.to;
  30282. var sourceKeys = source.animations[0].getKeys();
  30283. // rescaling prep
  30284. var sourceBoneLength = source.length;
  30285. var sourceParent = source.getParent();
  30286. var parent = this.getParent();
  30287. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30288. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30289. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30290. var destKeys = this.animations[0].getKeys();
  30291. // loop vars declaration
  30292. var orig;
  30293. var origTranslation;
  30294. var mat;
  30295. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30296. orig = sourceKeys[key];
  30297. if (orig.frame >= from && orig.frame <= to) {
  30298. if (rescaleAsRequired) {
  30299. mat = orig.value.clone();
  30300. // scale based on parent ratio, when bone has parent
  30301. if (parentScalingReqd) {
  30302. origTranslation = mat.getTranslation();
  30303. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30304. }
  30305. else if (dimensionsScalingReqd) {
  30306. origTranslation = mat.getTranslation();
  30307. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30308. }
  30309. else {
  30310. mat = orig.value;
  30311. }
  30312. }
  30313. else {
  30314. mat = orig.value;
  30315. }
  30316. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30317. }
  30318. }
  30319. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30320. return true;
  30321. };
  30322. Bone.prototype.translate = function (vec, space, mesh) {
  30323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30324. var lm = this.getLocalMatrix();
  30325. if (space == BABYLON.Space.LOCAL) {
  30326. lm.m[12] += vec.x;
  30327. lm.m[13] += vec.y;
  30328. lm.m[14] += vec.z;
  30329. }
  30330. else {
  30331. this._skeleton.computeAbsoluteTransforms();
  30332. var tmat = BABYLON.Tmp.Matrix[0];
  30333. var tvec = BABYLON.Tmp.Vector3[0];
  30334. if (mesh) {
  30335. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30336. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30337. }
  30338. else {
  30339. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30340. }
  30341. tmat.m[12] = 0;
  30342. tmat.m[13] = 0;
  30343. tmat.m[14] = 0;
  30344. tmat.invert();
  30345. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30346. lm.m[12] += tvec.x;
  30347. lm.m[13] += tvec.y;
  30348. lm.m[14] += tvec.z;
  30349. }
  30350. this.markAsDirty();
  30351. };
  30352. Bone.prototype.setPosition = function (position, space, mesh) {
  30353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30354. var lm = this.getLocalMatrix();
  30355. if (space == BABYLON.Space.LOCAL) {
  30356. lm.m[12] = position.x;
  30357. lm.m[13] = position.y;
  30358. lm.m[14] = position.z;
  30359. }
  30360. else {
  30361. this._skeleton.computeAbsoluteTransforms();
  30362. var tmat = BABYLON.Tmp.Matrix[0];
  30363. var vec = BABYLON.Tmp.Vector3[0];
  30364. if (mesh) {
  30365. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30366. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30367. }
  30368. else {
  30369. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30370. }
  30371. tmat.invert();
  30372. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30373. lm.m[12] = vec.x;
  30374. lm.m[13] = vec.y;
  30375. lm.m[14] = vec.z;
  30376. }
  30377. this.markAsDirty();
  30378. };
  30379. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30380. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30381. };
  30382. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30383. if (scaleChildren === void 0) { scaleChildren = false; }
  30384. if (this.animations[0] && !this.animations[0].isStopped()) {
  30385. if (!scaleChildren) {
  30386. this._negateScaleChildren.x = 1 / x;
  30387. this._negateScaleChildren.y = 1 / y;
  30388. this._negateScaleChildren.z = 1 / z;
  30389. }
  30390. this._syncScaleVector();
  30391. }
  30392. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30393. };
  30394. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30395. if (scaleChildren === void 0) { scaleChildren = false; }
  30396. var locMat = this.getLocalMatrix();
  30397. var origLocMat = BABYLON.Tmp.Matrix[0];
  30398. origLocMat.copyFrom(locMat);
  30399. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30400. origLocMatInv.copyFrom(origLocMat);
  30401. origLocMatInv.invert();
  30402. var scaleMat = BABYLON.Tmp.Matrix[2];
  30403. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30404. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30405. this._scaleVector.x *= x;
  30406. this._scaleVector.y *= y;
  30407. this._scaleVector.z *= z;
  30408. locMat.multiplyToRef(origLocMatInv, locMat);
  30409. locMat.multiplyToRef(scaleMat, locMat);
  30410. locMat.multiplyToRef(origLocMat, locMat);
  30411. var parent = this.getParent();
  30412. if (parent) {
  30413. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30414. }
  30415. else {
  30416. this.getAbsoluteTransform().copyFrom(locMat);
  30417. }
  30418. var len = this.children.length;
  30419. scaleMat.invert();
  30420. for (var i = 0; i < len; i++) {
  30421. var child = this.children[i];
  30422. var cm = child.getLocalMatrix();
  30423. cm.multiplyToRef(scaleMat, cm);
  30424. var lm = child.getLocalMatrix();
  30425. lm.m[12] *= x;
  30426. lm.m[13] *= y;
  30427. lm.m[14] *= z;
  30428. }
  30429. this.computeAbsoluteTransforms();
  30430. if (scaleChildren) {
  30431. for (var i = 0; i < len; i++) {
  30432. this.children[i].scale(x, y, z, scaleChildren);
  30433. }
  30434. }
  30435. this.markAsDirty();
  30436. };
  30437. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30438. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30439. var rotMat = BABYLON.Tmp.Matrix[0];
  30440. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30441. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30442. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30443. rotMatInv.multiplyToRef(rotMat, rotMat);
  30444. this._rotateWithMatrix(rotMat, space, mesh);
  30445. };
  30446. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30448. var rmat = BABYLON.Tmp.Matrix[0];
  30449. rmat.m[12] = 0;
  30450. rmat.m[13] = 0;
  30451. rmat.m[14] = 0;
  30452. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30453. this._rotateWithMatrix(rmat, space, mesh);
  30454. };
  30455. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30457. var rotMat = BABYLON.Tmp.Matrix[0];
  30458. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30459. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30460. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30461. rotMatInv.multiplyToRef(rotMat, rotMat);
  30462. this._rotateWithMatrix(rotMat, space, mesh);
  30463. };
  30464. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30466. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30467. };
  30468. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30470. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30471. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30472. var rotMat = BABYLON.Tmp.Matrix[1];
  30473. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30474. rotMatInv.multiplyToRef(rotMat, rotMat);
  30475. this._rotateWithMatrix(rotMat, space, mesh);
  30476. };
  30477. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30478. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30479. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30480. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30481. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30482. rotMat2.copyFrom(rotMat);
  30483. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30484. this._rotateWithMatrix(rotMat2, space, mesh);
  30485. };
  30486. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30488. var lmat = this.getLocalMatrix();
  30489. var lx = lmat.m[12];
  30490. var ly = lmat.m[13];
  30491. var lz = lmat.m[14];
  30492. var parent = this.getParent();
  30493. var parentScale = BABYLON.Tmp.Matrix[3];
  30494. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30495. if (parent) {
  30496. if (space == BABYLON.Space.WORLD) {
  30497. if (mesh) {
  30498. parentScale.copyFrom(mesh.getWorldMatrix());
  30499. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30500. }
  30501. else {
  30502. parentScale.copyFrom(parent.getAbsoluteTransform());
  30503. }
  30504. }
  30505. else {
  30506. parentScale = parent._scaleMatrix;
  30507. }
  30508. parentScaleInv.copyFrom(parentScale);
  30509. parentScaleInv.invert();
  30510. lmat.multiplyToRef(parentScale, lmat);
  30511. lmat.multiplyToRef(rmat, lmat);
  30512. lmat.multiplyToRef(parentScaleInv, lmat);
  30513. }
  30514. else {
  30515. if (space == BABYLON.Space.WORLD && mesh) {
  30516. parentScale.copyFrom(mesh.getWorldMatrix());
  30517. parentScaleInv.copyFrom(parentScale);
  30518. parentScaleInv.invert();
  30519. lmat.multiplyToRef(parentScale, lmat);
  30520. lmat.multiplyToRef(rmat, lmat);
  30521. lmat.multiplyToRef(parentScaleInv, lmat);
  30522. }
  30523. else {
  30524. lmat.multiplyToRef(rmat, lmat);
  30525. }
  30526. }
  30527. lmat.m[12] = lx;
  30528. lmat.m[13] = ly;
  30529. lmat.m[14] = lz;
  30530. this.computeAbsoluteTransforms();
  30531. this.markAsDirty();
  30532. };
  30533. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30535. if (space == BABYLON.Space.WORLD) {
  30536. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30537. scaleMatrix.copyFrom(this._scaleMatrix);
  30538. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30539. if (mesh) {
  30540. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30541. var meshScale = BABYLON.Tmp.Matrix[3];
  30542. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30543. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30544. }
  30545. rotMatInv.invert();
  30546. scaleMatrix.m[0] *= this._scalingDeterminant;
  30547. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30548. }
  30549. else {
  30550. rotMatInv.copyFrom(this.getLocalMatrix());
  30551. rotMatInv.invert();
  30552. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30553. scaleMatrix.copyFrom(this._scaleMatrix);
  30554. if (this._parent) {
  30555. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30556. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30557. pscaleMatrix.invert();
  30558. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30559. }
  30560. else {
  30561. scaleMatrix.m[0] *= this._scalingDeterminant;
  30562. }
  30563. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30564. }
  30565. };
  30566. Bone.prototype.getScale = function () {
  30567. return this._scaleVector.clone();
  30568. };
  30569. Bone.prototype.getScaleToRef = function (result) {
  30570. result.copyFrom(this._scaleVector);
  30571. };
  30572. Bone.prototype.getPosition = function (space, mesh) {
  30573. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30574. var pos = BABYLON.Vector3.Zero();
  30575. this.getPositionToRef(space, mesh, pos);
  30576. return pos;
  30577. };
  30578. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30579. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30580. if (space == BABYLON.Space.LOCAL) {
  30581. var lm = this.getLocalMatrix();
  30582. result.x = lm.m[12];
  30583. result.y = lm.m[13];
  30584. result.z = lm.m[14];
  30585. }
  30586. else {
  30587. this._skeleton.computeAbsoluteTransforms();
  30588. var tmat = BABYLON.Tmp.Matrix[0];
  30589. if (mesh) {
  30590. tmat.copyFrom(this.getAbsoluteTransform());
  30591. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30592. }
  30593. else {
  30594. tmat = this.getAbsoluteTransform();
  30595. }
  30596. result.x = tmat.m[12];
  30597. result.y = tmat.m[13];
  30598. result.z = tmat.m[14];
  30599. }
  30600. };
  30601. Bone.prototype.getAbsolutePosition = function (mesh) {
  30602. var pos = BABYLON.Vector3.Zero();
  30603. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30604. return pos;
  30605. };
  30606. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30607. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30608. };
  30609. Bone.prototype.computeAbsoluteTransforms = function () {
  30610. if (this._parent) {
  30611. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30612. }
  30613. else {
  30614. this._absoluteTransform.copyFrom(this._matrix);
  30615. var poseMatrix = this._skeleton.getPoseMatrix();
  30616. if (poseMatrix) {
  30617. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30618. }
  30619. }
  30620. var children = this.children;
  30621. var len = children.length;
  30622. for (var i = 0; i < len; i++) {
  30623. children[i].computeAbsoluteTransforms();
  30624. }
  30625. };
  30626. Bone.prototype.getDirection = function (localAxis, mesh) {
  30627. var result = BABYLON.Vector3.Zero();
  30628. this.getDirectionToRef(localAxis, mesh, result);
  30629. return result;
  30630. };
  30631. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30632. this._skeleton.computeAbsoluteTransforms();
  30633. var mat = BABYLON.Tmp.Matrix[0];
  30634. mat.copyFrom(this.getAbsoluteTransform());
  30635. if (mesh) {
  30636. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30637. }
  30638. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30639. result.normalize();
  30640. };
  30641. Bone.prototype.getRotation = function (space, mesh) {
  30642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30643. var result = BABYLON.Vector3.Zero();
  30644. this.getRotationToRef(space, mesh, result);
  30645. return result;
  30646. };
  30647. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30649. var quat = BABYLON.Tmp.Quaternion[0];
  30650. this.getRotationQuaternionToRef(space, mesh, quat);
  30651. quat.toEulerAnglesToRef(result);
  30652. };
  30653. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30655. var result = BABYLON.Quaternion.Identity();
  30656. this.getRotationQuaternionToRef(space, mesh, result);
  30657. return result;
  30658. };
  30659. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30661. if (space == BABYLON.Space.LOCAL) {
  30662. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30663. }
  30664. else {
  30665. var mat = BABYLON.Tmp.Matrix[0];
  30666. var amat = this.getAbsoluteTransform();
  30667. if (mesh) {
  30668. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30669. }
  30670. else {
  30671. mat.copyFrom(amat);
  30672. }
  30673. mat.m[0] *= this._scalingDeterminant;
  30674. mat.m[1] *= this._scalingDeterminant;
  30675. mat.m[2] *= this._scalingDeterminant;
  30676. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30677. }
  30678. };
  30679. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30681. var result = BABYLON.Matrix.Identity();
  30682. this.getRotationMatrixToRef(space, mesh, result);
  30683. return result;
  30684. };
  30685. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30687. if (space == BABYLON.Space.LOCAL) {
  30688. this.getLocalMatrix().getRotationMatrixToRef(result);
  30689. }
  30690. else {
  30691. var mat = BABYLON.Tmp.Matrix[0];
  30692. var amat = this.getAbsoluteTransform();
  30693. if (mesh) {
  30694. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30695. }
  30696. else {
  30697. mat.copyFrom(amat);
  30698. }
  30699. mat.m[0] *= this._scalingDeterminant;
  30700. mat.m[1] *= this._scalingDeterminant;
  30701. mat.m[2] *= this._scalingDeterminant;
  30702. mat.getRotationMatrixToRef(result);
  30703. }
  30704. };
  30705. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30706. var result = BABYLON.Vector3.Zero();
  30707. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30708. return result;
  30709. };
  30710. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30711. this._skeleton.computeAbsoluteTransforms();
  30712. var tmat = BABYLON.Tmp.Matrix[0];
  30713. if (mesh) {
  30714. tmat.copyFrom(this.getAbsoluteTransform());
  30715. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30716. }
  30717. else {
  30718. tmat = this.getAbsoluteTransform();
  30719. }
  30720. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30721. };
  30722. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30723. var result = BABYLON.Vector3.Zero();
  30724. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30725. return result;
  30726. };
  30727. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30728. this._skeleton.computeAbsoluteTransforms();
  30729. var tmat = BABYLON.Tmp.Matrix[0];
  30730. tmat.copyFrom(this.getAbsoluteTransform());
  30731. if (mesh) {
  30732. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30733. }
  30734. tmat.invert();
  30735. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30736. };
  30737. return Bone;
  30738. }(BABYLON.Node));
  30739. BABYLON.Bone = Bone;
  30740. })(BABYLON || (BABYLON = {}));
  30741. //# sourceMappingURL=babylon.bone.js.map
  30742. var BABYLON;
  30743. (function (BABYLON) {
  30744. var BoneIKController = (function () {
  30745. function BoneIKController(mesh, bone, options) {
  30746. this.targetPosition = BABYLON.Vector3.Zero();
  30747. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30748. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30749. this.poleAngle = 0;
  30750. this.slerpAmount = 1;
  30751. this._bone1Quat = BABYLON.Quaternion.Identity();
  30752. this._bone1Mat = BABYLON.Matrix.Identity();
  30753. this._bone2Ang = Math.PI;
  30754. this._maxAngle = Math.PI;
  30755. this._tmpVec1 = BABYLON.Vector3.Zero();
  30756. this._tmpVec2 = BABYLON.Vector3.Zero();
  30757. this._tmpVec3 = BABYLON.Vector3.Zero();
  30758. this._tmpVec4 = BABYLON.Vector3.Zero();
  30759. this._tmpVec5 = BABYLON.Vector3.Zero();
  30760. this._tmpMat1 = BABYLON.Matrix.Identity();
  30761. this._tmpMat2 = BABYLON.Matrix.Identity();
  30762. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30763. this._rightHandedSystem = false;
  30764. this._bendAxis = BABYLON.Vector3.Right();
  30765. this._slerping = false;
  30766. this._bone2 = bone;
  30767. this._bone1 = bone.getParent();
  30768. this.mesh = mesh;
  30769. if (bone.getAbsoluteTransform().determinant() > 0) {
  30770. this._rightHandedSystem = true;
  30771. this._bendAxis.x = 0;
  30772. this._bendAxis.y = 0;
  30773. this._bendAxis.z = 1;
  30774. }
  30775. if (this._bone1.length) {
  30776. var boneScale1 = this._bone1.getScale();
  30777. var boneScale2 = this._bone2.getScale();
  30778. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30779. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30780. }
  30781. else if (this._bone1.children[0]) {
  30782. mesh.computeWorldMatrix(true);
  30783. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30784. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30785. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30786. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30787. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30788. }
  30789. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30790. this.maxAngle = Math.PI;
  30791. if (options) {
  30792. if (options.targetMesh) {
  30793. this.targetMesh = options.targetMesh;
  30794. this.targetMesh.computeWorldMatrix(true);
  30795. }
  30796. if (options.poleTargetMesh) {
  30797. this.poleTargetMesh = options.poleTargetMesh;
  30798. this.poleTargetMesh.computeWorldMatrix(true);
  30799. }
  30800. else if (options.poleTargetBone) {
  30801. this.poleTargetBone = options.poleTargetBone;
  30802. }
  30803. else if (this._bone1.getParent()) {
  30804. this.poleTargetBone = this._bone1.getParent();
  30805. }
  30806. if (options.poleTargetLocalOffset) {
  30807. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30808. }
  30809. if (options.poleAngle) {
  30810. this.poleAngle = options.poleAngle;
  30811. }
  30812. if (options.bendAxis) {
  30813. this._bendAxis.copyFrom(options.bendAxis);
  30814. }
  30815. if (options.maxAngle) {
  30816. this.maxAngle = options.maxAngle;
  30817. }
  30818. if (options.slerpAmount) {
  30819. this.slerpAmount = options.slerpAmount;
  30820. }
  30821. }
  30822. }
  30823. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30824. get: function () {
  30825. return this._maxAngle;
  30826. },
  30827. set: function (value) {
  30828. this._setMaxAngle(value);
  30829. },
  30830. enumerable: true,
  30831. configurable: true
  30832. });
  30833. BoneIKController.prototype._setMaxAngle = function (ang) {
  30834. if (ang < 0) {
  30835. ang = 0;
  30836. }
  30837. if (ang > Math.PI || ang == undefined) {
  30838. ang = Math.PI;
  30839. }
  30840. this._maxAngle = ang;
  30841. var a = this._bone1Length;
  30842. var b = this._bone2Length;
  30843. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30844. };
  30845. BoneIKController.prototype.update = function () {
  30846. var bone1 = this._bone1;
  30847. var target = this.targetPosition;
  30848. var poleTarget = this.poleTargetPosition;
  30849. var mat1 = this._tmpMat1;
  30850. var mat2 = this._tmpMat2;
  30851. if (this.targetMesh) {
  30852. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30853. }
  30854. if (this.poleTargetBone) {
  30855. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30856. }
  30857. else if (this.poleTargetMesh) {
  30858. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30859. }
  30860. var bonePos = this._tmpVec1;
  30861. var zaxis = this._tmpVec2;
  30862. var xaxis = this._tmpVec3;
  30863. var yaxis = this._tmpVec4;
  30864. var upAxis = this._tmpVec5;
  30865. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30866. poleTarget.subtractToRef(bonePos, upAxis);
  30867. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30868. upAxis.y = 1;
  30869. }
  30870. else {
  30871. upAxis.normalize();
  30872. }
  30873. target.subtractToRef(bonePos, yaxis);
  30874. yaxis.normalize();
  30875. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30876. zaxis.normalize();
  30877. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30878. xaxis.normalize();
  30879. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30880. var a = this._bone1Length;
  30881. var b = this._bone2Length;
  30882. var c = BABYLON.Vector3.Distance(bonePos, target);
  30883. if (this._maxReach > 0) {
  30884. c = Math.min(this._maxReach, c);
  30885. }
  30886. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30887. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30888. if (acosa > 1) {
  30889. acosa = 1;
  30890. }
  30891. if (acosb > 1) {
  30892. acosb = 1;
  30893. }
  30894. if (acosa < -1) {
  30895. acosa = -1;
  30896. }
  30897. if (acosb < -1) {
  30898. acosb = -1;
  30899. }
  30900. var angA = Math.acos(acosa);
  30901. var angB = Math.acos(acosb);
  30902. var angC = -angA - angB;
  30903. if (this._rightHandedSystem) {
  30904. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30905. mat2.multiplyToRef(mat1, mat1);
  30906. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30907. mat2.multiplyToRef(mat1, mat1);
  30908. }
  30909. else {
  30910. this._tmpVec1.copyFrom(this._bendAxis);
  30911. this._tmpVec1.x *= -1;
  30912. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30913. mat2.multiplyToRef(mat1, mat1);
  30914. }
  30915. if (this.poleAngle) {
  30916. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30917. mat1.multiplyToRef(mat2, mat1);
  30918. }
  30919. if (this.slerpAmount < 1) {
  30920. if (!this._slerping) {
  30921. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30922. }
  30923. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30924. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30925. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30926. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30927. this._slerping = true;
  30928. }
  30929. else {
  30930. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30931. this._bone1Mat.copyFrom(mat1);
  30932. this._slerping = false;
  30933. }
  30934. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30935. this._bone2Ang = angC;
  30936. };
  30937. return BoneIKController;
  30938. }());
  30939. BABYLON.BoneIKController = BoneIKController;
  30940. })(BABYLON || (BABYLON = {}));
  30941. //# sourceMappingURL=babylon.boneIKController.js.map
  30942. var BABYLON;
  30943. (function (BABYLON) {
  30944. var BoneLookController = (function () {
  30945. function BoneLookController(mesh, bone, target, options) {
  30946. this.upAxis = BABYLON.Vector3.Up();
  30947. this.adjustYaw = 0;
  30948. this.adjustPitch = 0;
  30949. this.adjustRoll = 0;
  30950. this._tmpVec1 = BABYLON.Vector3.Zero();
  30951. this._tmpVec2 = BABYLON.Vector3.Zero();
  30952. this._tmpVec3 = BABYLON.Vector3.Zero();
  30953. this._tmpVec4 = BABYLON.Vector3.Zero();
  30954. this._tmpMat1 = BABYLON.Matrix.Identity();
  30955. this._tmpMat2 = BABYLON.Matrix.Identity();
  30956. this.mesh = mesh;
  30957. this.bone = bone;
  30958. this.target = target;
  30959. if (options) {
  30960. if (options.adjustYaw) {
  30961. this.adjustYaw = options.adjustYaw;
  30962. }
  30963. if (options.adjustPitch) {
  30964. this.adjustPitch = options.adjustPitch;
  30965. }
  30966. if (options.adjustRoll) {
  30967. this.adjustRoll = options.adjustRoll;
  30968. }
  30969. }
  30970. }
  30971. BoneLookController.prototype.update = function () {
  30972. var bone = this.bone;
  30973. var target = this.target;
  30974. var bonePos = this._tmpVec1;
  30975. var zaxis = this._tmpVec2;
  30976. var xaxis = this._tmpVec3;
  30977. var yaxis = this._tmpVec4;
  30978. var mat1 = this._tmpMat1;
  30979. var mat2 = this._tmpMat2;
  30980. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30981. target.subtractToRef(bonePos, zaxis);
  30982. zaxis.normalize();
  30983. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30984. xaxis.normalize();
  30985. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30986. yaxis.normalize();
  30987. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30988. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30989. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30990. mat2.multiplyToRef(mat1, mat1);
  30991. }
  30992. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30993. };
  30994. return BoneLookController;
  30995. }());
  30996. BABYLON.BoneLookController = BoneLookController;
  30997. })(BABYLON || (BABYLON = {}));
  30998. //# sourceMappingURL=babylon.boneLookController.js.map
  30999. var BABYLON;
  31000. (function (BABYLON) {
  31001. var Skeleton = (function () {
  31002. function Skeleton(name, id, scene) {
  31003. this.name = name;
  31004. this.id = id;
  31005. this.bones = new Array();
  31006. this.needInitialSkinMatrix = false;
  31007. this._isDirty = true;
  31008. this._meshesWithPoseMatrix = new Array();
  31009. this._identity = BABYLON.Matrix.Identity();
  31010. this._ranges = {};
  31011. this._lastAbsoluteTransformsUpdateId = -1;
  31012. this.bones = [];
  31013. this._scene = scene;
  31014. scene.skeletons.push(this);
  31015. //make sure it will recalculate the matrix next time prepare is called.
  31016. this._isDirty = true;
  31017. }
  31018. // Members
  31019. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31020. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31021. return mesh._bonesTransformMatrices;
  31022. }
  31023. if (!this._transformMatrices) {
  31024. this.prepare();
  31025. }
  31026. return this._transformMatrices;
  31027. };
  31028. Skeleton.prototype.getScene = function () {
  31029. return this._scene;
  31030. };
  31031. // Methods
  31032. /**
  31033. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31034. */
  31035. Skeleton.prototype.toString = function (fullDetails) {
  31036. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31037. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31038. if (fullDetails) {
  31039. ret += ", Ranges: {";
  31040. var first = true;
  31041. for (var name_1 in this._ranges) {
  31042. if (first) {
  31043. ret += ", ";
  31044. first = false;
  31045. }
  31046. ret += name_1;
  31047. }
  31048. ret += "}";
  31049. }
  31050. return ret;
  31051. };
  31052. /**
  31053. * Get bone's index searching by name
  31054. * @param {string} name is bone's name to search for
  31055. * @return {number} Indice of the bone. Returns -1 if not found
  31056. */
  31057. Skeleton.prototype.getBoneIndexByName = function (name) {
  31058. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31059. if (this.bones[boneIndex].name === name) {
  31060. return boneIndex;
  31061. }
  31062. }
  31063. return -1;
  31064. };
  31065. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31066. // check name not already in use
  31067. if (!this._ranges[name]) {
  31068. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31069. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31070. if (this.bones[i].animations[0]) {
  31071. this.bones[i].animations[0].createRange(name, from, to);
  31072. }
  31073. }
  31074. }
  31075. };
  31076. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31077. if (deleteFrames === void 0) { deleteFrames = true; }
  31078. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31079. if (this.bones[i].animations[0]) {
  31080. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31081. }
  31082. }
  31083. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31084. };
  31085. Skeleton.prototype.getAnimationRange = function (name) {
  31086. return this._ranges[name];
  31087. };
  31088. /**
  31089. * Returns as an Array, all AnimationRanges defined on this skeleton
  31090. */
  31091. Skeleton.prototype.getAnimationRanges = function () {
  31092. var animationRanges = [];
  31093. var name;
  31094. var i = 0;
  31095. for (name in this._ranges) {
  31096. animationRanges[i] = this._ranges[name];
  31097. i++;
  31098. }
  31099. return animationRanges;
  31100. };
  31101. /**
  31102. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31103. */
  31104. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31105. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31106. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31107. return false;
  31108. }
  31109. var ret = true;
  31110. var frameOffset = this._getHighestAnimationFrame() + 1;
  31111. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31112. var boneDict = {};
  31113. var sourceBones = source.bones;
  31114. var nBones;
  31115. var i;
  31116. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31117. boneDict[sourceBones[i].name] = sourceBones[i];
  31118. }
  31119. if (this.bones.length !== sourceBones.length) {
  31120. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31121. ret = false;
  31122. }
  31123. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31124. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31125. var boneName = this.bones[i].name;
  31126. var sourceBone = boneDict[boneName];
  31127. if (sourceBone) {
  31128. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31129. }
  31130. else {
  31131. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31132. ret = false;
  31133. }
  31134. }
  31135. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31136. var range = source.getAnimationRange(name);
  31137. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31138. return ret;
  31139. };
  31140. Skeleton.prototype.returnToRest = function () {
  31141. for (var index = 0; index < this.bones.length; index++) {
  31142. this.bones[index].returnToRest();
  31143. }
  31144. };
  31145. Skeleton.prototype._getHighestAnimationFrame = function () {
  31146. var ret = 0;
  31147. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31148. if (this.bones[i].animations[0]) {
  31149. var highest = this.bones[i].animations[0].getHighestFrame();
  31150. if (ret < highest) {
  31151. ret = highest;
  31152. }
  31153. }
  31154. }
  31155. return ret;
  31156. };
  31157. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31158. var range = this.getAnimationRange(name);
  31159. if (!range) {
  31160. return null;
  31161. }
  31162. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31163. };
  31164. Skeleton.prototype._markAsDirty = function () {
  31165. this._isDirty = true;
  31166. };
  31167. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31168. this._meshesWithPoseMatrix.push(mesh);
  31169. };
  31170. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31171. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31172. if (index > -1) {
  31173. this._meshesWithPoseMatrix.splice(index, 1);
  31174. }
  31175. };
  31176. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31177. for (var index = 0; index < this.bones.length; index++) {
  31178. var bone = this.bones[index];
  31179. var parentBone = bone.getParent();
  31180. if (parentBone) {
  31181. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31182. }
  31183. else {
  31184. if (initialSkinMatrix) {
  31185. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31186. }
  31187. else {
  31188. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31189. }
  31190. }
  31191. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31192. }
  31193. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31194. };
  31195. Skeleton.prototype.prepare = function () {
  31196. if (!this._isDirty) {
  31197. return;
  31198. }
  31199. if (this.needInitialSkinMatrix) {
  31200. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31201. var mesh = this._meshesWithPoseMatrix[index];
  31202. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31203. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31204. }
  31205. var poseMatrix = mesh.getPoseMatrix();
  31206. // Prepare bones
  31207. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31208. var bone = this.bones[boneIndex];
  31209. if (!bone.getParent()) {
  31210. var matrix = bone.getBaseMatrix();
  31211. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31212. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31213. }
  31214. }
  31215. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31216. }
  31217. }
  31218. else {
  31219. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31220. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31221. }
  31222. this._computeTransformMatrices(this._transformMatrices, null);
  31223. }
  31224. this._isDirty = false;
  31225. this._scene._activeBones.addCount(this.bones.length, false);
  31226. };
  31227. Skeleton.prototype.getAnimatables = function () {
  31228. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31229. this._animatables = [];
  31230. for (var index = 0; index < this.bones.length; index++) {
  31231. this._animatables.push(this.bones[index]);
  31232. }
  31233. }
  31234. return this._animatables;
  31235. };
  31236. Skeleton.prototype.clone = function (name, id) {
  31237. var result = new Skeleton(name, id || name, this._scene);
  31238. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31239. for (var index = 0; index < this.bones.length; index++) {
  31240. var source = this.bones[index];
  31241. var parentBone = null;
  31242. if (source.getParent()) {
  31243. var parentIndex = this.bones.indexOf(source.getParent());
  31244. parentBone = result.bones[parentIndex];
  31245. }
  31246. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31247. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31248. }
  31249. if (this._ranges) {
  31250. result._ranges = {};
  31251. for (var rangeName in this._ranges) {
  31252. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31253. }
  31254. }
  31255. this._isDirty = true;
  31256. return result;
  31257. };
  31258. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31259. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31260. this.bones.forEach(function (bone) {
  31261. bone.animations.forEach(function (animation) {
  31262. animation.enableBlending = true;
  31263. animation.blendingSpeed = blendingSpeed;
  31264. });
  31265. });
  31266. };
  31267. Skeleton.prototype.dispose = function () {
  31268. this._meshesWithPoseMatrix = [];
  31269. // Animations
  31270. this.getScene().stopAnimation(this);
  31271. // Remove from scene
  31272. this.getScene().removeSkeleton(this);
  31273. };
  31274. Skeleton.prototype.serialize = function () {
  31275. var serializationObject = {};
  31276. serializationObject.name = this.name;
  31277. serializationObject.id = this.id;
  31278. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31279. serializationObject.bones = [];
  31280. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31281. for (var index = 0; index < this.bones.length; index++) {
  31282. var bone = this.bones[index];
  31283. var serializedBone = {
  31284. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31285. name: bone.name,
  31286. matrix: bone.getLocalMatrix().toArray(),
  31287. rest: bone.getRestPose().toArray()
  31288. };
  31289. serializationObject.bones.push(serializedBone);
  31290. if (bone.length) {
  31291. serializedBone.length = bone.length;
  31292. }
  31293. if (bone.animations && bone.animations.length > 0) {
  31294. serializedBone.animation = bone.animations[0].serialize();
  31295. }
  31296. serializationObject.ranges = [];
  31297. for (var name in this._ranges) {
  31298. var range = {};
  31299. range.name = name;
  31300. range.from = this._ranges[name].from;
  31301. range.to = this._ranges[name].to;
  31302. serializationObject.ranges.push(range);
  31303. }
  31304. }
  31305. return serializationObject;
  31306. };
  31307. Skeleton.Parse = function (parsedSkeleton, scene) {
  31308. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31309. if (parsedSkeleton.dimensionsAtRest) {
  31310. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31311. }
  31312. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31313. var index;
  31314. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31315. var parsedBone = parsedSkeleton.bones[index];
  31316. var parentBone = null;
  31317. if (parsedBone.parentBoneIndex > -1) {
  31318. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31319. }
  31320. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31321. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31322. if (parsedBone.length) {
  31323. bone.length = parsedBone.length;
  31324. }
  31325. if (parsedBone.animation) {
  31326. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31327. }
  31328. }
  31329. // placed after bones, so createAnimationRange can cascade down
  31330. if (parsedSkeleton.ranges) {
  31331. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31332. var data = parsedSkeleton.ranges[index];
  31333. skeleton.createAnimationRange(data.name, data.from, data.to);
  31334. }
  31335. }
  31336. return skeleton;
  31337. };
  31338. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31339. if (forceUpdate === void 0) { forceUpdate = false; }
  31340. var renderId = this._scene.getRenderId();
  31341. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31342. this.bones[0].computeAbsoluteTransforms();
  31343. this._lastAbsoluteTransformsUpdateId = renderId;
  31344. }
  31345. };
  31346. Skeleton.prototype.getPoseMatrix = function () {
  31347. var poseMatrix;
  31348. if (this._meshesWithPoseMatrix.length > 0) {
  31349. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31350. }
  31351. return poseMatrix;
  31352. };
  31353. return Skeleton;
  31354. }());
  31355. BABYLON.Skeleton = Skeleton;
  31356. })(BABYLON || (BABYLON = {}));
  31357. //# sourceMappingURL=babylon.skeleton.js.map
  31358. var BABYLON;
  31359. (function (BABYLON) {
  31360. var PostProcess = (function () {
  31361. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31364. this.name = name;
  31365. this.width = -1;
  31366. this.height = -1;
  31367. /*
  31368. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31369. Can only be used on a single postprocess or on the last one of a chain.
  31370. */
  31371. this.enablePixelPerfectMode = false;
  31372. this._reusable = false;
  31373. this._textures = new BABYLON.SmartArray(2);
  31374. this._currentRenderTextureInd = 0;
  31375. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31376. // Events
  31377. /**
  31378. * An event triggered when the postprocess is activated.
  31379. * @type {BABYLON.Observable}
  31380. */
  31381. this.onActivateObservable = new BABYLON.Observable();
  31382. /**
  31383. * An event triggered when the postprocess changes its size.
  31384. * @type {BABYLON.Observable}
  31385. */
  31386. this.onSizeChangedObservable = new BABYLON.Observable();
  31387. /**
  31388. * An event triggered when the postprocess applies its effect.
  31389. * @type {BABYLON.Observable}
  31390. */
  31391. this.onApplyObservable = new BABYLON.Observable();
  31392. /**
  31393. * An event triggered before rendering the postprocess
  31394. * @type {BABYLON.Observable}
  31395. */
  31396. this.onBeforeRenderObservable = new BABYLON.Observable();
  31397. /**
  31398. * An event triggered after rendering the postprocess
  31399. * @type {BABYLON.Observable}
  31400. */
  31401. this.onAfterRenderObservable = new BABYLON.Observable();
  31402. if (camera != null) {
  31403. this._camera = camera;
  31404. this._scene = camera.getScene();
  31405. camera.attachPostProcess(this);
  31406. this._engine = this._scene.getEngine();
  31407. }
  31408. else {
  31409. this._engine = engine;
  31410. }
  31411. this._options = options;
  31412. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31413. this._reusable = reusable || false;
  31414. this._textureType = textureType;
  31415. this._samplers = samplers || [];
  31416. this._samplers.push("textureSampler");
  31417. this._fragmentUrl = fragmentUrl;
  31418. this._parameters = parameters || [];
  31419. this._parameters.push("scale");
  31420. this.updateEffect(defines);
  31421. }
  31422. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31423. set: function (callback) {
  31424. if (this._onActivateObserver) {
  31425. this.onActivateObservable.remove(this._onActivateObserver);
  31426. }
  31427. this._onActivateObserver = this.onActivateObservable.add(callback);
  31428. },
  31429. enumerable: true,
  31430. configurable: true
  31431. });
  31432. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31433. set: function (callback) {
  31434. if (this._onSizeChangedObserver) {
  31435. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31436. }
  31437. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31438. },
  31439. enumerable: true,
  31440. configurable: true
  31441. });
  31442. Object.defineProperty(PostProcess.prototype, "onApply", {
  31443. set: function (callback) {
  31444. if (this._onApplyObserver) {
  31445. this.onApplyObservable.remove(this._onApplyObserver);
  31446. }
  31447. this._onApplyObserver = this.onApplyObservable.add(callback);
  31448. },
  31449. enumerable: true,
  31450. configurable: true
  31451. });
  31452. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31453. set: function (callback) {
  31454. if (this._onBeforeRenderObserver) {
  31455. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31456. }
  31457. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31463. set: function (callback) {
  31464. if (this._onAfterRenderObserver) {
  31465. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31466. }
  31467. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. PostProcess.prototype.updateEffect = function (defines) {
  31473. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31474. };
  31475. PostProcess.prototype.isReusable = function () {
  31476. return this._reusable;
  31477. };
  31478. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31479. PostProcess.prototype.markTextureDirty = function () {
  31480. this.width = -1;
  31481. };
  31482. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31483. camera = camera || this._camera;
  31484. var scene = camera.getScene();
  31485. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31486. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31487. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31488. var desiredWidth = this._options.width || requiredWidth;
  31489. var desiredHeight = this._options.height || requiredHeight;
  31490. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31491. if (!this._options.width) {
  31492. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31493. }
  31494. if (!this._options.height) {
  31495. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31496. }
  31497. }
  31498. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31499. if (this._textures.length > 0) {
  31500. for (var i = 0; i < this._textures.length; i++) {
  31501. this._engine._releaseTexture(this._textures.data[i]);
  31502. }
  31503. this._textures.reset();
  31504. }
  31505. this.width = desiredWidth;
  31506. this.height = desiredHeight;
  31507. var textureSize = { width: this.width, height: this.height };
  31508. var textureOptions = {
  31509. generateMipMaps: false,
  31510. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31511. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31512. samplingMode: this.renderTargetSamplingMode,
  31513. type: this._textureType
  31514. };
  31515. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31516. if (this._reusable) {
  31517. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31518. }
  31519. this.onSizeChangedObservable.notifyObservers(this);
  31520. }
  31521. if (this.enablePixelPerfectMode) {
  31522. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31523. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31524. }
  31525. else {
  31526. this._scaleRatio.copyFromFloats(1, 1);
  31527. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31528. }
  31529. this.onActivateObservable.notifyObservers(camera);
  31530. // Clear
  31531. if (this.clearColor) {
  31532. this._engine.clear(this.clearColor, true, true, true);
  31533. }
  31534. else {
  31535. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31536. }
  31537. if (this._reusable) {
  31538. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31539. }
  31540. };
  31541. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31542. get: function () {
  31543. return this._effect.isSupported;
  31544. },
  31545. enumerable: true,
  31546. configurable: true
  31547. });
  31548. PostProcess.prototype.apply = function () {
  31549. // Check
  31550. if (!this._effect.isReady())
  31551. return null;
  31552. // States
  31553. this._engine.enableEffect(this._effect);
  31554. this._engine.setState(false);
  31555. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31556. this._engine.setDepthBuffer(false);
  31557. this._engine.setDepthWrite(false);
  31558. // Texture
  31559. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31560. // Parameters
  31561. this._effect.setVector2("scale", this._scaleRatio);
  31562. this.onApplyObservable.notifyObservers(this._effect);
  31563. return this._effect;
  31564. };
  31565. PostProcess.prototype.dispose = function (camera) {
  31566. camera = camera || this._camera;
  31567. if (this._textures.length > 0) {
  31568. for (var i = 0; i < this._textures.length; i++) {
  31569. this._engine._releaseTexture(this._textures.data[i]);
  31570. }
  31571. this._textures.reset();
  31572. }
  31573. if (!camera) {
  31574. return;
  31575. }
  31576. camera.detachPostProcess(this);
  31577. var index = camera._postProcesses.indexOf(this);
  31578. if (index === 0 && camera._postProcesses.length > 0) {
  31579. this._camera._postProcesses[0].markTextureDirty();
  31580. }
  31581. this.onActivateObservable.clear();
  31582. this.onAfterRenderObservable.clear();
  31583. this.onApplyObservable.clear();
  31584. this.onBeforeRenderObservable.clear();
  31585. this.onSizeChangedObservable.clear();
  31586. };
  31587. return PostProcess;
  31588. }());
  31589. BABYLON.PostProcess = PostProcess;
  31590. })(BABYLON || (BABYLON = {}));
  31591. //# sourceMappingURL=babylon.postProcess.js.map
  31592. var BABYLON;
  31593. (function (BABYLON) {
  31594. var PostProcessManager = (function () {
  31595. function PostProcessManager(scene) {
  31596. this._vertexBuffers = {};
  31597. this._scene = scene;
  31598. }
  31599. PostProcessManager.prototype._prepareBuffers = function () {
  31600. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31601. return;
  31602. }
  31603. // VBO
  31604. var vertices = [];
  31605. vertices.push(1, 1);
  31606. vertices.push(-1, 1);
  31607. vertices.push(-1, -1);
  31608. vertices.push(1, -1);
  31609. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31610. // Indices
  31611. var indices = [];
  31612. indices.push(0);
  31613. indices.push(1);
  31614. indices.push(2);
  31615. indices.push(0);
  31616. indices.push(2);
  31617. indices.push(3);
  31618. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31619. };
  31620. // Methods
  31621. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31622. var postProcesses = this._scene.activeCamera._postProcesses;
  31623. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31624. return false;
  31625. }
  31626. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31627. return true;
  31628. };
  31629. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31630. var engine = this._scene.getEngine();
  31631. for (var index = 0; index < postProcesses.length; index++) {
  31632. if (index < postProcesses.length - 1) {
  31633. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31634. }
  31635. else {
  31636. if (targetTexture) {
  31637. engine.bindFramebuffer(targetTexture);
  31638. }
  31639. else {
  31640. engine.restoreDefaultFramebuffer();
  31641. }
  31642. }
  31643. var pp = postProcesses[index];
  31644. var effect = pp.apply();
  31645. if (effect) {
  31646. pp.onBeforeRenderObservable.notifyObservers(effect);
  31647. // VBOs
  31648. this._prepareBuffers();
  31649. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31650. // Draw order
  31651. engine.draw(true, 0, 6);
  31652. pp.onAfterRenderObservable.notifyObservers(effect);
  31653. }
  31654. }
  31655. // Restore depth buffer
  31656. engine.setDepthBuffer(true);
  31657. engine.setDepthWrite(true);
  31658. };
  31659. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31660. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31661. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31662. return;
  31663. }
  31664. var engine = this._scene.getEngine();
  31665. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31666. if (index < len - 1) {
  31667. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31668. }
  31669. else {
  31670. if (targetTexture) {
  31671. engine.bindFramebuffer(targetTexture, faceIndex);
  31672. }
  31673. else {
  31674. engine.restoreDefaultFramebuffer();
  31675. }
  31676. }
  31677. if (doNotPresent) {
  31678. break;
  31679. }
  31680. var pp = postProcesses[index];
  31681. var effect = pp.apply();
  31682. if (effect) {
  31683. pp.onBeforeRenderObservable.notifyObservers(effect);
  31684. // VBOs
  31685. this._prepareBuffers();
  31686. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31687. // Draw order
  31688. engine.draw(true, 0, 6);
  31689. pp.onAfterRenderObservable.notifyObservers(effect);
  31690. }
  31691. }
  31692. // Restore depth buffer
  31693. engine.setDepthBuffer(true);
  31694. engine.setDepthWrite(true);
  31695. };
  31696. PostProcessManager.prototype.dispose = function () {
  31697. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31698. if (buffer) {
  31699. buffer.dispose();
  31700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31701. }
  31702. if (this._indexBuffer) {
  31703. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31704. this._indexBuffer = null;
  31705. }
  31706. };
  31707. return PostProcessManager;
  31708. }());
  31709. BABYLON.PostProcessManager = PostProcessManager;
  31710. })(BABYLON || (BABYLON = {}));
  31711. //# sourceMappingURL=babylon.postProcessManager.js.map
  31712. var BABYLON;
  31713. (function (BABYLON) {
  31714. var PassPostProcess = (function (_super) {
  31715. __extends(PassPostProcess, _super);
  31716. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31717. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  31718. }
  31719. return PassPostProcess;
  31720. }(BABYLON.PostProcess));
  31721. BABYLON.PassPostProcess = PassPostProcess;
  31722. })(BABYLON || (BABYLON = {}));
  31723. //# sourceMappingURL=babylon.passPostProcess.js.map
  31724. var BABYLON;
  31725. (function (BABYLON) {
  31726. /**
  31727. * This is a holder class for the physics joint created by the physics plugin.
  31728. * It holds a set of functions to control the underlying joint.
  31729. */
  31730. var PhysicsJoint = (function () {
  31731. function PhysicsJoint(type, jointData) {
  31732. this.type = type;
  31733. this.jointData = jointData;
  31734. jointData.nativeParams = jointData.nativeParams || {};
  31735. }
  31736. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31737. get: function () {
  31738. return this._physicsJoint;
  31739. },
  31740. set: function (newJoint) {
  31741. if (this._physicsJoint) {
  31742. }
  31743. this._physicsJoint = newJoint;
  31744. },
  31745. enumerable: true,
  31746. configurable: true
  31747. });
  31748. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31749. set: function (physicsPlugin) {
  31750. this._physicsPlugin = physicsPlugin;
  31751. },
  31752. enumerable: true,
  31753. configurable: true
  31754. });
  31755. /**
  31756. * Execute a function that is physics-plugin specific.
  31757. * @param {Function} func the function that will be executed.
  31758. * It accepts two parameters: the physics world and the physics joint.
  31759. */
  31760. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31761. func(this._physicsPlugin.world, this._physicsJoint);
  31762. };
  31763. return PhysicsJoint;
  31764. }());
  31765. //TODO check if the native joints are the same
  31766. //Joint Types
  31767. PhysicsJoint.DistanceJoint = 0;
  31768. PhysicsJoint.HingeJoint = 1;
  31769. PhysicsJoint.BallAndSocketJoint = 2;
  31770. PhysicsJoint.WheelJoint = 3;
  31771. PhysicsJoint.SliderJoint = 4;
  31772. //OIMO
  31773. PhysicsJoint.PrismaticJoint = 5;
  31774. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31775. PhysicsJoint.UniversalJoint = 6;
  31776. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31777. //Cannon
  31778. //Similar to a Ball-Joint. Different in params
  31779. PhysicsJoint.PointToPointJoint = 8;
  31780. //Cannon only at the moment
  31781. PhysicsJoint.SpringJoint = 9;
  31782. PhysicsJoint.LockJoint = 10;
  31783. BABYLON.PhysicsJoint = PhysicsJoint;
  31784. /**
  31785. * A class representing a physics distance joint.
  31786. */
  31787. var DistanceJoint = (function (_super) {
  31788. __extends(DistanceJoint, _super);
  31789. function DistanceJoint(jointData) {
  31790. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  31791. }
  31792. /**
  31793. * Update the predefined distance.
  31794. */
  31795. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31796. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31797. };
  31798. return DistanceJoint;
  31799. }(PhysicsJoint));
  31800. BABYLON.DistanceJoint = DistanceJoint;
  31801. var MotorEnabledJoint = (function (_super) {
  31802. __extends(MotorEnabledJoint, _super);
  31803. function MotorEnabledJoint(type, jointData) {
  31804. return _super.call(this, type, jointData) || this;
  31805. }
  31806. /**
  31807. * Set the motor values.
  31808. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31809. * @param {number} force the force to apply
  31810. * @param {number} maxForce max force for this motor.
  31811. */
  31812. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31813. this._physicsPlugin.setMotor(this, force, maxForce);
  31814. };
  31815. /**
  31816. * Set the motor's limits.
  31817. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31818. */
  31819. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31820. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31821. };
  31822. return MotorEnabledJoint;
  31823. }(PhysicsJoint));
  31824. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31825. /**
  31826. * This class represents a single hinge physics joint
  31827. */
  31828. var HingeJoint = (function (_super) {
  31829. __extends(HingeJoint, _super);
  31830. function HingeJoint(jointData) {
  31831. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  31832. }
  31833. /**
  31834. * Set the motor values.
  31835. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31836. * @param {number} force the force to apply
  31837. * @param {number} maxForce max force for this motor.
  31838. */
  31839. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31840. this._physicsPlugin.setMotor(this, force, maxForce);
  31841. };
  31842. /**
  31843. * Set the motor's limits.
  31844. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31845. */
  31846. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31847. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31848. };
  31849. return HingeJoint;
  31850. }(MotorEnabledJoint));
  31851. BABYLON.HingeJoint = HingeJoint;
  31852. /**
  31853. * This class represents a dual hinge physics joint (same as wheel joint)
  31854. */
  31855. var Hinge2Joint = (function (_super) {
  31856. __extends(Hinge2Joint, _super);
  31857. function Hinge2Joint(jointData) {
  31858. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  31859. }
  31860. /**
  31861. * Set the motor values.
  31862. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31863. * @param {number} force the force to apply
  31864. * @param {number} maxForce max force for this motor.
  31865. * @param {motorIndex} the motor's index, 0 or 1.
  31866. */
  31867. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31868. if (motorIndex === void 0) { motorIndex = 0; }
  31869. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31870. };
  31871. /**
  31872. * Set the motor limits.
  31873. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31874. * @param {number} upperLimit the upper limit
  31875. * @param {number} lowerLimit lower limit
  31876. * @param {motorIndex} the motor's index, 0 or 1.
  31877. */
  31878. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31879. if (motorIndex === void 0) { motorIndex = 0; }
  31880. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31881. };
  31882. return Hinge2Joint;
  31883. }(MotorEnabledJoint));
  31884. BABYLON.Hinge2Joint = Hinge2Joint;
  31885. })(BABYLON || (BABYLON = {}));
  31886. //# sourceMappingURL=babylon.physicsJoint.js.map
  31887. var BABYLON;
  31888. (function (BABYLON) {
  31889. var PhysicsImpostor = (function () {
  31890. function PhysicsImpostor(object, type, _options, _scene) {
  31891. if (_options === void 0) { _options = { mass: 0 }; }
  31892. var _this = this;
  31893. this.object = object;
  31894. this.type = type;
  31895. this._options = _options;
  31896. this._scene = _scene;
  31897. this._bodyUpdateRequired = false;
  31898. this._onBeforePhysicsStepCallbacks = new Array();
  31899. this._onAfterPhysicsStepCallbacks = new Array();
  31900. this._onPhysicsCollideCallbacks = [];
  31901. this._deltaPosition = BABYLON.Vector3.Zero();
  31902. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31903. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31904. /**
  31905. * this function is executed by the physics engine.
  31906. */
  31907. this.beforeStep = function () {
  31908. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31909. //conjugate deltaRotation
  31910. if (_this._deltaRotationConjugated) {
  31911. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31912. }
  31913. else {
  31914. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31915. }
  31916. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31917. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31918. func(_this);
  31919. });
  31920. };
  31921. /**
  31922. * this function is executed by the physics engine.
  31923. */
  31924. this.afterStep = function () {
  31925. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31926. func(_this);
  31927. });
  31928. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31929. _this.object.position.addInPlace(_this._deltaPosition);
  31930. if (_this._deltaRotation) {
  31931. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31932. }
  31933. };
  31934. //event and body object due to cannon's event-based architecture.
  31935. this.onCollide = function (e) {
  31936. if (!_this._onPhysicsCollideCallbacks.length)
  31937. return;
  31938. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31939. if (otherImpostor) {
  31940. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31941. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31942. }).forEach(function (obj) {
  31943. obj.callback(_this, otherImpostor);
  31944. });
  31945. }
  31946. };
  31947. //sanity check!
  31948. if (!this.object) {
  31949. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31950. return;
  31951. }
  31952. //legacy support for old syntax.
  31953. if (!this._scene && object.getScene) {
  31954. this._scene = object.getScene();
  31955. }
  31956. this._physicsEngine = this._scene.getPhysicsEngine();
  31957. if (!this._physicsEngine) {
  31958. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31959. }
  31960. else {
  31961. //set the object's quaternion, if not set
  31962. if (!this.object.rotationQuaternion) {
  31963. if (this.object.rotation) {
  31964. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31965. }
  31966. else {
  31967. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31968. }
  31969. }
  31970. //default options params
  31971. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31972. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31973. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31974. this._joints = [];
  31975. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31976. if (!this.object.parent) {
  31977. this._init();
  31978. }
  31979. }
  31980. }
  31981. /**
  31982. * This function will completly initialize this impostor.
  31983. * It will create a new body - but only if this mesh has no parent.
  31984. * If it has, this impostor will not be used other than to define the impostor
  31985. * of the child mesh.
  31986. */
  31987. PhysicsImpostor.prototype._init = function () {
  31988. this._physicsEngine.removeImpostor(this);
  31989. this.physicsBody = null;
  31990. this._parent = this._parent || this._getPhysicsParent();
  31991. if (!this.parent) {
  31992. this._physicsEngine.addImpostor(this);
  31993. }
  31994. };
  31995. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31996. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31997. var parentMesh = this.object.parent;
  31998. return parentMesh.physicsImpostor;
  31999. }
  32000. return;
  32001. };
  32002. /**
  32003. * Should a new body be generated.
  32004. */
  32005. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32006. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32007. };
  32008. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32009. this.forceUpdate();
  32010. };
  32011. /**
  32012. * Force a regeneration of this or the parent's impostor's body.
  32013. * Use under cautious - This will remove all joints already implemented.
  32014. */
  32015. PhysicsImpostor.prototype.forceUpdate = function () {
  32016. this._init();
  32017. if (this.parent) {
  32018. this.parent.forceUpdate();
  32019. }
  32020. };
  32021. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32022. /*public get mesh(): AbstractMesh {
  32023. return this._mesh;
  32024. }*/
  32025. /**
  32026. * Gets the body that holds this impostor. Either its own, or its parent.
  32027. */
  32028. get: function () {
  32029. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32030. },
  32031. /**
  32032. * Set the physics body. Used mainly by the physics engine/plugin
  32033. */
  32034. set: function (physicsBody) {
  32035. if (this._physicsBody) {
  32036. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32037. }
  32038. this._physicsBody = physicsBody;
  32039. this.resetUpdateFlags();
  32040. },
  32041. enumerable: true,
  32042. configurable: true
  32043. });
  32044. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32045. get: function () {
  32046. return this._parent;
  32047. },
  32048. set: function (value) {
  32049. this._parent = value;
  32050. },
  32051. enumerable: true,
  32052. configurable: true
  32053. });
  32054. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32055. this._bodyUpdateRequired = false;
  32056. };
  32057. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32058. if (this.object.getBoundingInfo) {
  32059. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32060. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32061. }
  32062. else {
  32063. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32064. }
  32065. };
  32066. PhysicsImpostor.prototype.getObjectCenter = function () {
  32067. if (this.object.getBoundingInfo) {
  32068. return this.object.getBoundingInfo().boundingBox.center;
  32069. }
  32070. else {
  32071. return this.object.position;
  32072. }
  32073. };
  32074. /**
  32075. * Get a specific parametes from the options parameter.
  32076. */
  32077. PhysicsImpostor.prototype.getParam = function (paramName) {
  32078. return this._options[paramName];
  32079. };
  32080. /**
  32081. * Sets a specific parameter in the options given to the physics plugin
  32082. */
  32083. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32084. this._options[paramName] = value;
  32085. this._bodyUpdateRequired = true;
  32086. };
  32087. /**
  32088. * Specifically change the body's mass option. Won't recreate the physics body object
  32089. */
  32090. PhysicsImpostor.prototype.setMass = function (mass) {
  32091. if (this.getParam("mass") !== mass) {
  32092. this.setParam("mass", mass);
  32093. }
  32094. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32095. };
  32096. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32097. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32098. };
  32099. /**
  32100. * Set the body's linear velocity.
  32101. */
  32102. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32103. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32104. };
  32105. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32106. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32107. };
  32108. /**
  32109. * Set the body's linear velocity.
  32110. */
  32111. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32112. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32113. };
  32114. /**
  32115. * Execute a function with the physics plugin native code.
  32116. * Provide a function the will have two variables - the world object and the physics body object.
  32117. */
  32118. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32119. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32120. };
  32121. /**
  32122. * Register a function that will be executed before the physics world is stepping forward.
  32123. */
  32124. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32125. this._onBeforePhysicsStepCallbacks.push(func);
  32126. };
  32127. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32128. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32129. if (index > -1) {
  32130. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32131. }
  32132. else {
  32133. BABYLON.Tools.Warn("Function to remove was not found");
  32134. }
  32135. };
  32136. /**
  32137. * Register a function that will be executed after the physics step
  32138. */
  32139. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32140. this._onAfterPhysicsStepCallbacks.push(func);
  32141. };
  32142. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32143. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32144. if (index > -1) {
  32145. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32146. }
  32147. else {
  32148. BABYLON.Tools.Warn("Function to remove was not found");
  32149. }
  32150. };
  32151. /**
  32152. * register a function that will be executed when this impostor collides against a different body.
  32153. */
  32154. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32155. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32156. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32157. };
  32158. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32159. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32160. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32161. if (index > -1) {
  32162. this._onPhysicsCollideCallbacks.splice(index, 1);
  32163. }
  32164. else {
  32165. BABYLON.Tools.Warn("Function to remove was not found");
  32166. }
  32167. };
  32168. /**
  32169. * Apply a force
  32170. */
  32171. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32172. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32173. };
  32174. /**
  32175. * Apply an impulse
  32176. */
  32177. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32178. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32179. };
  32180. /**
  32181. * A help function to create a joint.
  32182. */
  32183. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32184. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32185. this.addJoint(otherImpostor, joint);
  32186. };
  32187. /**
  32188. * Add a joint to this impostor with a different impostor.
  32189. */
  32190. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32191. this._joints.push({
  32192. otherImpostor: otherImpostor,
  32193. joint: joint
  32194. });
  32195. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32196. };
  32197. /**
  32198. * Will keep this body still, in a sleep mode.
  32199. */
  32200. PhysicsImpostor.prototype.sleep = function () {
  32201. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32202. };
  32203. /**
  32204. * Wake the body up.
  32205. */
  32206. PhysicsImpostor.prototype.wakeUp = function () {
  32207. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32208. };
  32209. PhysicsImpostor.prototype.clone = function (newObject) {
  32210. if (!newObject)
  32211. return null;
  32212. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32213. };
  32214. PhysicsImpostor.prototype.dispose = function () {
  32215. var _this = this;
  32216. //no dispose if no physics engine is available.
  32217. if (!this._physicsEngine) {
  32218. return;
  32219. }
  32220. this._joints.forEach(function (j) {
  32221. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32222. });
  32223. //dispose the physics body
  32224. this._physicsEngine.removeImpostor(this);
  32225. if (this.parent) {
  32226. this.parent.forceUpdate();
  32227. }
  32228. else {
  32229. }
  32230. };
  32231. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32232. this._deltaPosition.copyFrom(position);
  32233. };
  32234. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32235. if (!this._deltaRotation) {
  32236. this._deltaRotation = new BABYLON.Quaternion();
  32237. }
  32238. this._deltaRotation.copyFrom(rotation);
  32239. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32240. };
  32241. return PhysicsImpostor;
  32242. }());
  32243. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32244. //Impostor types
  32245. PhysicsImpostor.NoImpostor = 0;
  32246. PhysicsImpostor.SphereImpostor = 1;
  32247. PhysicsImpostor.BoxImpostor = 2;
  32248. PhysicsImpostor.PlaneImpostor = 3;
  32249. PhysicsImpostor.MeshImpostor = 4;
  32250. PhysicsImpostor.CylinderImpostor = 7;
  32251. PhysicsImpostor.ParticleImpostor = 8;
  32252. PhysicsImpostor.HeightmapImpostor = 9;
  32253. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32254. })(BABYLON || (BABYLON = {}));
  32255. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32256. var BABYLON;
  32257. (function (BABYLON) {
  32258. var PhysicsEngine = (function () {
  32259. function PhysicsEngine(gravity, _physicsPlugin) {
  32260. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32261. this._physicsPlugin = _physicsPlugin;
  32262. //new methods and parameters
  32263. this._impostors = [];
  32264. this._joints = [];
  32265. if (!this._physicsPlugin.isSupported()) {
  32266. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32267. + "Please make sure it is included.");
  32268. }
  32269. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32270. this.setGravity(gravity);
  32271. this.setTimeStep();
  32272. }
  32273. PhysicsEngine.prototype.setGravity = function (gravity) {
  32274. this.gravity = gravity;
  32275. this._physicsPlugin.setGravity(this.gravity);
  32276. };
  32277. /**
  32278. * Set the time step of the physics engine.
  32279. * default is 1/60.
  32280. * To slow it down, enter 1/600 for example.
  32281. * To speed it up, 1/30
  32282. * @param {number} newTimeStep the new timestep to apply to this world.
  32283. */
  32284. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32285. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32286. this._physicsPlugin.setTimeStep(newTimeStep);
  32287. };
  32288. PhysicsEngine.prototype.dispose = function () {
  32289. this._impostors.forEach(function (impostor) {
  32290. impostor.dispose();
  32291. });
  32292. this._physicsPlugin.dispose();
  32293. };
  32294. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32295. return this._physicsPlugin.name;
  32296. };
  32297. /**
  32298. * Adding a new impostor for the impostor tracking.
  32299. * This will be done by the impostor itself.
  32300. * @param {PhysicsImpostor} impostor the impostor to add
  32301. */
  32302. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32303. impostor.uniqueId = this._impostors.push(impostor);
  32304. //if no parent, generate the body
  32305. if (!impostor.parent) {
  32306. this._physicsPlugin.generatePhysicsBody(impostor);
  32307. }
  32308. };
  32309. /**
  32310. * Remove an impostor from the engine.
  32311. * This impostor and its mesh will not longer be updated by the physics engine.
  32312. * @param {PhysicsImpostor} impostor the impostor to remove
  32313. */
  32314. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32315. var index = this._impostors.indexOf(impostor);
  32316. if (index > -1) {
  32317. var removed = this._impostors.splice(index, 1);
  32318. //Is it needed?
  32319. if (removed.length) {
  32320. //this will also remove it from the world.
  32321. removed[0].physicsBody = null;
  32322. }
  32323. }
  32324. };
  32325. /**
  32326. * Add a joint to the physics engine
  32327. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32328. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32329. * @param {PhysicsJoint} the joint that will connect both impostors.
  32330. */
  32331. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32332. var impostorJoint = {
  32333. mainImpostor: mainImpostor,
  32334. connectedImpostor: connectedImpostor,
  32335. joint: joint
  32336. };
  32337. joint.physicsPlugin = this._physicsPlugin;
  32338. this._joints.push(impostorJoint);
  32339. this._physicsPlugin.generateJoint(impostorJoint);
  32340. };
  32341. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32342. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32343. return (impostorJoint.connectedImpostor === connectedImpostor
  32344. && impostorJoint.joint === joint
  32345. && impostorJoint.mainImpostor === mainImpostor);
  32346. });
  32347. if (matchingJoints.length) {
  32348. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32349. }
  32350. };
  32351. /**
  32352. * Called by the scene. no need to call it.
  32353. */
  32354. PhysicsEngine.prototype._step = function (delta) {
  32355. var _this = this;
  32356. //check if any mesh has no body / requires an update
  32357. this._impostors.forEach(function (impostor) {
  32358. if (impostor.isBodyInitRequired()) {
  32359. _this._physicsPlugin.generatePhysicsBody(impostor);
  32360. }
  32361. });
  32362. if (delta > 0.1) {
  32363. delta = 0.1;
  32364. }
  32365. else if (delta <= 0) {
  32366. delta = 1.0 / 60.0;
  32367. }
  32368. this._physicsPlugin.executeStep(delta, this._impostors);
  32369. };
  32370. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32371. return this._physicsPlugin;
  32372. };
  32373. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32374. for (var i = 0; i < this._impostors.length; ++i) {
  32375. if (this._impostors[i].object === object) {
  32376. return this._impostors[i];
  32377. }
  32378. }
  32379. };
  32380. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32381. for (var i = 0; i < this._impostors.length; ++i) {
  32382. if (this._impostors[i].physicsBody === body) {
  32383. return this._impostors[i];
  32384. }
  32385. }
  32386. };
  32387. return PhysicsEngine;
  32388. }());
  32389. // Statics, Legacy support.
  32390. /**
  32391. * @Deprecated
  32392. *
  32393. */
  32394. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32395. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32396. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32397. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32398. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32399. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32400. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32401. PhysicsEngine.CapsuleImpostor = -1;
  32402. PhysicsEngine.ConeImpostor = -1;
  32403. PhysicsEngine.ConvexHullImpostor = -1;
  32404. PhysicsEngine.Epsilon = 0.001;
  32405. BABYLON.PhysicsEngine = PhysicsEngine;
  32406. })(BABYLON || (BABYLON = {}));
  32407. //# sourceMappingURL=babylon.physicsEngine.js.map
  32408. var BABYLON;
  32409. (function (BABYLON) {
  32410. var VertexData = (function () {
  32411. function VertexData() {
  32412. }
  32413. VertexData.prototype.set = function (data, kind) {
  32414. switch (kind) {
  32415. case BABYLON.VertexBuffer.PositionKind:
  32416. this.positions = data;
  32417. break;
  32418. case BABYLON.VertexBuffer.NormalKind:
  32419. this.normals = data;
  32420. break;
  32421. case BABYLON.VertexBuffer.UVKind:
  32422. this.uvs = data;
  32423. break;
  32424. case BABYLON.VertexBuffer.UV2Kind:
  32425. this.uvs2 = data;
  32426. break;
  32427. case BABYLON.VertexBuffer.UV3Kind:
  32428. this.uvs3 = data;
  32429. break;
  32430. case BABYLON.VertexBuffer.UV4Kind:
  32431. this.uvs4 = data;
  32432. break;
  32433. case BABYLON.VertexBuffer.UV5Kind:
  32434. this.uvs5 = data;
  32435. break;
  32436. case BABYLON.VertexBuffer.UV6Kind:
  32437. this.uvs6 = data;
  32438. break;
  32439. case BABYLON.VertexBuffer.ColorKind:
  32440. this.colors = data;
  32441. break;
  32442. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32443. this.matricesIndices = data;
  32444. break;
  32445. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32446. this.matricesWeights = data;
  32447. break;
  32448. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32449. this.matricesIndicesExtra = data;
  32450. break;
  32451. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32452. this.matricesWeightsExtra = data;
  32453. break;
  32454. }
  32455. };
  32456. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32457. this._applyTo(mesh, updatable);
  32458. };
  32459. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32460. this._applyTo(geometry, updatable);
  32461. };
  32462. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32463. this._update(mesh);
  32464. };
  32465. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32466. this._update(geometry);
  32467. };
  32468. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32469. if (this.positions) {
  32470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32471. }
  32472. if (this.normals) {
  32473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32474. }
  32475. if (this.uvs) {
  32476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32477. }
  32478. if (this.uvs2) {
  32479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32480. }
  32481. if (this.uvs3) {
  32482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32483. }
  32484. if (this.uvs4) {
  32485. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32486. }
  32487. if (this.uvs5) {
  32488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32489. }
  32490. if (this.uvs6) {
  32491. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32492. }
  32493. if (this.colors) {
  32494. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32495. }
  32496. if (this.matricesIndices) {
  32497. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32498. }
  32499. if (this.matricesWeights) {
  32500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32501. }
  32502. if (this.matricesIndicesExtra) {
  32503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32504. }
  32505. if (this.matricesWeightsExtra) {
  32506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32507. }
  32508. if (this.indices) {
  32509. meshOrGeometry.setIndices(this.indices);
  32510. }
  32511. };
  32512. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32513. if (this.positions) {
  32514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32515. }
  32516. if (this.normals) {
  32517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32518. }
  32519. if (this.uvs) {
  32520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32521. }
  32522. if (this.uvs2) {
  32523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32524. }
  32525. if (this.uvs3) {
  32526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32527. }
  32528. if (this.uvs4) {
  32529. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32530. }
  32531. if (this.uvs5) {
  32532. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32533. }
  32534. if (this.uvs6) {
  32535. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32536. }
  32537. if (this.colors) {
  32538. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32539. }
  32540. if (this.matricesIndices) {
  32541. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32542. }
  32543. if (this.matricesWeights) {
  32544. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32545. }
  32546. if (this.matricesIndicesExtra) {
  32547. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32548. }
  32549. if (this.matricesWeightsExtra) {
  32550. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32551. }
  32552. if (this.indices) {
  32553. meshOrGeometry.setIndices(this.indices);
  32554. }
  32555. };
  32556. VertexData.prototype.transform = function (matrix) {
  32557. var transformed = BABYLON.Vector3.Zero();
  32558. var index;
  32559. if (this.positions) {
  32560. var position = BABYLON.Vector3.Zero();
  32561. for (index = 0; index < this.positions.length; index += 3) {
  32562. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32563. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32564. this.positions[index] = transformed.x;
  32565. this.positions[index + 1] = transformed.y;
  32566. this.positions[index + 2] = transformed.z;
  32567. }
  32568. }
  32569. if (this.normals) {
  32570. var normal = BABYLON.Vector3.Zero();
  32571. for (index = 0; index < this.normals.length; index += 3) {
  32572. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32573. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32574. this.normals[index] = transformed.x;
  32575. this.normals[index + 1] = transformed.y;
  32576. this.normals[index + 2] = transformed.z;
  32577. }
  32578. }
  32579. };
  32580. VertexData.prototype.merge = function (other) {
  32581. if (other.indices) {
  32582. if (!this.indices) {
  32583. this.indices = [];
  32584. }
  32585. var offset = this.positions ? this.positions.length / 3 : 0;
  32586. for (var index = 0; index < other.indices.length; index++) {
  32587. //TODO check type - if Int32Array!
  32588. this.indices.push(other.indices[index] + offset);
  32589. }
  32590. }
  32591. this.positions = this._mergeElement(this.positions, other.positions);
  32592. this.normals = this._mergeElement(this.normals, other.normals);
  32593. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32594. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32595. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32596. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32597. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32598. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32599. this.colors = this._mergeElement(this.colors, other.colors);
  32600. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32601. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32602. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32603. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32604. };
  32605. VertexData.prototype._mergeElement = function (source, other) {
  32606. if (!other)
  32607. return source;
  32608. if (!source)
  32609. return other;
  32610. var len = other.length + source.length;
  32611. var isSrcTypedArray = source instanceof Float32Array;
  32612. var isOthTypedArray = other instanceof Float32Array;
  32613. // use non-loop method when the source is Float32Array
  32614. if (isSrcTypedArray) {
  32615. var ret32 = new Float32Array(len);
  32616. ret32.set(source);
  32617. ret32.set(other, source.length);
  32618. return ret32;
  32619. }
  32620. else if (!isOthTypedArray) {
  32621. return source.concat(other);
  32622. }
  32623. else {
  32624. var ret = source.slice(0); // copy source to a separate array
  32625. for (var i = 0, len = other.length; i < len; i++) {
  32626. ret.push(other[i]);
  32627. }
  32628. return ret;
  32629. }
  32630. };
  32631. VertexData.prototype.serialize = function () {
  32632. var serializationObject = this.serialize();
  32633. if (this.positions) {
  32634. serializationObject.positions = this.positions;
  32635. }
  32636. if (this.normals) {
  32637. serializationObject.normals = this.normals;
  32638. }
  32639. if (this.uvs) {
  32640. serializationObject.uvs = this.uvs;
  32641. }
  32642. if (this.uvs2) {
  32643. serializationObject.uvs2 = this.uvs2;
  32644. }
  32645. if (this.uvs3) {
  32646. serializationObject.uvs3 = this.uvs3;
  32647. }
  32648. if (this.uvs4) {
  32649. serializationObject.uvs4 = this.uvs4;
  32650. }
  32651. if (this.uvs5) {
  32652. serializationObject.uvs5 = this.uvs5;
  32653. }
  32654. if (this.uvs6) {
  32655. serializationObject.uvs6 = this.uvs6;
  32656. }
  32657. if (this.colors) {
  32658. serializationObject.colors = this.colors;
  32659. }
  32660. if (this.matricesIndices) {
  32661. serializationObject.matricesIndices = this.matricesIndices;
  32662. serializationObject.matricesIndices._isExpanded = true;
  32663. }
  32664. if (this.matricesWeights) {
  32665. serializationObject.matricesWeights = this.matricesWeights;
  32666. }
  32667. if (this.matricesIndicesExtra) {
  32668. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32669. serializationObject.matricesIndicesExtra._isExpanded = true;
  32670. }
  32671. if (this.matricesWeightsExtra) {
  32672. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32673. }
  32674. serializationObject.indices = this.indices;
  32675. return serializationObject;
  32676. };
  32677. // Statics
  32678. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32679. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32680. };
  32681. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32682. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32683. };
  32684. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32685. var result = new VertexData();
  32686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32687. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32688. }
  32689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32690. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32691. }
  32692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32693. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32694. }
  32695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32696. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32697. }
  32698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32699. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32700. }
  32701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32702. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32703. }
  32704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32705. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32706. }
  32707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32708. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32709. }
  32710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32711. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32712. }
  32713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32714. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32715. }
  32716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32717. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32718. }
  32719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32720. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32721. }
  32722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32723. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32724. }
  32725. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32726. return result;
  32727. };
  32728. VertexData.CreateRibbon = function (options) {
  32729. var pathArray = options.pathArray;
  32730. var closeArray = options.closeArray || false;
  32731. var closePath = options.closePath || false;
  32732. var invertUV = options.invertUV || false;
  32733. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32734. var offset = options.offset || defaultOffset;
  32735. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32736. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32737. var positions = [];
  32738. var indices = [];
  32739. var normals = [];
  32740. var uvs = [];
  32741. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32742. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32743. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32744. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32745. var minlg; // minimal length among all paths from pathArray
  32746. var lg = []; // array of path lengths : nb of vertex per path
  32747. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32748. var p; // path iterator
  32749. var i; // point iterator
  32750. var j; // point iterator
  32751. // if single path in pathArray
  32752. if (pathArray.length < 2) {
  32753. var ar1 = [];
  32754. var ar2 = [];
  32755. for (i = 0; i < pathArray[0].length - offset; i++) {
  32756. ar1.push(pathArray[0][i]);
  32757. ar2.push(pathArray[0][i + offset]);
  32758. }
  32759. pathArray = [ar1, ar2];
  32760. }
  32761. // positions and horizontal distances (u)
  32762. var idc = 0;
  32763. var closePathCorr = (closePath) ? 1 : 0;
  32764. var path;
  32765. var l;
  32766. minlg = pathArray[0].length;
  32767. var vectlg;
  32768. var dist;
  32769. for (p = 0; p < pathArray.length; p++) {
  32770. uTotalDistance[p] = 0;
  32771. us[p] = [0];
  32772. path = pathArray[p];
  32773. l = path.length;
  32774. minlg = (minlg < l) ? minlg : l;
  32775. j = 0;
  32776. while (j < l) {
  32777. positions.push(path[j].x, path[j].y, path[j].z);
  32778. if (j > 0) {
  32779. vectlg = path[j].subtract(path[j - 1]).length();
  32780. dist = vectlg + uTotalDistance[p];
  32781. us[p].push(dist);
  32782. uTotalDistance[p] = dist;
  32783. }
  32784. j++;
  32785. }
  32786. if (closePath) {
  32787. j--;
  32788. positions.push(path[0].x, path[0].y, path[0].z);
  32789. vectlg = path[j].subtract(path[0]).length();
  32790. dist = vectlg + uTotalDistance[p];
  32791. us[p].push(dist);
  32792. uTotalDistance[p] = dist;
  32793. }
  32794. lg[p] = l + closePathCorr;
  32795. idx[p] = idc;
  32796. idc += (l + closePathCorr);
  32797. }
  32798. // vertical distances (v)
  32799. var path1;
  32800. var path2;
  32801. var vertex1;
  32802. var vertex2;
  32803. for (i = 0; i < minlg + closePathCorr; i++) {
  32804. vTotalDistance[i] = 0;
  32805. vs[i] = [0];
  32806. for (p = 0; p < pathArray.length - 1; p++) {
  32807. path1 = pathArray[p];
  32808. path2 = pathArray[p + 1];
  32809. if (i === minlg) {
  32810. vertex1 = path1[0];
  32811. vertex2 = path2[0];
  32812. }
  32813. else {
  32814. vertex1 = path1[i];
  32815. vertex2 = path2[i];
  32816. }
  32817. vectlg = vertex2.subtract(vertex1).length();
  32818. dist = vectlg + vTotalDistance[i];
  32819. vs[i].push(dist);
  32820. vTotalDistance[i] = dist;
  32821. }
  32822. if (closeArray) {
  32823. path1 = pathArray[p];
  32824. path2 = pathArray[0];
  32825. if (i === minlg) {
  32826. vertex2 = path2[0];
  32827. }
  32828. vectlg = vertex2.subtract(vertex1).length();
  32829. dist = vectlg + vTotalDistance[i];
  32830. vTotalDistance[i] = dist;
  32831. }
  32832. }
  32833. // uvs
  32834. var u;
  32835. var v;
  32836. for (p = 0; p < pathArray.length; p++) {
  32837. for (i = 0; i < minlg + closePathCorr; i++) {
  32838. u = us[p][i] / uTotalDistance[p];
  32839. v = vs[i][p] / vTotalDistance[i];
  32840. if (invertUV) {
  32841. uvs.push(v, u);
  32842. }
  32843. else {
  32844. uvs.push(u, v);
  32845. }
  32846. }
  32847. }
  32848. // indices
  32849. p = 0; // path index
  32850. var pi = 0; // positions array index
  32851. var l1 = lg[p] - 1; // path1 length
  32852. var l2 = lg[p + 1] - 1; // path2 length
  32853. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32854. var shft = idx[1] - idx[0]; // shift
  32855. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32856. while (pi <= min && p < path1nb) {
  32857. // 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
  32858. indices.push(pi, pi + shft, pi + 1);
  32859. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32860. pi += 1;
  32861. if (pi === min) {
  32862. p++;
  32863. if (p === lg.length - 1) {
  32864. shft = idx[0] - idx[p];
  32865. l1 = lg[p] - 1;
  32866. l2 = lg[0] - 1;
  32867. }
  32868. else {
  32869. shft = idx[p + 1] - idx[p];
  32870. l1 = lg[p] - 1;
  32871. l2 = lg[p + 1] - 1;
  32872. }
  32873. pi = idx[p];
  32874. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32875. }
  32876. }
  32877. // normals
  32878. VertexData.ComputeNormals(positions, indices, normals);
  32879. if (closePath) {
  32880. var indexFirst = 0;
  32881. var indexLast = 0;
  32882. for (p = 0; p < pathArray.length; p++) {
  32883. indexFirst = idx[p] * 3;
  32884. if (p + 1 < pathArray.length) {
  32885. indexLast = (idx[p + 1] - 1) * 3;
  32886. }
  32887. else {
  32888. indexLast = normals.length - 3;
  32889. }
  32890. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32891. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32892. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32893. normals[indexLast] = normals[indexFirst];
  32894. normals[indexLast + 1] = normals[indexFirst + 1];
  32895. normals[indexLast + 2] = normals[indexFirst + 2];
  32896. }
  32897. }
  32898. // sides
  32899. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32900. // Result
  32901. var vertexData = new VertexData();
  32902. vertexData.indices = indices;
  32903. vertexData.positions = positions;
  32904. vertexData.normals = normals;
  32905. vertexData.uvs = uvs;
  32906. if (closePath) {
  32907. vertexData._idx = idx;
  32908. }
  32909. return vertexData;
  32910. };
  32911. VertexData.CreateBox = function (options) {
  32912. var normalsSource = [
  32913. new BABYLON.Vector3(0, 0, 1),
  32914. new BABYLON.Vector3(0, 0, -1),
  32915. new BABYLON.Vector3(1, 0, 0),
  32916. new BABYLON.Vector3(-1, 0, 0),
  32917. new BABYLON.Vector3(0, 1, 0),
  32918. new BABYLON.Vector3(0, -1, 0)
  32919. ];
  32920. var indices = [];
  32921. var positions = [];
  32922. var normals = [];
  32923. var uvs = [];
  32924. var width = options.width || options.size || 1;
  32925. var height = options.height || options.size || 1;
  32926. var depth = options.depth || options.size || 1;
  32927. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32928. var faceUV = options.faceUV || new Array(6);
  32929. var faceColors = options.faceColors;
  32930. var colors = [];
  32931. // default face colors and UV if undefined
  32932. for (var f = 0; f < 6; f++) {
  32933. if (faceUV[f] === undefined) {
  32934. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32935. }
  32936. if (faceColors && faceColors[f] === undefined) {
  32937. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32938. }
  32939. }
  32940. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32941. // Create each face in turn.
  32942. for (var index = 0; index < normalsSource.length; index++) {
  32943. var normal = normalsSource[index];
  32944. // Get two vectors perpendicular to the face normal and to each other.
  32945. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32946. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32947. // Six indices (two triangles) per face.
  32948. var verticesLength = positions.length / 3;
  32949. indices.push(verticesLength);
  32950. indices.push(verticesLength + 1);
  32951. indices.push(verticesLength + 2);
  32952. indices.push(verticesLength);
  32953. indices.push(verticesLength + 2);
  32954. indices.push(verticesLength + 3);
  32955. // Four vertices per face.
  32956. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32957. positions.push(vertex.x, vertex.y, vertex.z);
  32958. normals.push(normal.x, normal.y, normal.z);
  32959. uvs.push(faceUV[index].z, faceUV[index].w);
  32960. if (faceColors) {
  32961. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32962. }
  32963. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32964. positions.push(vertex.x, vertex.y, vertex.z);
  32965. normals.push(normal.x, normal.y, normal.z);
  32966. uvs.push(faceUV[index].x, faceUV[index].w);
  32967. if (faceColors) {
  32968. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32969. }
  32970. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32971. positions.push(vertex.x, vertex.y, vertex.z);
  32972. normals.push(normal.x, normal.y, normal.z);
  32973. uvs.push(faceUV[index].x, faceUV[index].y);
  32974. if (faceColors) {
  32975. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32976. }
  32977. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32978. positions.push(vertex.x, vertex.y, vertex.z);
  32979. normals.push(normal.x, normal.y, normal.z);
  32980. uvs.push(faceUV[index].z, faceUV[index].y);
  32981. if (faceColors) {
  32982. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32983. }
  32984. }
  32985. // sides
  32986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32987. // Result
  32988. var vertexData = new VertexData();
  32989. vertexData.indices = indices;
  32990. vertexData.positions = positions;
  32991. vertexData.normals = normals;
  32992. vertexData.uvs = uvs;
  32993. if (faceColors) {
  32994. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32995. vertexData.colors = totalColors;
  32996. }
  32997. return vertexData;
  32998. };
  32999. VertexData.CreateSphere = function (options) {
  33000. var segments = options.segments || 32;
  33001. var diameterX = options.diameterX || options.diameter || 1;
  33002. var diameterY = options.diameterY || options.diameter || 1;
  33003. var diameterZ = options.diameterZ || options.diameter || 1;
  33004. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33005. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33007. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33008. var totalZRotationSteps = 2 + segments;
  33009. var totalYRotationSteps = 2 * totalZRotationSteps;
  33010. var indices = [];
  33011. var positions = [];
  33012. var normals = [];
  33013. var uvs = [];
  33014. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33015. var normalizedZ = zRotationStep / totalZRotationSteps;
  33016. var angleZ = normalizedZ * Math.PI * slice;
  33017. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33018. var normalizedY = yRotationStep / totalYRotationSteps;
  33019. var angleY = normalizedY * Math.PI * 2 * arc;
  33020. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33021. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33022. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33023. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33024. var vertex = complete.multiply(radius);
  33025. var normal = complete.divide(radius).normalize();
  33026. positions.push(vertex.x, vertex.y, vertex.z);
  33027. normals.push(normal.x, normal.y, normal.z);
  33028. uvs.push(normalizedY, normalizedZ);
  33029. }
  33030. if (zRotationStep > 0) {
  33031. var verticesCount = positions.length / 3;
  33032. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33033. indices.push((firstIndex));
  33034. indices.push((firstIndex + 1));
  33035. indices.push(firstIndex + totalYRotationSteps + 1);
  33036. indices.push((firstIndex + totalYRotationSteps + 1));
  33037. indices.push((firstIndex + 1));
  33038. indices.push((firstIndex + totalYRotationSteps + 2));
  33039. }
  33040. }
  33041. }
  33042. // Sides
  33043. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33044. // Result
  33045. var vertexData = new VertexData();
  33046. vertexData.indices = indices;
  33047. vertexData.positions = positions;
  33048. vertexData.normals = normals;
  33049. vertexData.uvs = uvs;
  33050. return vertexData;
  33051. };
  33052. // Cylinder and cone
  33053. VertexData.CreateCylinder = function (options) {
  33054. var height = options.height || 2;
  33055. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33056. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33057. var tessellation = options.tessellation || 24;
  33058. var subdivisions = options.subdivisions || 1;
  33059. var hasRings = options.hasRings;
  33060. var enclose = options.enclose;
  33061. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33062. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33063. var faceUV = options.faceUV || new Array(3);
  33064. var faceColors = options.faceColors;
  33065. // default face colors and UV if undefined
  33066. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33067. var ringNb = (hasRings) ? subdivisions : 1;
  33068. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33069. var f;
  33070. for (f = 0; f < surfaceNb; f++) {
  33071. if (faceColors && faceColors[f] === undefined) {
  33072. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33073. }
  33074. }
  33075. for (f = 0; f < surfaceNb; f++) {
  33076. if (faceUV && faceUV[f] === undefined) {
  33077. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33078. }
  33079. }
  33080. var indices = [];
  33081. var positions = [];
  33082. var normals = [];
  33083. var uvs = [];
  33084. var colors = [];
  33085. var angle_step = Math.PI * 2 * arc / tessellation;
  33086. var angle;
  33087. var h;
  33088. var radius;
  33089. var tan = (diameterBottom - diameterTop) / 2 / height;
  33090. var ringVertex = BABYLON.Vector3.Zero();
  33091. var ringNormal = BABYLON.Vector3.Zero();
  33092. var ringFirstVertex = BABYLON.Vector3.Zero();
  33093. var ringFirstNormal = BABYLON.Vector3.Zero();
  33094. var quadNormal = BABYLON.Vector3.Zero();
  33095. var Y = BABYLON.Axis.Y;
  33096. // positions, normals, uvs
  33097. var i;
  33098. var j;
  33099. var r;
  33100. var ringIdx = 1;
  33101. var s = 1; // surface index
  33102. var cs = 0;
  33103. var v = 0;
  33104. for (i = 0; i <= subdivisions; i++) {
  33105. h = i / subdivisions;
  33106. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33107. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33108. for (r = 0; r < ringIdx; r++) {
  33109. if (hasRings) {
  33110. s += r;
  33111. }
  33112. if (enclose) {
  33113. s += 2 * r;
  33114. }
  33115. for (j = 0; j <= tessellation; j++) {
  33116. angle = j * angle_step;
  33117. // position
  33118. ringVertex.x = Math.cos(-angle) * radius;
  33119. ringVertex.y = -height / 2 + h * height;
  33120. ringVertex.z = Math.sin(-angle) * radius;
  33121. // normal
  33122. if (diameterTop === 0 && i === subdivisions) {
  33123. // if no top cap, reuse former normals
  33124. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33125. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33126. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33127. }
  33128. else {
  33129. ringNormal.x = ringVertex.x;
  33130. ringNormal.z = ringVertex.z;
  33131. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33132. ringNormal.normalize();
  33133. }
  33134. // keep first ring vertex values for enclose
  33135. if (j === 0) {
  33136. ringFirstVertex.copyFrom(ringVertex);
  33137. ringFirstNormal.copyFrom(ringNormal);
  33138. }
  33139. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33140. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33141. if (hasRings) {
  33142. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33143. }
  33144. else {
  33145. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33146. }
  33147. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33148. if (faceColors) {
  33149. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33150. }
  33151. }
  33152. // if enclose, add four vertices and their dedicated normals
  33153. if (arc !== 1 && enclose) {
  33154. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33155. positions.push(0, ringVertex.y, 0);
  33156. positions.push(0, ringVertex.y, 0);
  33157. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33158. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33159. quadNormal.normalize();
  33160. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33161. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33162. quadNormal.normalize();
  33163. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33164. if (hasRings) {
  33165. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33166. }
  33167. else {
  33168. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33169. }
  33170. uvs.push(faceUV[s + 1].x, v);
  33171. uvs.push(faceUV[s + 1].z, v);
  33172. if (hasRings) {
  33173. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33174. }
  33175. else {
  33176. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33177. }
  33178. uvs.push(faceUV[s + 2].x, v);
  33179. uvs.push(faceUV[s + 2].z, v);
  33180. if (faceColors) {
  33181. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33182. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33183. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33184. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33185. }
  33186. }
  33187. if (cs !== s) {
  33188. cs = s;
  33189. }
  33190. }
  33191. }
  33192. // indices
  33193. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33194. var s;
  33195. i = 0;
  33196. for (s = 0; s < subdivisions; s++) {
  33197. for (j = 0; j < tessellation; j++) {
  33198. var i0 = i * (e + 1) + j;
  33199. var i1 = (i + 1) * (e + 1) + j;
  33200. var i2 = i * (e + 1) + (j + 1);
  33201. var i3 = (i + 1) * (e + 1) + (j + 1);
  33202. indices.push(i0, i1, i2);
  33203. indices.push(i3, i2, i1);
  33204. }
  33205. if (arc !== 1 && enclose) {
  33206. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33207. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33208. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33209. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33210. }
  33211. i = (hasRings) ? (i + 2) : (i + 1);
  33212. }
  33213. // Caps
  33214. var createCylinderCap = function (isTop) {
  33215. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33216. if (radius === 0) {
  33217. return;
  33218. }
  33219. // Cap positions, normals & uvs
  33220. var angle;
  33221. var circleVector;
  33222. var i;
  33223. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33224. var c;
  33225. if (faceColors) {
  33226. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33227. }
  33228. // cap center
  33229. var vbase = positions.length / 3;
  33230. var offset = isTop ? height / 2 : -height / 2;
  33231. var center = new BABYLON.Vector3(0, offset, 0);
  33232. positions.push(center.x, center.y, center.z);
  33233. normals.push(0, isTop ? 1 : -1, 0);
  33234. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33235. if (faceColors) {
  33236. colors.push(c.r, c.g, c.b, c.a);
  33237. }
  33238. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33239. for (i = 0; i <= tessellation; i++) {
  33240. angle = Math.PI * 2 * i * arc / tessellation;
  33241. var cos = Math.cos(-angle);
  33242. var sin = Math.sin(-angle);
  33243. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33244. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33245. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33246. normals.push(0, isTop ? 1 : -1, 0);
  33247. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33248. if (faceColors) {
  33249. colors.push(c.r, c.g, c.b, c.a);
  33250. }
  33251. }
  33252. // Cap indices
  33253. for (i = 0; i < tessellation; i++) {
  33254. if (!isTop) {
  33255. indices.push(vbase);
  33256. indices.push(vbase + (i + 1));
  33257. indices.push(vbase + (i + 2));
  33258. }
  33259. else {
  33260. indices.push(vbase);
  33261. indices.push(vbase + (i + 2));
  33262. indices.push(vbase + (i + 1));
  33263. }
  33264. }
  33265. };
  33266. // add caps to geometry
  33267. createCylinderCap(false);
  33268. createCylinderCap(true);
  33269. // Sides
  33270. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33271. var vertexData = new VertexData();
  33272. vertexData.indices = indices;
  33273. vertexData.positions = positions;
  33274. vertexData.normals = normals;
  33275. vertexData.uvs = uvs;
  33276. if (faceColors) {
  33277. vertexData.colors = colors;
  33278. }
  33279. return vertexData;
  33280. };
  33281. VertexData.CreateTorus = function (options) {
  33282. var indices = [];
  33283. var positions = [];
  33284. var normals = [];
  33285. var uvs = [];
  33286. var diameter = options.diameter || 1;
  33287. var thickness = options.thickness || 0.5;
  33288. var tessellation = options.tessellation || 16;
  33289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33290. var stride = tessellation + 1;
  33291. for (var i = 0; i <= tessellation; i++) {
  33292. var u = i / tessellation;
  33293. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33294. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33295. for (var j = 0; j <= tessellation; j++) {
  33296. var v = 1 - j / tessellation;
  33297. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33298. var dx = Math.cos(innerAngle);
  33299. var dy = Math.sin(innerAngle);
  33300. // Create a vertex.
  33301. var normal = new BABYLON.Vector3(dx, dy, 0);
  33302. var position = normal.scale(thickness / 2);
  33303. var textureCoordinate = new BABYLON.Vector2(u, v);
  33304. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33305. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33306. positions.push(position.x, position.y, position.z);
  33307. normals.push(normal.x, normal.y, normal.z);
  33308. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33309. // And create indices for two triangles.
  33310. var nextI = (i + 1) % stride;
  33311. var nextJ = (j + 1) % stride;
  33312. indices.push(i * stride + j);
  33313. indices.push(i * stride + nextJ);
  33314. indices.push(nextI * stride + j);
  33315. indices.push(i * stride + nextJ);
  33316. indices.push(nextI * stride + nextJ);
  33317. indices.push(nextI * stride + j);
  33318. }
  33319. }
  33320. // Sides
  33321. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33322. // Result
  33323. var vertexData = new VertexData();
  33324. vertexData.indices = indices;
  33325. vertexData.positions = positions;
  33326. vertexData.normals = normals;
  33327. vertexData.uvs = uvs;
  33328. return vertexData;
  33329. };
  33330. VertexData.CreateLineSystem = function (options) {
  33331. var indices = [];
  33332. var positions = [];
  33333. var lines = options.lines;
  33334. var idx = 0;
  33335. for (var l = 0; l < lines.length; l++) {
  33336. var points = lines[l];
  33337. for (var index = 0; index < points.length; index++) {
  33338. positions.push(points[index].x, points[index].y, points[index].z);
  33339. if (index > 0) {
  33340. indices.push(idx - 1);
  33341. indices.push(idx);
  33342. }
  33343. idx++;
  33344. }
  33345. }
  33346. var vertexData = new VertexData();
  33347. vertexData.indices = indices;
  33348. vertexData.positions = positions;
  33349. return vertexData;
  33350. };
  33351. VertexData.CreateDashedLines = function (options) {
  33352. var dashSize = options.dashSize || 3;
  33353. var gapSize = options.gapSize || 1;
  33354. var dashNb = options.dashNb || 200;
  33355. var points = options.points;
  33356. var positions = new Array();
  33357. var indices = new Array();
  33358. var curvect = BABYLON.Vector3.Zero();
  33359. var lg = 0;
  33360. var nb = 0;
  33361. var shft = 0;
  33362. var dashshft = 0;
  33363. var curshft = 0;
  33364. var idx = 0;
  33365. var i = 0;
  33366. for (i = 0; i < points.length - 1; i++) {
  33367. points[i + 1].subtractToRef(points[i], curvect);
  33368. lg += curvect.length();
  33369. }
  33370. shft = lg / dashNb;
  33371. dashshft = dashSize * shft / (dashSize + gapSize);
  33372. for (i = 0; i < points.length - 1; i++) {
  33373. points[i + 1].subtractToRef(points[i], curvect);
  33374. nb = Math.floor(curvect.length() / shft);
  33375. curvect.normalize();
  33376. for (var j = 0; j < nb; j++) {
  33377. curshft = shft * j;
  33378. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33379. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33380. indices.push(idx, idx + 1);
  33381. idx += 2;
  33382. }
  33383. }
  33384. // Result
  33385. var vertexData = new VertexData();
  33386. vertexData.positions = positions;
  33387. vertexData.indices = indices;
  33388. return vertexData;
  33389. };
  33390. VertexData.CreateGround = function (options) {
  33391. var indices = [];
  33392. var positions = [];
  33393. var normals = [];
  33394. var uvs = [];
  33395. var row, col;
  33396. var width = options.width || 1;
  33397. var height = options.height || 1;
  33398. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33399. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33400. for (row = 0; row <= subdivisionsY; row++) {
  33401. for (col = 0; col <= subdivisionsX; col++) {
  33402. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33403. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33404. positions.push(position.x, position.y, position.z);
  33405. normals.push(normal.x, normal.y, normal.z);
  33406. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33407. }
  33408. }
  33409. for (row = 0; row < subdivisionsY; row++) {
  33410. for (col = 0; col < subdivisionsX; col++) {
  33411. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33412. indices.push(col + 1 + row * (subdivisionsX + 1));
  33413. indices.push(col + row * (subdivisionsX + 1));
  33414. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33415. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33416. indices.push(col + row * (subdivisionsX + 1));
  33417. }
  33418. }
  33419. // Result
  33420. var vertexData = new VertexData();
  33421. vertexData.indices = indices;
  33422. vertexData.positions = positions;
  33423. vertexData.normals = normals;
  33424. vertexData.uvs = uvs;
  33425. return vertexData;
  33426. };
  33427. VertexData.CreateTiledGround = function (options) {
  33428. var xmin = options.xmin || -1.0;
  33429. var zmin = options.zmin || -1.0;
  33430. var xmax = options.xmax || 1.0;
  33431. var zmax = options.zmax || 1.0;
  33432. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33433. var precision = options.precision || { w: 1, h: 1 };
  33434. var indices = [];
  33435. var positions = [];
  33436. var normals = [];
  33437. var uvs = [];
  33438. var row, col, tileRow, tileCol;
  33439. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33440. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33441. precision.w = (precision.w < 1) ? 1 : precision.w;
  33442. precision.h = (precision.h < 1) ? 1 : precision.h;
  33443. var tileSize = {
  33444. 'w': (xmax - xmin) / subdivisions.w,
  33445. 'h': (zmax - zmin) / subdivisions.h
  33446. };
  33447. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33448. // Indices
  33449. var base = positions.length / 3;
  33450. var rowLength = precision.w + 1;
  33451. for (row = 0; row < precision.h; row++) {
  33452. for (col = 0; col < precision.w; col++) {
  33453. var square = [
  33454. base + col + row * rowLength,
  33455. base + (col + 1) + row * rowLength,
  33456. base + (col + 1) + (row + 1) * rowLength,
  33457. base + col + (row + 1) * rowLength
  33458. ];
  33459. indices.push(square[1]);
  33460. indices.push(square[2]);
  33461. indices.push(square[3]);
  33462. indices.push(square[0]);
  33463. indices.push(square[1]);
  33464. indices.push(square[3]);
  33465. }
  33466. }
  33467. // Position, normals and uvs
  33468. var position = BABYLON.Vector3.Zero();
  33469. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33470. for (row = 0; row <= precision.h; row++) {
  33471. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33472. for (col = 0; col <= precision.w; col++) {
  33473. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33474. position.y = 0;
  33475. positions.push(position.x, position.y, position.z);
  33476. normals.push(normal.x, normal.y, normal.z);
  33477. uvs.push(col / precision.w, row / precision.h);
  33478. }
  33479. }
  33480. }
  33481. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33482. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33483. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33484. }
  33485. }
  33486. // Result
  33487. var vertexData = new VertexData();
  33488. vertexData.indices = indices;
  33489. vertexData.positions = positions;
  33490. vertexData.normals = normals;
  33491. vertexData.uvs = uvs;
  33492. return vertexData;
  33493. };
  33494. VertexData.CreateGroundFromHeightMap = function (options) {
  33495. var indices = [];
  33496. var positions = [];
  33497. var normals = [];
  33498. var uvs = [];
  33499. var row, col;
  33500. // Vertices
  33501. for (row = 0; row <= options.subdivisions; row++) {
  33502. for (col = 0; col <= options.subdivisions; col++) {
  33503. 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));
  33504. // Compute height
  33505. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33506. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33507. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33508. var r = options.buffer[pos] / 255.0;
  33509. var g = options.buffer[pos + 1] / 255.0;
  33510. var b = options.buffer[pos + 2] / 255.0;
  33511. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33512. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33513. // Add vertex
  33514. positions.push(position.x, position.y, position.z);
  33515. normals.push(0, 0, 0);
  33516. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33517. }
  33518. }
  33519. // Indices
  33520. for (row = 0; row < options.subdivisions; row++) {
  33521. for (col = 0; col < options.subdivisions; col++) {
  33522. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33523. indices.push(col + 1 + row * (options.subdivisions + 1));
  33524. indices.push(col + row * (options.subdivisions + 1));
  33525. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33526. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33527. indices.push(col + row * (options.subdivisions + 1));
  33528. }
  33529. }
  33530. // Normals
  33531. VertexData.ComputeNormals(positions, indices, normals);
  33532. // Result
  33533. var vertexData = new VertexData();
  33534. vertexData.indices = indices;
  33535. vertexData.positions = positions;
  33536. vertexData.normals = normals;
  33537. vertexData.uvs = uvs;
  33538. return vertexData;
  33539. };
  33540. VertexData.CreatePlane = function (options) {
  33541. var indices = [];
  33542. var positions = [];
  33543. var normals = [];
  33544. var uvs = [];
  33545. var width = options.width || options.size || 1;
  33546. var height = options.height || options.size || 1;
  33547. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33548. // Vertices
  33549. var halfWidth = width / 2.0;
  33550. var halfHeight = height / 2.0;
  33551. positions.push(-halfWidth, -halfHeight, 0);
  33552. normals.push(0, 0, -1.0);
  33553. uvs.push(0.0, 0.0);
  33554. positions.push(halfWidth, -halfHeight, 0);
  33555. normals.push(0, 0, -1.0);
  33556. uvs.push(1.0, 0.0);
  33557. positions.push(halfWidth, halfHeight, 0);
  33558. normals.push(0, 0, -1.0);
  33559. uvs.push(1.0, 1.0);
  33560. positions.push(-halfWidth, halfHeight, 0);
  33561. normals.push(0, 0, -1.0);
  33562. uvs.push(0.0, 1.0);
  33563. // Indices
  33564. indices.push(0);
  33565. indices.push(1);
  33566. indices.push(2);
  33567. indices.push(0);
  33568. indices.push(2);
  33569. indices.push(3);
  33570. // Sides
  33571. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33572. // Result
  33573. var vertexData = new VertexData();
  33574. vertexData.indices = indices;
  33575. vertexData.positions = positions;
  33576. vertexData.normals = normals;
  33577. vertexData.uvs = uvs;
  33578. return vertexData;
  33579. };
  33580. VertexData.CreateDisc = function (options) {
  33581. var positions = [];
  33582. var indices = [];
  33583. var normals = [];
  33584. var uvs = [];
  33585. var radius = options.radius || 0.5;
  33586. var tessellation = options.tessellation || 64;
  33587. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33589. // positions and uvs
  33590. positions.push(0, 0, 0); // disc center first
  33591. uvs.push(0.5, 0.5);
  33592. var theta = Math.PI * 2 * arc;
  33593. var step = theta / tessellation;
  33594. for (var a = 0; a < theta; a += step) {
  33595. var x = Math.cos(a);
  33596. var y = Math.sin(a);
  33597. var u = (x + 1) / 2;
  33598. var v = (1 - y) / 2;
  33599. positions.push(radius * x, radius * y, 0);
  33600. uvs.push(u, v);
  33601. }
  33602. if (arc === 1) {
  33603. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33604. uvs.push(uvs[2], uvs[3]);
  33605. }
  33606. //indices
  33607. var vertexNb = positions.length / 3;
  33608. for (var i = 1; i < vertexNb - 1; i++) {
  33609. indices.push(i + 1, 0, i);
  33610. }
  33611. // result
  33612. VertexData.ComputeNormals(positions, indices, normals);
  33613. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33614. var vertexData = new VertexData();
  33615. vertexData.indices = indices;
  33616. vertexData.positions = positions;
  33617. vertexData.normals = normals;
  33618. vertexData.uvs = uvs;
  33619. return vertexData;
  33620. };
  33621. VertexData.CreateIcoSphere = function (options) {
  33622. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33623. var radius = options.radius || 1;
  33624. var flat = (options.flat === undefined) ? true : options.flat;
  33625. var subdivisions = options.subdivisions || 4;
  33626. var radiusX = options.radiusX || radius;
  33627. var radiusY = options.radiusY || radius;
  33628. var radiusZ = options.radiusZ || radius;
  33629. var t = (1 + Math.sqrt(5)) / 2;
  33630. // 12 vertex x,y,z
  33631. var ico_vertices = [
  33632. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33633. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33634. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33635. ];
  33636. // index of 3 vertex makes a face of icopshere
  33637. var ico_indices = [
  33638. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33639. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33640. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33641. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33642. ];
  33643. // vertex for uv have aliased position, not for UV
  33644. var vertices_unalias_id = [
  33645. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33646. // vertex alias
  33647. 0,
  33648. 2,
  33649. 3,
  33650. 3,
  33651. 3,
  33652. 4,
  33653. 7,
  33654. 8,
  33655. 9,
  33656. 9,
  33657. 10,
  33658. 11 // 23: B + 12
  33659. ];
  33660. // uv as integer step (not pixels !)
  33661. var ico_vertexuv = [
  33662. 5, 1, 3, 1, 6, 4, 0, 0,
  33663. 5, 3, 4, 2, 2, 2, 4, 0,
  33664. 2, 0, 1, 1, 6, 0, 6, 2,
  33665. // vertex alias (for same vertex on different faces)
  33666. 0, 4,
  33667. 3, 3,
  33668. 4, 4,
  33669. 3, 1,
  33670. 4, 2,
  33671. 4, 4,
  33672. 0, 2,
  33673. 1, 1,
  33674. 2, 2,
  33675. 3, 3,
  33676. 1, 3,
  33677. 2, 4 // 23: B + 12
  33678. ];
  33679. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33680. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33681. // First island of uv mapping
  33682. // v = 4h 3+ 2
  33683. // v = 3h 9+ 4
  33684. // v = 2h 9+ 5 B
  33685. // v = 1h 9 1 0
  33686. // v = 0h 3 8 7 A
  33687. // u = 0 1 2 3 4 5 6 *a
  33688. // Second island of uv mapping
  33689. // v = 4h 0+ B+ 4+
  33690. // v = 3h A+ 2+
  33691. // v = 2h 7+ 6 3+
  33692. // v = 1h 8+ 3+
  33693. // v = 0h
  33694. // u = 0 1 2 3 4 5 6 *a
  33695. // Face layout on texture UV mapping
  33696. // ============
  33697. // \ 4 /\ 16 / ======
  33698. // \ / \ / /\ 11 /
  33699. // \/ 7 \/ / \ /
  33700. // ======= / 10 \/
  33701. // /\ 17 /\ =======
  33702. // / \ / \ \ 15 /\
  33703. // / 8 \/ 12 \ \ / \
  33704. // ============ \/ 6 \
  33705. // \ 18 /\ ============
  33706. // \ / \ \ 5 /\ 0 /
  33707. // \/ 13 \ \ / \ /
  33708. // ======= \/ 1 \/
  33709. // =============
  33710. // /\ 19 /\ 2 /\
  33711. // / \ / \ / \
  33712. // / 14 \/ 9 \/ 3 \
  33713. // ===================
  33714. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33715. var ustep = 138 / 1024;
  33716. var vstep = 239 / 1024;
  33717. var uoffset = 60 / 1024;
  33718. var voffset = 26 / 1024;
  33719. // Second island should have margin, not to touch the first island
  33720. // avoid any borderline artefact in pixel rounding
  33721. var island_u_offset = -40 / 1024;
  33722. var island_v_offset = +20 / 1024;
  33723. // face is either island 0 or 1 :
  33724. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33725. var island = [
  33726. 0, 0, 0, 0, 1,
  33727. 0, 0, 1, 1, 0,
  33728. 0, 0, 1, 1, 0,
  33729. 0, 1, 1, 1, 0 // 15 - 19
  33730. ];
  33731. var indices = [];
  33732. var positions = [];
  33733. var normals = [];
  33734. var uvs = [];
  33735. var current_indice = 0;
  33736. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33737. var face_vertex_pos = new Array(3);
  33738. var face_vertex_uv = new Array(3);
  33739. var v012;
  33740. for (v012 = 0; v012 < 3; v012++) {
  33741. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33742. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33743. }
  33744. // create all with normals
  33745. for (var face = 0; face < 20; face++) {
  33746. // 3 vertex per face
  33747. for (v012 = 0; v012 < 3; v012++) {
  33748. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33749. var v_id = ico_indices[3 * face + v012];
  33750. // vertex have 3D position (x,y,z)
  33751. 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]);
  33752. // Normalize to get normal, then scale to radius
  33753. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33754. // uv Coordinates from vertex ID
  33755. 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);
  33756. }
  33757. // Subdivide the face (interpolate pos, norm, uv)
  33758. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33759. // - norm is linear interpolation of vertex corner normal
  33760. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33761. // - uv is linear interpolation
  33762. //
  33763. // Topology is as below for sub-divide by 2
  33764. // vertex shown as v0,v1,v2
  33765. // interp index is i1 to progress in range [v0,v1[
  33766. // interp index is i2 to progress in range [v0,v2[
  33767. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33768. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33769. //
  33770. //
  33771. // i2 v2
  33772. // ^ ^
  33773. // / / \
  33774. // / / \
  33775. // / / \
  33776. // / / (0,1) \
  33777. // / #---------\
  33778. // / / \ (0,0)'/ \
  33779. // / / \ / \
  33780. // / / \ / \
  33781. // / / (0,0) \ / (1,0) \
  33782. // / #---------#---------\
  33783. // v0 v1
  33784. //
  33785. // --------------------> i1
  33786. //
  33787. // interp of (i1,i2):
  33788. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33789. // along i1 : lerp(x0,x1, i1/(S-i2))
  33790. //
  33791. // centroid of triangle is needed to get help normal computation
  33792. // (c1,c2) are used for centroid location
  33793. var interp_vertex = function (i1, i2, c1, c2) {
  33794. // vertex is interpolated from
  33795. // - face_vertex_pos[0..2]
  33796. // - face_vertex_uv[0..2]
  33797. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33798. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33799. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33800. pos_interp.normalize();
  33801. var vertex_normal;
  33802. if (flat) {
  33803. // in flat mode, recalculate normal as face centroid normal
  33804. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33805. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33806. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33807. }
  33808. else {
  33809. // in smooth mode, recalculate normal from each single vertex position
  33810. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33811. }
  33812. // Vertex normal need correction due to X,Y,Z radius scaling
  33813. vertex_normal.x /= radiusX;
  33814. vertex_normal.y /= radiusY;
  33815. vertex_normal.z /= radiusZ;
  33816. vertex_normal.normalize();
  33817. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33818. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33819. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33820. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33821. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33822. uvs.push(uv_interp.x, uv_interp.y);
  33823. // push each vertex has member of a face
  33824. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33825. indices.push(current_indice);
  33826. current_indice++;
  33827. };
  33828. for (var i2 = 0; i2 < subdivisions; i2++) {
  33829. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33830. // face : (i1,i2) for /\ :
  33831. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33832. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33833. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33834. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33835. if (i1 + i2 + 1 < subdivisions) {
  33836. // face : (i1,i2)' for \/ :
  33837. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33838. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33839. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33840. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33841. }
  33842. }
  33843. }
  33844. }
  33845. // Sides
  33846. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33847. // Result
  33848. var vertexData = new VertexData();
  33849. vertexData.indices = indices;
  33850. vertexData.positions = positions;
  33851. vertexData.normals = normals;
  33852. vertexData.uvs = uvs;
  33853. return vertexData;
  33854. };
  33855. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33856. VertexData.CreatePolyhedron = function (options) {
  33857. // provided polyhedron types :
  33858. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33859. // 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)
  33860. var polyhedra = [];
  33861. 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]] };
  33862. 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]] };
  33863. polyhedra[2] = {
  33864. 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]],
  33865. 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]]
  33866. };
  33867. polyhedra[3] = {
  33868. 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]],
  33869. 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]]
  33870. };
  33871. polyhedra[4] = {
  33872. 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]],
  33873. 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]]
  33874. };
  33875. 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]] };
  33876. 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]] };
  33877. 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]] };
  33878. 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]] };
  33879. 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]] };
  33880. 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]] };
  33881. 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]] };
  33882. 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]] };
  33883. 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]] };
  33884. polyhedra[14] = {
  33885. 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]],
  33886. 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]]
  33887. };
  33888. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33889. var size = options.size;
  33890. var sizeX = options.sizeX || size || 1;
  33891. var sizeY = options.sizeY || size || 1;
  33892. var sizeZ = options.sizeZ || size || 1;
  33893. var data = options.custom || polyhedra[type];
  33894. var nbfaces = data.face.length;
  33895. var faceUV = options.faceUV || new Array(nbfaces);
  33896. var faceColors = options.faceColors;
  33897. var flat = (options.flat === undefined) ? true : options.flat;
  33898. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33899. var positions = [];
  33900. var indices = [];
  33901. var normals = [];
  33902. var uvs = [];
  33903. var colors = [];
  33904. var index = 0;
  33905. var faceIdx = 0; // face cursor in the array "indexes"
  33906. var indexes = [];
  33907. var i = 0;
  33908. var f = 0;
  33909. var u, v, ang, x, y, tmp;
  33910. // default face colors and UV if undefined
  33911. if (flat) {
  33912. for (f = 0; f < nbfaces; f++) {
  33913. if (faceColors && faceColors[f] === undefined) {
  33914. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33915. }
  33916. if (faceUV && faceUV[f] === undefined) {
  33917. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33918. }
  33919. }
  33920. }
  33921. if (!flat) {
  33922. for (i = 0; i < data.vertex.length; i++) {
  33923. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33924. uvs.push(0, 0);
  33925. }
  33926. for (f = 0; f < nbfaces; f++) {
  33927. for (i = 0; i < data.face[f].length - 2; i++) {
  33928. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33929. }
  33930. }
  33931. }
  33932. else {
  33933. for (f = 0; f < nbfaces; f++) {
  33934. var fl = data.face[f].length; // number of vertices of the current face
  33935. ang = 2 * Math.PI / fl;
  33936. x = 0.5 * Math.tan(ang / 2);
  33937. y = 0.5;
  33938. // positions, uvs, colors
  33939. for (i = 0; i < fl; i++) {
  33940. // positions
  33941. 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);
  33942. indexes.push(index);
  33943. index++;
  33944. // uvs
  33945. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33946. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33947. uvs.push(u, v);
  33948. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33949. y = x * Math.sin(ang) + y * Math.cos(ang);
  33950. x = tmp;
  33951. // colors
  33952. if (faceColors) {
  33953. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33954. }
  33955. }
  33956. // indices from indexes
  33957. for (i = 0; i < fl - 2; i++) {
  33958. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33959. }
  33960. faceIdx += fl;
  33961. }
  33962. }
  33963. VertexData.ComputeNormals(positions, indices, normals);
  33964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33965. var vertexData = new VertexData();
  33966. vertexData.positions = positions;
  33967. vertexData.indices = indices;
  33968. vertexData.normals = normals;
  33969. vertexData.uvs = uvs;
  33970. if (faceColors && flat) {
  33971. vertexData.colors = colors;
  33972. }
  33973. return vertexData;
  33974. };
  33975. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33976. VertexData.CreateTorusKnot = function (options) {
  33977. var indices = [];
  33978. var positions = [];
  33979. var normals = [];
  33980. var uvs = [];
  33981. var radius = options.radius || 2;
  33982. var tube = options.tube || 0.5;
  33983. var radialSegments = options.radialSegments || 32;
  33984. var tubularSegments = options.tubularSegments || 32;
  33985. var p = options.p || 2;
  33986. var q = options.q || 3;
  33987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33988. // Helper
  33989. var getPos = function (angle) {
  33990. var cu = Math.cos(angle);
  33991. var su = Math.sin(angle);
  33992. var quOverP = q / p * angle;
  33993. var cs = Math.cos(quOverP);
  33994. var tx = radius * (2 + cs) * 0.5 * cu;
  33995. var ty = radius * (2 + cs) * su * 0.5;
  33996. var tz = radius * Math.sin(quOverP) * 0.5;
  33997. return new BABYLON.Vector3(tx, ty, tz);
  33998. };
  33999. // Vertices
  34000. var i;
  34001. var j;
  34002. for (i = 0; i <= radialSegments; i++) {
  34003. var modI = i % radialSegments;
  34004. var u = modI / radialSegments * 2 * p * Math.PI;
  34005. var p1 = getPos(u);
  34006. var p2 = getPos(u + 0.01);
  34007. var tang = p2.subtract(p1);
  34008. var n = p2.add(p1);
  34009. var bitan = BABYLON.Vector3.Cross(tang, n);
  34010. n = BABYLON.Vector3.Cross(bitan, tang);
  34011. bitan.normalize();
  34012. n.normalize();
  34013. for (j = 0; j < tubularSegments; j++) {
  34014. var modJ = j % tubularSegments;
  34015. var v = modJ / tubularSegments * 2 * Math.PI;
  34016. var cx = -tube * Math.cos(v);
  34017. var cy = tube * Math.sin(v);
  34018. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34019. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34020. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34021. uvs.push(i / radialSegments);
  34022. uvs.push(j / tubularSegments);
  34023. }
  34024. }
  34025. for (i = 0; i < radialSegments; i++) {
  34026. for (j = 0; j < tubularSegments; j++) {
  34027. var jNext = (j + 1) % tubularSegments;
  34028. var a = i * tubularSegments + j;
  34029. var b = (i + 1) * tubularSegments + j;
  34030. var c = (i + 1) * tubularSegments + jNext;
  34031. var d = i * tubularSegments + jNext;
  34032. indices.push(d);
  34033. indices.push(b);
  34034. indices.push(a);
  34035. indices.push(d);
  34036. indices.push(c);
  34037. indices.push(b);
  34038. }
  34039. }
  34040. // Normals
  34041. VertexData.ComputeNormals(positions, indices, normals);
  34042. // Sides
  34043. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34044. // Result
  34045. var vertexData = new VertexData();
  34046. vertexData.indices = indices;
  34047. vertexData.positions = positions;
  34048. vertexData.normals = normals;
  34049. vertexData.uvs = uvs;
  34050. return vertexData;
  34051. };
  34052. // Tools
  34053. /**
  34054. * @param {any} - positions (number[] or Float32Array)
  34055. * @param {any} - indices (number[] or Uint16Array)
  34056. * @param {any} - normals (number[] or Float32Array)
  34057. */
  34058. VertexData.ComputeNormals = function (positions, indices, normals) {
  34059. var index = 0;
  34060. var p1p2x = 0.0;
  34061. var p1p2y = 0.0;
  34062. var p1p2z = 0.0;
  34063. var p3p2x = 0.0;
  34064. var p3p2y = 0.0;
  34065. var p3p2z = 0.0;
  34066. var faceNormalx = 0.0;
  34067. var faceNormaly = 0.0;
  34068. var faceNormalz = 0.0;
  34069. var length = 0.0;
  34070. var i1 = 0;
  34071. var i2 = 0;
  34072. var i3 = 0;
  34073. for (index = 0; index < positions.length; index++) {
  34074. normals[index] = 0.0;
  34075. }
  34076. // indice triplet = 1 face
  34077. var nbFaces = indices.length / 3;
  34078. for (index = 0; index < nbFaces; index++) {
  34079. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34080. i2 = indices[index * 3 + 1];
  34081. i3 = indices[index * 3 + 2];
  34082. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34083. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34084. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34085. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34086. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34087. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34088. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34089. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34090. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34091. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34092. length = (length === 0) ? 1.0 : length;
  34093. faceNormalx /= length; // normalize this normal
  34094. faceNormaly /= length;
  34095. faceNormalz /= length;
  34096. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34097. normals[i1 * 3 + 1] += faceNormaly;
  34098. normals[i1 * 3 + 2] += faceNormalz;
  34099. normals[i2 * 3] += faceNormalx;
  34100. normals[i2 * 3 + 1] += faceNormaly;
  34101. normals[i2 * 3 + 2] += faceNormalz;
  34102. normals[i3 * 3] += faceNormalx;
  34103. normals[i3 * 3 + 1] += faceNormaly;
  34104. normals[i3 * 3 + 2] += faceNormalz;
  34105. }
  34106. // last normalization of each normal
  34107. for (index = 0; index < normals.length / 3; index++) {
  34108. faceNormalx = normals[index * 3];
  34109. faceNormaly = normals[index * 3 + 1];
  34110. faceNormalz = normals[index * 3 + 2];
  34111. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34112. length = (length === 0) ? 1.0 : length;
  34113. faceNormalx /= length;
  34114. faceNormaly /= length;
  34115. faceNormalz /= length;
  34116. normals[index * 3] = faceNormalx;
  34117. normals[index * 3 + 1] = faceNormaly;
  34118. normals[index * 3 + 2] = faceNormalz;
  34119. }
  34120. };
  34121. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34122. var li = indices.length;
  34123. var ln = normals.length;
  34124. var i;
  34125. var n;
  34126. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34127. switch (sideOrientation) {
  34128. case BABYLON.Mesh.FRONTSIDE:
  34129. // nothing changed
  34130. break;
  34131. case BABYLON.Mesh.BACKSIDE:
  34132. var tmp;
  34133. // indices
  34134. for (i = 0; i < li; i += 3) {
  34135. tmp = indices[i];
  34136. indices[i] = indices[i + 2];
  34137. indices[i + 2] = tmp;
  34138. }
  34139. // normals
  34140. for (n = 0; n < ln; n++) {
  34141. normals[n] = -normals[n];
  34142. }
  34143. break;
  34144. case BABYLON.Mesh.DOUBLESIDE:
  34145. // positions
  34146. var lp = positions.length;
  34147. var l = lp / 3;
  34148. for (var p = 0; p < lp; p++) {
  34149. positions[lp + p] = positions[p];
  34150. }
  34151. // indices
  34152. for (i = 0; i < li; i += 3) {
  34153. indices[i + li] = indices[i + 2] + l;
  34154. indices[i + 1 + li] = indices[i + 1] + l;
  34155. indices[i + 2 + li] = indices[i] + l;
  34156. }
  34157. // normals
  34158. for (n = 0; n < ln; n++) {
  34159. normals[ln + n] = -normals[n];
  34160. }
  34161. // uvs
  34162. var lu = uvs.length;
  34163. for (var u = 0; u < lu; u++) {
  34164. uvs[u + lu] = uvs[u];
  34165. }
  34166. break;
  34167. }
  34168. };
  34169. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34170. var vertexData = new VertexData();
  34171. // positions
  34172. var positions = parsedVertexData.positions;
  34173. if (positions) {
  34174. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34175. }
  34176. // normals
  34177. var normals = parsedVertexData.normals;
  34178. if (normals) {
  34179. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34180. }
  34181. // uvs
  34182. var uvs = parsedVertexData.uvs;
  34183. if (uvs) {
  34184. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34185. }
  34186. // uv2s
  34187. var uv2s = parsedVertexData.uv2s;
  34188. if (uv2s) {
  34189. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34190. }
  34191. // uv3s
  34192. var uv3s = parsedVertexData.uv3s;
  34193. if (uv3s) {
  34194. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34195. }
  34196. // uv4s
  34197. var uv4s = parsedVertexData.uv4s;
  34198. if (uv4s) {
  34199. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34200. }
  34201. // uv5s
  34202. var uv5s = parsedVertexData.uv5s;
  34203. if (uv5s) {
  34204. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34205. }
  34206. // uv6s
  34207. var uv6s = parsedVertexData.uv6s;
  34208. if (uv6s) {
  34209. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34210. }
  34211. // colors
  34212. var colors = parsedVertexData.colors;
  34213. if (colors) {
  34214. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34215. }
  34216. // matricesIndices
  34217. var matricesIndices = parsedVertexData.matricesIndices;
  34218. if (matricesIndices) {
  34219. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34220. }
  34221. // matricesWeights
  34222. var matricesWeights = parsedVertexData.matricesWeights;
  34223. if (matricesWeights) {
  34224. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34225. }
  34226. // indices
  34227. var indices = parsedVertexData.indices;
  34228. if (indices) {
  34229. vertexData.indices = indices;
  34230. }
  34231. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34232. };
  34233. return VertexData;
  34234. }());
  34235. BABYLON.VertexData = VertexData;
  34236. })(BABYLON || (BABYLON = {}));
  34237. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34238. var BABYLON;
  34239. (function (BABYLON) {
  34240. var Tags = (function () {
  34241. function Tags() {
  34242. }
  34243. Tags.EnableFor = function (obj) {
  34244. obj._tags = obj._tags || {};
  34245. obj.hasTags = function () {
  34246. return Tags.HasTags(obj);
  34247. };
  34248. obj.addTags = function (tagsString) {
  34249. return Tags.AddTagsTo(obj, tagsString);
  34250. };
  34251. obj.removeTags = function (tagsString) {
  34252. return Tags.RemoveTagsFrom(obj, tagsString);
  34253. };
  34254. obj.matchesTagsQuery = function (tagsQuery) {
  34255. return Tags.MatchesQuery(obj, tagsQuery);
  34256. };
  34257. };
  34258. Tags.DisableFor = function (obj) {
  34259. delete obj._tags;
  34260. delete obj.hasTags;
  34261. delete obj.addTags;
  34262. delete obj.removeTags;
  34263. delete obj.matchesTagsQuery;
  34264. };
  34265. Tags.HasTags = function (obj) {
  34266. if (!obj._tags) {
  34267. return false;
  34268. }
  34269. return !BABYLON.Tools.IsEmpty(obj._tags);
  34270. };
  34271. Tags.GetTags = function (obj, asString) {
  34272. if (asString === void 0) { asString = true; }
  34273. if (!obj._tags) {
  34274. return null;
  34275. }
  34276. if (asString) {
  34277. var tagsArray = [];
  34278. for (var tag in obj._tags) {
  34279. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34280. tagsArray.push(tag);
  34281. }
  34282. }
  34283. return tagsArray.join(" ");
  34284. }
  34285. else {
  34286. return obj._tags;
  34287. }
  34288. };
  34289. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34290. // a tag cannot start with '||', '&&', and '!'
  34291. // it cannot contain whitespaces
  34292. Tags.AddTagsTo = function (obj, tagsString) {
  34293. if (!tagsString) {
  34294. return;
  34295. }
  34296. if (typeof tagsString !== "string") {
  34297. return;
  34298. }
  34299. var tags = tagsString.split(" ");
  34300. tags.forEach(function (tag, index, array) {
  34301. Tags._AddTagTo(obj, tag);
  34302. });
  34303. };
  34304. Tags._AddTagTo = function (obj, tag) {
  34305. tag = tag.trim();
  34306. if (tag === "" || tag === "true" || tag === "false") {
  34307. return;
  34308. }
  34309. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34310. return;
  34311. }
  34312. Tags.EnableFor(obj);
  34313. obj._tags[tag] = true;
  34314. };
  34315. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34316. if (!Tags.HasTags(obj)) {
  34317. return;
  34318. }
  34319. var tags = tagsString.split(" ");
  34320. for (var t in tags) {
  34321. Tags._RemoveTagFrom(obj, tags[t]);
  34322. }
  34323. };
  34324. Tags._RemoveTagFrom = function (obj, tag) {
  34325. delete obj._tags[tag];
  34326. };
  34327. Tags.MatchesQuery = function (obj, tagsQuery) {
  34328. if (tagsQuery === undefined) {
  34329. return true;
  34330. }
  34331. if (tagsQuery === "") {
  34332. return Tags.HasTags(obj);
  34333. }
  34334. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34335. };
  34336. return Tags;
  34337. }());
  34338. BABYLON.Tags = Tags;
  34339. })(BABYLON || (BABYLON = {}));
  34340. //# sourceMappingURL=babylon.tags.js.map
  34341. var BABYLON;
  34342. (function (BABYLON) {
  34343. var Internals;
  34344. (function (Internals) {
  34345. var AndOrNotEvaluator = (function () {
  34346. function AndOrNotEvaluator() {
  34347. }
  34348. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34349. if (!query.match(/\([^\(\)]*\)/g)) {
  34350. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34351. }
  34352. else {
  34353. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34354. // remove parenthesis
  34355. r = r.slice(1, r.length - 1);
  34356. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34357. });
  34358. }
  34359. if (query === "true") {
  34360. return true;
  34361. }
  34362. if (query === "false") {
  34363. return false;
  34364. }
  34365. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34366. };
  34367. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34368. evaluateCallback = evaluateCallback || (function (r) {
  34369. return r === "true" ? true : false;
  34370. });
  34371. var result;
  34372. var or = parenthesisContent.split("||");
  34373. for (var i in or) {
  34374. if (or.hasOwnProperty(i)) {
  34375. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34376. var and = ori.split("&&");
  34377. if (and.length > 1) {
  34378. for (var j = 0; j < and.length; ++j) {
  34379. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34380. if (andj !== "true" && andj !== "false") {
  34381. if (andj[0] === "!") {
  34382. result = !evaluateCallback(andj.substring(1));
  34383. }
  34384. else {
  34385. result = evaluateCallback(andj);
  34386. }
  34387. }
  34388. else {
  34389. result = andj === "true" ? true : false;
  34390. }
  34391. if (!result) {
  34392. ori = "false";
  34393. break;
  34394. }
  34395. }
  34396. }
  34397. if (result || ori === "true") {
  34398. result = true;
  34399. break;
  34400. }
  34401. // result equals false (or undefined)
  34402. if (ori !== "true" && ori !== "false") {
  34403. if (ori[0] === "!") {
  34404. result = !evaluateCallback(ori.substring(1));
  34405. }
  34406. else {
  34407. result = evaluateCallback(ori);
  34408. }
  34409. }
  34410. else {
  34411. result = ori === "true" ? true : false;
  34412. }
  34413. }
  34414. }
  34415. // the whole parenthesis scope is replaced by 'true' or 'false'
  34416. return result ? "true" : "false";
  34417. };
  34418. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34419. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34420. // remove whitespaces
  34421. r = r.replace(/[\s]/g, function () { return ""; });
  34422. return r.length % 2 ? "!" : "";
  34423. });
  34424. booleanString = booleanString.trim();
  34425. if (booleanString === "!true") {
  34426. booleanString = "false";
  34427. }
  34428. else if (booleanString === "!false") {
  34429. booleanString = "true";
  34430. }
  34431. return booleanString;
  34432. };
  34433. return AndOrNotEvaluator;
  34434. }());
  34435. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34436. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34437. })(BABYLON || (BABYLON = {}));
  34438. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34439. var BABYLON;
  34440. (function (BABYLON) {
  34441. var PostProcessRenderPass = (function () {
  34442. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34443. this._enabled = true;
  34444. this._refCount = 0;
  34445. this._name = name;
  34446. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34447. this.setRenderList(renderList);
  34448. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34449. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34450. this._scene = scene;
  34451. this._renderList = renderList;
  34452. }
  34453. // private
  34454. PostProcessRenderPass.prototype._incRefCount = function () {
  34455. if (this._refCount === 0) {
  34456. this._scene.customRenderTargets.push(this._renderTexture);
  34457. }
  34458. return ++this._refCount;
  34459. };
  34460. PostProcessRenderPass.prototype._decRefCount = function () {
  34461. this._refCount--;
  34462. if (this._refCount <= 0) {
  34463. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34464. }
  34465. return this._refCount;
  34466. };
  34467. PostProcessRenderPass.prototype._update = function () {
  34468. this.setRenderList(this._renderList);
  34469. };
  34470. // public
  34471. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34472. this._renderTexture.renderList = renderList;
  34473. };
  34474. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34475. return this._renderTexture;
  34476. };
  34477. return PostProcessRenderPass;
  34478. }());
  34479. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34480. })(BABYLON || (BABYLON = {}));
  34481. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34482. var BABYLON;
  34483. (function (BABYLON) {
  34484. var PostProcessRenderEffect = (function () {
  34485. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34486. this._engine = engine;
  34487. this._name = name;
  34488. this._singleInstance = singleInstance || true;
  34489. this._getPostProcess = getPostProcess;
  34490. this._cameras = [];
  34491. this._indicesForCamera = [];
  34492. this._postProcesses = {};
  34493. this._renderPasses = {};
  34494. this._renderEffectAsPasses = {};
  34495. }
  34496. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34497. get: function () {
  34498. for (var index in this._postProcesses) {
  34499. if (!this._postProcesses[index].isSupported) {
  34500. return false;
  34501. }
  34502. }
  34503. return true;
  34504. },
  34505. enumerable: true,
  34506. configurable: true
  34507. });
  34508. PostProcessRenderEffect.prototype._update = function () {
  34509. for (var renderPassName in this._renderPasses) {
  34510. this._renderPasses[renderPassName]._update();
  34511. }
  34512. };
  34513. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34514. this._renderPasses[renderPass._name] = renderPass;
  34515. this._linkParameters();
  34516. };
  34517. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34518. delete this._renderPasses[renderPass._name];
  34519. this._linkParameters();
  34520. };
  34521. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34522. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34523. this._linkParameters();
  34524. };
  34525. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34526. for (var renderPassName in this._renderPasses) {
  34527. if (renderPassName === passName) {
  34528. return this._renderPasses[passName];
  34529. }
  34530. }
  34531. };
  34532. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34533. this._renderPasses = {};
  34534. this._linkParameters();
  34535. };
  34536. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34537. var cameraKey;
  34538. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34539. for (var i = 0; i < _cam.length; i++) {
  34540. var camera = _cam[i];
  34541. var cameraName = camera.name;
  34542. if (this._singleInstance) {
  34543. cameraKey = 0;
  34544. }
  34545. else {
  34546. cameraKey = cameraName;
  34547. }
  34548. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34549. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34550. if (!this._indicesForCamera[cameraName]) {
  34551. this._indicesForCamera[cameraName] = [];
  34552. }
  34553. this._indicesForCamera[cameraName].push(index);
  34554. if (this._cameras.indexOf(camera) === -1) {
  34555. this._cameras[cameraName] = camera;
  34556. }
  34557. for (var passName in this._renderPasses) {
  34558. this._renderPasses[passName]._incRefCount();
  34559. }
  34560. }
  34561. this._linkParameters();
  34562. };
  34563. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34564. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34565. for (var i = 0; i < _cam.length; i++) {
  34566. var camera = _cam[i];
  34567. var cameraName = camera.name;
  34568. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34569. var index = this._cameras.indexOf(cameraName);
  34570. this._indicesForCamera.splice(index, 1);
  34571. this._cameras.splice(index, 1);
  34572. for (var passName in this._renderPasses) {
  34573. this._renderPasses[passName]._decRefCount();
  34574. }
  34575. }
  34576. };
  34577. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34578. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34579. for (var i = 0; i < _cam.length; i++) {
  34580. var camera = _cam[i];
  34581. var cameraName = camera.name;
  34582. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34583. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34584. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34585. }
  34586. }
  34587. for (var passName in this._renderPasses) {
  34588. this._renderPasses[passName]._incRefCount();
  34589. }
  34590. }
  34591. };
  34592. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34593. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34594. for (var i = 0; i < _cam.length; i++) {
  34595. var camera = _cam[i];
  34596. var cameraName = camera.Name;
  34597. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34598. for (var passName in this._renderPasses) {
  34599. this._renderPasses[passName]._decRefCount();
  34600. }
  34601. }
  34602. };
  34603. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34604. if (this._singleInstance) {
  34605. return this._postProcesses[0];
  34606. }
  34607. else {
  34608. return this._postProcesses[camera.name];
  34609. }
  34610. };
  34611. PostProcessRenderEffect.prototype._linkParameters = function () {
  34612. var _this = this;
  34613. for (var index in this._postProcesses) {
  34614. if (this.applyParameters) {
  34615. this.applyParameters(this._postProcesses[index]);
  34616. }
  34617. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34618. _this._linkTextures(effect);
  34619. });
  34620. }
  34621. };
  34622. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34623. for (var renderPassName in this._renderPasses) {
  34624. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34625. }
  34626. for (var renderEffectName in this._renderEffectAsPasses) {
  34627. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34628. }
  34629. };
  34630. return PostProcessRenderEffect;
  34631. }());
  34632. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34633. })(BABYLON || (BABYLON = {}));
  34634. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34635. var BABYLON;
  34636. (function (BABYLON) {
  34637. var PostProcessRenderPipeline = (function () {
  34638. function PostProcessRenderPipeline(engine, name) {
  34639. this._engine = engine;
  34640. this._name = name;
  34641. this._renderEffects = {};
  34642. this._renderEffectsForIsolatedPass = {};
  34643. this._cameras = [];
  34644. }
  34645. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34646. get: function () {
  34647. for (var renderEffectName in this._renderEffects) {
  34648. if (!this._renderEffects[renderEffectName].isSupported) {
  34649. return false;
  34650. }
  34651. }
  34652. return true;
  34653. },
  34654. enumerable: true,
  34655. configurable: true
  34656. });
  34657. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34658. this._renderEffects[renderEffect._name] = renderEffect;
  34659. };
  34660. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34661. var renderEffects = this._renderEffects[renderEffectName];
  34662. if (!renderEffects) {
  34663. return;
  34664. }
  34665. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34666. };
  34667. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34668. var renderEffects = this._renderEffects[renderEffectName];
  34669. if (!renderEffects) {
  34670. return;
  34671. }
  34672. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34673. };
  34674. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34675. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34676. var indicesToDelete = [];
  34677. var i;
  34678. for (i = 0; i < _cam.length; i++) {
  34679. var camera = _cam[i];
  34680. var cameraName = camera.name;
  34681. if (this._cameras.indexOf(camera) === -1) {
  34682. this._cameras[cameraName] = camera;
  34683. }
  34684. else if (unique) {
  34685. indicesToDelete.push(i);
  34686. }
  34687. }
  34688. for (i = 0; i < indicesToDelete.length; i++) {
  34689. cameras.splice(indicesToDelete[i], 1);
  34690. }
  34691. for (var renderEffectName in this._renderEffects) {
  34692. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34693. }
  34694. };
  34695. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34696. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34697. for (var renderEffectName in this._renderEffects) {
  34698. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34699. }
  34700. for (var i = 0; i < _cam.length; i++) {
  34701. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34702. }
  34703. };
  34704. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34705. var _this = this;
  34706. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34707. var pass = null;
  34708. var renderEffectName;
  34709. for (renderEffectName in this._renderEffects) {
  34710. pass = this._renderEffects[renderEffectName].getPass(passName);
  34711. if (pass != null) {
  34712. break;
  34713. }
  34714. }
  34715. if (pass === null) {
  34716. return;
  34717. }
  34718. for (renderEffectName in this._renderEffects) {
  34719. this._renderEffects[renderEffectName]._disable(_cam);
  34720. }
  34721. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34722. for (var i = 0; i < _cam.length; i++) {
  34723. var camera = _cam[i];
  34724. var cameraName = camera.name;
  34725. 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); });
  34726. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34727. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34728. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34729. }
  34730. };
  34731. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34732. var _this = this;
  34733. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34734. for (var i = 0; i < _cam.length; i++) {
  34735. var camera = _cam[i];
  34736. var cameraName = camera.name;
  34737. 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); });
  34738. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34739. }
  34740. for (var renderEffectName in this._renderEffects) {
  34741. this._renderEffects[renderEffectName]._enable(_cam);
  34742. }
  34743. };
  34744. PostProcessRenderPipeline.prototype._update = function () {
  34745. for (var renderEffectName in this._renderEffects) {
  34746. this._renderEffects[renderEffectName]._update();
  34747. }
  34748. for (var i = 0; i < this._cameras.length; i++) {
  34749. var cameraName = this._cameras[i].name;
  34750. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34751. this._renderEffectsForIsolatedPass[cameraName]._update();
  34752. }
  34753. }
  34754. };
  34755. PostProcessRenderPipeline.prototype.dispose = function () {
  34756. // Must be implemented by children
  34757. };
  34758. return PostProcessRenderPipeline;
  34759. }());
  34760. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34761. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34762. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34763. })(BABYLON || (BABYLON = {}));
  34764. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34765. var BABYLON;
  34766. (function (BABYLON) {
  34767. var PostProcessRenderPipelineManager = (function () {
  34768. function PostProcessRenderPipelineManager() {
  34769. this._renderPipelines = {};
  34770. }
  34771. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34772. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34773. };
  34774. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34775. var renderPipeline = this._renderPipelines[renderPipelineName];
  34776. if (!renderPipeline) {
  34777. return;
  34778. }
  34779. renderPipeline._attachCameras(cameras, unique);
  34780. };
  34781. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34782. var renderPipeline = this._renderPipelines[renderPipelineName];
  34783. if (!renderPipeline) {
  34784. return;
  34785. }
  34786. renderPipeline._detachCameras(cameras);
  34787. };
  34788. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34789. var renderPipeline = this._renderPipelines[renderPipelineName];
  34790. if (!renderPipeline) {
  34791. return;
  34792. }
  34793. renderPipeline._enableEffect(renderEffectName, cameras);
  34794. };
  34795. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34796. var renderPipeline = this._renderPipelines[renderPipelineName];
  34797. if (!renderPipeline) {
  34798. return;
  34799. }
  34800. renderPipeline._disableEffect(renderEffectName, cameras);
  34801. };
  34802. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34803. var renderPipeline = this._renderPipelines[renderPipelineName];
  34804. if (!renderPipeline) {
  34805. return;
  34806. }
  34807. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34808. };
  34809. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34810. var renderPipeline = this._renderPipelines[renderPipelineName];
  34811. if (!renderPipeline) {
  34812. return;
  34813. }
  34814. renderPipeline._disableDisplayOnlyPass(cameras);
  34815. };
  34816. PostProcessRenderPipelineManager.prototype.update = function () {
  34817. for (var renderPipelineName in this._renderPipelines) {
  34818. var pipeline = this._renderPipelines[renderPipelineName];
  34819. if (!pipeline.isSupported) {
  34820. pipeline.dispose();
  34821. delete this._renderPipelines[renderPipelineName];
  34822. }
  34823. else {
  34824. pipeline._update();
  34825. }
  34826. }
  34827. };
  34828. return PostProcessRenderPipelineManager;
  34829. }());
  34830. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34831. })(BABYLON || (BABYLON = {}));
  34832. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34833. var BABYLON;
  34834. (function (BABYLON) {
  34835. var BoundingBoxRenderer = (function () {
  34836. function BoundingBoxRenderer(scene) {
  34837. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34838. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34839. this.showBackLines = true;
  34840. this.renderList = new BABYLON.SmartArray(32);
  34841. this._vertexBuffers = {};
  34842. this._scene = scene;
  34843. }
  34844. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34845. if (this._colorShader) {
  34846. return;
  34847. }
  34848. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34849. attributes: [BABYLON.VertexBuffer.PositionKind],
  34850. uniforms: ["worldViewProjection", "color"]
  34851. });
  34852. var engine = this._scene.getEngine();
  34853. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34854. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34855. 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]);
  34856. };
  34857. BoundingBoxRenderer.prototype.reset = function () {
  34858. this.renderList.reset();
  34859. };
  34860. BoundingBoxRenderer.prototype.render = function () {
  34861. if (this.renderList.length === 0) {
  34862. return;
  34863. }
  34864. this._prepareRessources();
  34865. if (!this._colorShader.isReady()) {
  34866. return;
  34867. }
  34868. var engine = this._scene.getEngine();
  34869. engine.setDepthWrite(false);
  34870. this._colorShader._preBind();
  34871. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34872. var boundingBox = this.renderList.data[boundingBoxIndex];
  34873. var min = boundingBox.minimum;
  34874. var max = boundingBox.maximum;
  34875. var diff = max.subtract(min);
  34876. var median = min.add(diff.scale(0.5));
  34877. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34878. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34879. .multiply(boundingBox.getWorldMatrix());
  34880. // VBOs
  34881. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34882. if (this.showBackLines) {
  34883. // Back
  34884. engine.setDepthFunctionToGreaterOrEqual();
  34885. this._scene.resetCachedMaterial();
  34886. this._colorShader.setColor4("color", this.backColor.toColor4());
  34887. this._colorShader.bind(worldMatrix);
  34888. // Draw order
  34889. engine.draw(false, 0, 24);
  34890. }
  34891. // Front
  34892. engine.setDepthFunctionToLess();
  34893. this._scene.resetCachedMaterial();
  34894. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34895. this._colorShader.bind(worldMatrix);
  34896. // Draw order
  34897. engine.draw(false, 0, 24);
  34898. }
  34899. this._colorShader.unbind();
  34900. engine.setDepthFunctionToLessOrEqual();
  34901. engine.setDepthWrite(true);
  34902. };
  34903. BoundingBoxRenderer.prototype.dispose = function () {
  34904. if (!this._colorShader) {
  34905. return;
  34906. }
  34907. this._colorShader.dispose();
  34908. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34909. if (buffer) {
  34910. buffer.dispose();
  34911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34912. }
  34913. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34914. };
  34915. return BoundingBoxRenderer;
  34916. }());
  34917. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34918. })(BABYLON || (BABYLON = {}));
  34919. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34920. var BABYLON;
  34921. (function (BABYLON) {
  34922. var Condition = (function () {
  34923. function Condition(actionManager) {
  34924. this._actionManager = actionManager;
  34925. }
  34926. Condition.prototype.isValid = function () {
  34927. return true;
  34928. };
  34929. Condition.prototype._getProperty = function (propertyPath) {
  34930. return this._actionManager._getProperty(propertyPath);
  34931. };
  34932. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34933. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34934. };
  34935. Condition.prototype.serialize = function () {
  34936. };
  34937. Condition.prototype._serialize = function (serializedCondition) {
  34938. return {
  34939. type: 2,
  34940. children: [],
  34941. name: serializedCondition.name,
  34942. properties: serializedCondition.properties
  34943. };
  34944. };
  34945. return Condition;
  34946. }());
  34947. BABYLON.Condition = Condition;
  34948. var ValueCondition = (function (_super) {
  34949. __extends(ValueCondition, _super);
  34950. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34951. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34952. var _this = _super.call(this, actionManager) || this;
  34953. _this.propertyPath = propertyPath;
  34954. _this.value = value;
  34955. _this.operator = operator;
  34956. _this._target = target;
  34957. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  34958. _this._property = _this._getProperty(_this.propertyPath);
  34959. return _this;
  34960. }
  34961. Object.defineProperty(ValueCondition, "IsEqual", {
  34962. get: function () {
  34963. return ValueCondition._IsEqual;
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. Object.defineProperty(ValueCondition, "IsDifferent", {
  34969. get: function () {
  34970. return ValueCondition._IsDifferent;
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(ValueCondition, "IsGreater", {
  34976. get: function () {
  34977. return ValueCondition._IsGreater;
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. Object.defineProperty(ValueCondition, "IsLesser", {
  34983. get: function () {
  34984. return ValueCondition._IsLesser;
  34985. },
  34986. enumerable: true,
  34987. configurable: true
  34988. });
  34989. // Methods
  34990. ValueCondition.prototype.isValid = function () {
  34991. switch (this.operator) {
  34992. case ValueCondition.IsGreater:
  34993. return this._effectiveTarget[this._property] > this.value;
  34994. case ValueCondition.IsLesser:
  34995. return this._effectiveTarget[this._property] < this.value;
  34996. case ValueCondition.IsEqual:
  34997. case ValueCondition.IsDifferent:
  34998. var check;
  34999. if (this.value.equals) {
  35000. check = this.value.equals(this._effectiveTarget[this._property]);
  35001. }
  35002. else {
  35003. check = this.value === this._effectiveTarget[this._property];
  35004. }
  35005. return this.operator === ValueCondition.IsEqual ? check : !check;
  35006. }
  35007. return false;
  35008. };
  35009. ValueCondition.prototype.serialize = function () {
  35010. return this._serialize({
  35011. name: "ValueCondition",
  35012. properties: [
  35013. BABYLON.Action._GetTargetProperty(this._target),
  35014. { name: "propertyPath", value: this.propertyPath },
  35015. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35016. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35017. ]
  35018. });
  35019. };
  35020. ValueCondition.GetOperatorName = function (operator) {
  35021. switch (operator) {
  35022. case ValueCondition._IsEqual: return "IsEqual";
  35023. case ValueCondition._IsDifferent: return "IsDifferent";
  35024. case ValueCondition._IsGreater: return "IsGreater";
  35025. case ValueCondition._IsLesser: return "IsLesser";
  35026. default: return "";
  35027. }
  35028. };
  35029. return ValueCondition;
  35030. }(Condition));
  35031. // Statics
  35032. ValueCondition._IsEqual = 0;
  35033. ValueCondition._IsDifferent = 1;
  35034. ValueCondition._IsGreater = 2;
  35035. ValueCondition._IsLesser = 3;
  35036. BABYLON.ValueCondition = ValueCondition;
  35037. var PredicateCondition = (function (_super) {
  35038. __extends(PredicateCondition, _super);
  35039. function PredicateCondition(actionManager, predicate) {
  35040. var _this = _super.call(this, actionManager) || this;
  35041. _this.predicate = predicate;
  35042. return _this;
  35043. }
  35044. PredicateCondition.prototype.isValid = function () {
  35045. return this.predicate();
  35046. };
  35047. return PredicateCondition;
  35048. }(Condition));
  35049. BABYLON.PredicateCondition = PredicateCondition;
  35050. var StateCondition = (function (_super) {
  35051. __extends(StateCondition, _super);
  35052. function StateCondition(actionManager, target, value) {
  35053. var _this = _super.call(this, actionManager) || this;
  35054. _this.value = value;
  35055. _this._target = target;
  35056. return _this;
  35057. }
  35058. // Methods
  35059. StateCondition.prototype.isValid = function () {
  35060. return this._target.state === this.value;
  35061. };
  35062. StateCondition.prototype.serialize = function () {
  35063. return this._serialize({
  35064. name: "StateCondition",
  35065. properties: [
  35066. BABYLON.Action._GetTargetProperty(this._target),
  35067. { name: "value", value: this.value }
  35068. ]
  35069. });
  35070. };
  35071. return StateCondition;
  35072. }(Condition));
  35073. BABYLON.StateCondition = StateCondition;
  35074. })(BABYLON || (BABYLON = {}));
  35075. //# sourceMappingURL=babylon.condition.js.map
  35076. var BABYLON;
  35077. (function (BABYLON) {
  35078. var Action = (function () {
  35079. function Action(triggerOptions, condition) {
  35080. this.triggerOptions = triggerOptions;
  35081. if (triggerOptions.parameter) {
  35082. this.trigger = triggerOptions.trigger;
  35083. this._triggerParameter = triggerOptions.parameter;
  35084. }
  35085. else {
  35086. this.trigger = triggerOptions;
  35087. }
  35088. this._nextActiveAction = this;
  35089. this._condition = condition;
  35090. }
  35091. // Methods
  35092. Action.prototype._prepare = function () {
  35093. };
  35094. Action.prototype.getTriggerParameter = function () {
  35095. return this._triggerParameter;
  35096. };
  35097. Action.prototype._executeCurrent = function (evt) {
  35098. if (this._nextActiveAction._condition) {
  35099. var condition = this._nextActiveAction._condition;
  35100. var currentRenderId = this._actionManager.getScene().getRenderId();
  35101. // We cache the current evaluation for the current frame
  35102. if (condition._evaluationId === currentRenderId) {
  35103. if (!condition._currentResult) {
  35104. return;
  35105. }
  35106. }
  35107. else {
  35108. condition._evaluationId = currentRenderId;
  35109. if (!condition.isValid()) {
  35110. condition._currentResult = false;
  35111. return;
  35112. }
  35113. condition._currentResult = true;
  35114. }
  35115. }
  35116. this._nextActiveAction.execute(evt);
  35117. this.skipToNextActiveAction();
  35118. };
  35119. Action.prototype.execute = function (evt) {
  35120. };
  35121. Action.prototype.skipToNextActiveAction = function () {
  35122. if (this._nextActiveAction._child) {
  35123. if (!this._nextActiveAction._child._actionManager) {
  35124. this._nextActiveAction._child._actionManager = this._actionManager;
  35125. }
  35126. this._nextActiveAction = this._nextActiveAction._child;
  35127. }
  35128. else {
  35129. this._nextActiveAction = this;
  35130. }
  35131. };
  35132. Action.prototype.then = function (action) {
  35133. this._child = action;
  35134. action._actionManager = this._actionManager;
  35135. action._prepare();
  35136. return action;
  35137. };
  35138. Action.prototype._getProperty = function (propertyPath) {
  35139. return this._actionManager._getProperty(propertyPath);
  35140. };
  35141. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35142. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35143. };
  35144. Action.prototype.serialize = function (parent) {
  35145. };
  35146. // Called by BABYLON.Action objects in serialize(...). Internal use
  35147. Action.prototype._serialize = function (serializedAction, parent) {
  35148. var serializationObject = {
  35149. type: 1,
  35150. children: [],
  35151. name: serializedAction.name,
  35152. properties: serializedAction.properties || []
  35153. };
  35154. // Serialize child
  35155. if (this._child) {
  35156. this._child.serialize(serializationObject);
  35157. }
  35158. // Check if "this" has a condition
  35159. if (this._condition) {
  35160. var serializedCondition = this._condition.serialize();
  35161. serializedCondition.children.push(serializationObject);
  35162. if (parent) {
  35163. parent.children.push(serializedCondition);
  35164. }
  35165. return serializedCondition;
  35166. }
  35167. if (parent) {
  35168. parent.children.push(serializationObject);
  35169. }
  35170. return serializationObject;
  35171. };
  35172. return Action;
  35173. }());
  35174. Action._SerializeValueAsString = function (value) {
  35175. if (typeof value === "number") {
  35176. return value.toString();
  35177. }
  35178. if (typeof value === "boolean") {
  35179. return value ? "true" : "false";
  35180. }
  35181. if (value instanceof BABYLON.Vector2) {
  35182. return value.x + ", " + value.y;
  35183. }
  35184. if (value instanceof BABYLON.Vector3) {
  35185. return value.x + ", " + value.y + ", " + value.z;
  35186. }
  35187. if (value instanceof BABYLON.Color3) {
  35188. return value.r + ", " + value.g + ", " + value.b;
  35189. }
  35190. if (value instanceof BABYLON.Color4) {
  35191. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35192. }
  35193. return value; // string
  35194. };
  35195. Action._GetTargetProperty = function (target) {
  35196. return {
  35197. name: "target",
  35198. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35199. : target instanceof BABYLON.Light ? "LightProperties"
  35200. : target instanceof BABYLON.Camera ? "CameraProperties"
  35201. : "SceneProperties",
  35202. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35203. };
  35204. };
  35205. BABYLON.Action = Action;
  35206. })(BABYLON || (BABYLON = {}));
  35207. //# sourceMappingURL=babylon.action.js.map
  35208. var BABYLON;
  35209. (function (BABYLON) {
  35210. /**
  35211. * ActionEvent is the event beint sent when an action is triggered.
  35212. */
  35213. var ActionEvent = (function () {
  35214. /**
  35215. * @constructor
  35216. * @param source The mesh or sprite that triggered the action.
  35217. * @param pointerX The X mouse cursor position at the time of the event
  35218. * @param pointerY The Y mouse cursor position at the time of the event
  35219. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35220. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35221. */
  35222. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35223. this.source = source;
  35224. this.pointerX = pointerX;
  35225. this.pointerY = pointerY;
  35226. this.meshUnderPointer = meshUnderPointer;
  35227. this.sourceEvent = sourceEvent;
  35228. this.additionalData = additionalData;
  35229. }
  35230. /**
  35231. * Helper function to auto-create an ActionEvent from a source mesh.
  35232. * @param source The source mesh that triggered the event
  35233. * @param evt {Event} The original (browser) event
  35234. */
  35235. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35236. var scene = source.getScene();
  35237. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35238. };
  35239. /**
  35240. * Helper function to auto-create an ActionEvent from a source mesh.
  35241. * @param source The source sprite that triggered the event
  35242. * @param scene Scene associated with the sprite
  35243. * @param evt {Event} The original (browser) event
  35244. */
  35245. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35246. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35247. };
  35248. /**
  35249. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35250. * @param scene the scene where the event occurred
  35251. * @param evt {Event} The original (browser) event
  35252. */
  35253. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35254. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35255. };
  35256. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35257. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35258. };
  35259. return ActionEvent;
  35260. }());
  35261. BABYLON.ActionEvent = ActionEvent;
  35262. /**
  35263. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35264. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35265. */
  35266. var ActionManager = (function () {
  35267. function ActionManager(scene) {
  35268. // Members
  35269. this.actions = new Array();
  35270. this.hoverCursor = '';
  35271. this._scene = scene;
  35272. scene._actionManagers.push(this);
  35273. }
  35274. Object.defineProperty(ActionManager, "NothingTrigger", {
  35275. get: function () {
  35276. return ActionManager._NothingTrigger;
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35282. get: function () {
  35283. return ActionManager._OnPickTrigger;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35289. get: function () {
  35290. return ActionManager._OnLeftPickTrigger;
  35291. },
  35292. enumerable: true,
  35293. configurable: true
  35294. });
  35295. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35296. get: function () {
  35297. return ActionManager._OnRightPickTrigger;
  35298. },
  35299. enumerable: true,
  35300. configurable: true
  35301. });
  35302. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35303. get: function () {
  35304. return ActionManager._OnCenterPickTrigger;
  35305. },
  35306. enumerable: true,
  35307. configurable: true
  35308. });
  35309. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35310. get: function () {
  35311. return ActionManager._OnPickDownTrigger;
  35312. },
  35313. enumerable: true,
  35314. configurable: true
  35315. });
  35316. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35317. get: function () {
  35318. return ActionManager._OnPickUpTrigger;
  35319. },
  35320. enumerable: true,
  35321. configurable: true
  35322. });
  35323. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35324. /// This trigger will only be raised if you also declared a OnPickDown
  35325. get: function () {
  35326. return ActionManager._OnPickOutTrigger;
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35332. get: function () {
  35333. return ActionManager._OnLongPressTrigger;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35339. get: function () {
  35340. return ActionManager._OnPointerOverTrigger;
  35341. },
  35342. enumerable: true,
  35343. configurable: true
  35344. });
  35345. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35346. get: function () {
  35347. return ActionManager._OnPointerOutTrigger;
  35348. },
  35349. enumerable: true,
  35350. configurable: true
  35351. });
  35352. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35353. get: function () {
  35354. return ActionManager._OnEveryFrameTrigger;
  35355. },
  35356. enumerable: true,
  35357. configurable: true
  35358. });
  35359. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35360. get: function () {
  35361. return ActionManager._OnIntersectionEnterTrigger;
  35362. },
  35363. enumerable: true,
  35364. configurable: true
  35365. });
  35366. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35367. get: function () {
  35368. return ActionManager._OnIntersectionExitTrigger;
  35369. },
  35370. enumerable: true,
  35371. configurable: true
  35372. });
  35373. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35374. get: function () {
  35375. return ActionManager._OnKeyDownTrigger;
  35376. },
  35377. enumerable: true,
  35378. configurable: true
  35379. });
  35380. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35381. get: function () {
  35382. return ActionManager._OnKeyUpTrigger;
  35383. },
  35384. enumerable: true,
  35385. configurable: true
  35386. });
  35387. // Methods
  35388. ActionManager.prototype.dispose = function () {
  35389. var index = this._scene._actionManagers.indexOf(this);
  35390. if (index > -1) {
  35391. this._scene._actionManagers.splice(index, 1);
  35392. }
  35393. };
  35394. ActionManager.prototype.getScene = function () {
  35395. return this._scene;
  35396. };
  35397. /**
  35398. * Does this action manager handles actions of any of the given triggers
  35399. * @param {number[]} triggers - the triggers to be tested
  35400. * @return {boolean} whether one (or more) of the triggers is handeled
  35401. */
  35402. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35403. for (var index = 0; index < this.actions.length; index++) {
  35404. var action = this.actions[index];
  35405. if (triggers.indexOf(action.trigger) > -1) {
  35406. return true;
  35407. }
  35408. }
  35409. return false;
  35410. };
  35411. /**
  35412. * Does this action manager handles actions of a given trigger
  35413. * @param {number} trigger - the trigger to be tested
  35414. * @return {boolean} whether the trigger is handeled
  35415. */
  35416. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35417. for (var index = 0; index < this.actions.length; index++) {
  35418. var action = this.actions[index];
  35419. if (action.trigger === trigger) {
  35420. return true;
  35421. }
  35422. }
  35423. return false;
  35424. };
  35425. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35426. /**
  35427. * Does this action manager has pointer triggers
  35428. * @return {boolean} whether or not it has pointer triggers
  35429. */
  35430. get: function () {
  35431. for (var index = 0; index < this.actions.length; index++) {
  35432. var action = this.actions[index];
  35433. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35434. return true;
  35435. }
  35436. }
  35437. return false;
  35438. },
  35439. enumerable: true,
  35440. configurable: true
  35441. });
  35442. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35443. /**
  35444. * Does this action manager has pick triggers
  35445. * @return {boolean} whether or not it has pick triggers
  35446. */
  35447. get: function () {
  35448. for (var index = 0; index < this.actions.length; index++) {
  35449. var action = this.actions[index];
  35450. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35451. return true;
  35452. }
  35453. }
  35454. return false;
  35455. },
  35456. enumerable: true,
  35457. configurable: true
  35458. });
  35459. /**
  35460. * Registers an action to this action manager
  35461. * @param {BABYLON.Action} action - the action to be registered
  35462. * @return {BABYLON.Action} the action amended (prepared) after registration
  35463. */
  35464. ActionManager.prototype.registerAction = function (action) {
  35465. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35466. if (this.getScene().actionManager !== this) {
  35467. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35468. return null;
  35469. }
  35470. }
  35471. this.actions.push(action);
  35472. action._actionManager = this;
  35473. action._prepare();
  35474. return action;
  35475. };
  35476. /**
  35477. * Process a specific trigger
  35478. * @param {number} trigger - the trigger to process
  35479. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35480. */
  35481. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35482. for (var index = 0; index < this.actions.length; index++) {
  35483. var action = this.actions[index];
  35484. if (action.trigger === trigger) {
  35485. if (trigger === ActionManager.OnKeyUpTrigger
  35486. || trigger === ActionManager.OnKeyDownTrigger) {
  35487. var parameter = action.getTriggerParameter();
  35488. if (parameter) {
  35489. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35490. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35491. if (actualkey !== parameter.toLowerCase()) {
  35492. continue;
  35493. }
  35494. }
  35495. }
  35496. action._executeCurrent(evt);
  35497. }
  35498. }
  35499. };
  35500. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35501. var properties = propertyPath.split(".");
  35502. for (var index = 0; index < properties.length - 1; index++) {
  35503. target = target[properties[index]];
  35504. }
  35505. return target;
  35506. };
  35507. ActionManager.prototype._getProperty = function (propertyPath) {
  35508. var properties = propertyPath.split(".");
  35509. return properties[properties.length - 1];
  35510. };
  35511. ActionManager.prototype.serialize = function (name) {
  35512. var root = {
  35513. children: [],
  35514. name: name,
  35515. type: 3,
  35516. properties: [] // Empty for root but required
  35517. };
  35518. for (var i = 0; i < this.actions.length; i++) {
  35519. var triggerObject = {
  35520. type: 0,
  35521. children: [],
  35522. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35523. properties: []
  35524. };
  35525. var triggerOptions = this.actions[i].triggerOptions;
  35526. if (triggerOptions && typeof triggerOptions !== "number") {
  35527. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35528. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35529. }
  35530. else {
  35531. var parameter = {};
  35532. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35533. if (triggerOptions.parameter.mesh) {
  35534. parameter._meshId = triggerOptions.parameter.mesh.id;
  35535. }
  35536. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35537. }
  35538. }
  35539. // Serialize child action, recursively
  35540. this.actions[i].serialize(triggerObject);
  35541. // Add serialized trigger
  35542. root.children.push(triggerObject);
  35543. }
  35544. return root;
  35545. };
  35546. ActionManager.Parse = function (parsedActions, object, scene) {
  35547. var actionManager = new BABYLON.ActionManager(scene);
  35548. if (object === null)
  35549. scene.actionManager = actionManager;
  35550. else
  35551. object.actionManager = actionManager;
  35552. // instanciate a new object
  35553. var instanciate = function (name, params) {
  35554. var newInstance = Object.create(BABYLON[name].prototype);
  35555. newInstance.constructor.apply(newInstance, params);
  35556. return newInstance;
  35557. };
  35558. var parseParameter = function (name, value, target, propertyPath) {
  35559. if (propertyPath === null) {
  35560. // String, boolean or float
  35561. var floatValue = parseFloat(value);
  35562. if (value === "true" || value === "false")
  35563. return value === "true";
  35564. else
  35565. return isNaN(floatValue) ? value : floatValue;
  35566. }
  35567. var effectiveTarget = propertyPath.split(".");
  35568. var values = value.split(",");
  35569. // Get effective Target
  35570. for (var i = 0; i < effectiveTarget.length; i++) {
  35571. target = target[effectiveTarget[i]];
  35572. }
  35573. // Return appropriate value with its type
  35574. if (typeof (target) === "boolean")
  35575. return values[0] === "true";
  35576. if (typeof (target) === "string")
  35577. return values[0];
  35578. // Parameters with multiple values such as Vector3 etc.
  35579. var split = new Array();
  35580. for (var i = 0; i < values.length; i++)
  35581. split.push(parseFloat(values[i]));
  35582. if (target instanceof BABYLON.Vector3)
  35583. return BABYLON.Vector3.FromArray(split);
  35584. if (target instanceof BABYLON.Vector4)
  35585. return BABYLON.Vector4.FromArray(split);
  35586. if (target instanceof BABYLON.Color3)
  35587. return BABYLON.Color3.FromArray(split);
  35588. if (target instanceof BABYLON.Color4)
  35589. return BABYLON.Color4.FromArray(split);
  35590. return parseFloat(values[0]);
  35591. };
  35592. // traverse graph per trigger
  35593. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35594. if (combineArray === void 0) { combineArray = null; }
  35595. if (parsedAction.detached)
  35596. return;
  35597. var parameters = new Array();
  35598. var target = null;
  35599. var propertyPath = null;
  35600. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35601. // Parameters
  35602. if (parsedAction.type === 2)
  35603. parameters.push(actionManager);
  35604. else
  35605. parameters.push(trigger);
  35606. if (combine) {
  35607. var actions = new Array();
  35608. for (var j = 0; j < parsedAction.combine.length; j++) {
  35609. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35610. }
  35611. parameters.push(actions);
  35612. }
  35613. else {
  35614. for (var i = 0; i < parsedAction.properties.length; i++) {
  35615. var value = parsedAction.properties[i].value;
  35616. var name = parsedAction.properties[i].name;
  35617. var targetType = parsedAction.properties[i].targetType;
  35618. if (name === "target")
  35619. if (targetType !== null && targetType === "SceneProperties")
  35620. value = target = scene;
  35621. else
  35622. value = target = scene.getNodeByName(value);
  35623. else if (name === "parent")
  35624. value = scene.getNodeByName(value);
  35625. else if (name === "sound")
  35626. value = scene.getSoundByName(value);
  35627. else if (name !== "propertyPath") {
  35628. if (parsedAction.type === 2 && name === "operator")
  35629. value = BABYLON.ValueCondition[value];
  35630. else
  35631. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35632. }
  35633. else {
  35634. propertyPath = value;
  35635. }
  35636. parameters.push(value);
  35637. }
  35638. }
  35639. if (combineArray === null) {
  35640. parameters.push(condition);
  35641. }
  35642. else {
  35643. parameters.push(null);
  35644. }
  35645. // If interpolate value action
  35646. if (parsedAction.name === "InterpolateValueAction") {
  35647. var param = parameters[parameters.length - 2];
  35648. parameters[parameters.length - 1] = param;
  35649. parameters[parameters.length - 2] = condition;
  35650. }
  35651. // Action or condition(s) and not CombineAction
  35652. var newAction = instanciate(parsedAction.name, parameters);
  35653. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35654. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35655. if (action)
  35656. action.then(nothing);
  35657. else
  35658. actionManager.registerAction(nothing);
  35659. action = nothing;
  35660. }
  35661. if (combineArray === null) {
  35662. if (newAction instanceof BABYLON.Condition) {
  35663. condition = newAction;
  35664. newAction = action;
  35665. }
  35666. else {
  35667. condition = null;
  35668. if (action)
  35669. action.then(newAction);
  35670. else
  35671. actionManager.registerAction(newAction);
  35672. }
  35673. }
  35674. else {
  35675. combineArray.push(newAction);
  35676. }
  35677. for (var i = 0; i < parsedAction.children.length; i++)
  35678. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35679. };
  35680. // triggers
  35681. for (var i = 0; i < parsedActions.children.length; i++) {
  35682. var triggerParams;
  35683. var trigger = parsedActions.children[i];
  35684. if (trigger.properties.length > 0) {
  35685. var param = trigger.properties[0].value;
  35686. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35687. if (value._meshId) {
  35688. value.mesh = scene.getMeshByID(value._meshId);
  35689. }
  35690. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35691. }
  35692. else
  35693. triggerParams = BABYLON.ActionManager[trigger.name];
  35694. for (var j = 0; j < trigger.children.length; j++) {
  35695. if (!trigger.detached)
  35696. traverse(trigger.children[j], triggerParams, null, null);
  35697. }
  35698. }
  35699. };
  35700. ActionManager.GetTriggerName = function (trigger) {
  35701. switch (trigger) {
  35702. case 0: return "NothingTrigger";
  35703. case 1: return "OnPickTrigger";
  35704. case 2: return "OnLeftPickTrigger";
  35705. case 3: return "OnRightPickTrigger";
  35706. case 4: return "OnCenterPickTrigger";
  35707. case 5: return "OnPickDownTrigger";
  35708. case 6: return "OnPickUpTrigger";
  35709. case 7: return "OnLongPressTrigger";
  35710. case 8: return "OnPointerOverTrigger";
  35711. case 9: return "OnPointerOutTrigger";
  35712. case 10: return "OnEveryFrameTrigger";
  35713. case 11: return "OnIntersectionEnterTrigger";
  35714. case 12: return "OnIntersectionExitTrigger";
  35715. case 13: return "OnKeyDownTrigger";
  35716. case 14: return "OnKeyUpTrigger";
  35717. case 15: return "OnPickOutTrigger";
  35718. default: return "";
  35719. }
  35720. };
  35721. return ActionManager;
  35722. }());
  35723. // Statics
  35724. ActionManager._NothingTrigger = 0;
  35725. ActionManager._OnPickTrigger = 1;
  35726. ActionManager._OnLeftPickTrigger = 2;
  35727. ActionManager._OnRightPickTrigger = 3;
  35728. ActionManager._OnCenterPickTrigger = 4;
  35729. ActionManager._OnPickDownTrigger = 5;
  35730. ActionManager._OnPickUpTrigger = 6;
  35731. ActionManager._OnLongPressTrigger = 7;
  35732. ActionManager._OnPointerOverTrigger = 8;
  35733. ActionManager._OnPointerOutTrigger = 9;
  35734. ActionManager._OnEveryFrameTrigger = 10;
  35735. ActionManager._OnIntersectionEnterTrigger = 11;
  35736. ActionManager._OnIntersectionExitTrigger = 12;
  35737. ActionManager._OnKeyDownTrigger = 13;
  35738. ActionManager._OnKeyUpTrigger = 14;
  35739. ActionManager._OnPickOutTrigger = 15;
  35740. ActionManager.DragMovementThreshold = 10; // in pixels
  35741. ActionManager.LongPressDelay = 500; // in milliseconds
  35742. BABYLON.ActionManager = ActionManager;
  35743. })(BABYLON || (BABYLON = {}));
  35744. //# sourceMappingURL=babylon.actionManager.js.map
  35745. var BABYLON;
  35746. (function (BABYLON) {
  35747. var InterpolateValueAction = (function (_super) {
  35748. __extends(InterpolateValueAction, _super);
  35749. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35750. if (duration === void 0) { duration = 1000; }
  35751. var _this = _super.call(this, triggerOptions, condition) || this;
  35752. _this.propertyPath = propertyPath;
  35753. _this.value = value;
  35754. _this.duration = duration;
  35755. _this.stopOtherAnimations = stopOtherAnimations;
  35756. _this.onInterpolationDone = onInterpolationDone;
  35757. _this._target = _this._effectiveTarget = target;
  35758. return _this;
  35759. }
  35760. InterpolateValueAction.prototype._prepare = function () {
  35761. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35762. this._property = this._getProperty(this.propertyPath);
  35763. };
  35764. InterpolateValueAction.prototype.execute = function () {
  35765. var scene = this._actionManager.getScene();
  35766. var keys = [
  35767. {
  35768. frame: 0,
  35769. value: this._effectiveTarget[this._property]
  35770. }, {
  35771. frame: 100,
  35772. value: this.value
  35773. }
  35774. ];
  35775. var dataType;
  35776. if (typeof this.value === "number") {
  35777. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35778. }
  35779. else if (this.value instanceof BABYLON.Color3) {
  35780. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35781. }
  35782. else if (this.value instanceof BABYLON.Vector3) {
  35783. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35784. }
  35785. else if (this.value instanceof BABYLON.Matrix) {
  35786. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35787. }
  35788. else if (this.value instanceof BABYLON.Quaternion) {
  35789. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35790. }
  35791. else {
  35792. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35793. return;
  35794. }
  35795. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35796. animation.setKeys(keys);
  35797. if (this.stopOtherAnimations) {
  35798. scene.stopAnimation(this._effectiveTarget);
  35799. }
  35800. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35801. };
  35802. InterpolateValueAction.prototype.serialize = function (parent) {
  35803. return _super.prototype._serialize.call(this, {
  35804. name: "InterpolateValueAction",
  35805. properties: [
  35806. BABYLON.Action._GetTargetProperty(this._target),
  35807. { name: "propertyPath", value: this.propertyPath },
  35808. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35809. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35810. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35811. ]
  35812. }, parent);
  35813. };
  35814. return InterpolateValueAction;
  35815. }(BABYLON.Action));
  35816. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35817. })(BABYLON || (BABYLON = {}));
  35818. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35819. var BABYLON;
  35820. (function (BABYLON) {
  35821. var SwitchBooleanAction = (function (_super) {
  35822. __extends(SwitchBooleanAction, _super);
  35823. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35824. var _this = _super.call(this, triggerOptions, condition) || this;
  35825. _this.propertyPath = propertyPath;
  35826. _this._target = _this._effectiveTarget = target;
  35827. return _this;
  35828. }
  35829. SwitchBooleanAction.prototype._prepare = function () {
  35830. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35831. this._property = this._getProperty(this.propertyPath);
  35832. };
  35833. SwitchBooleanAction.prototype.execute = function () {
  35834. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35835. };
  35836. SwitchBooleanAction.prototype.serialize = function (parent) {
  35837. return _super.prototype._serialize.call(this, {
  35838. name: "SwitchBooleanAction",
  35839. properties: [
  35840. BABYLON.Action._GetTargetProperty(this._target),
  35841. { name: "propertyPath", value: this.propertyPath }
  35842. ]
  35843. }, parent);
  35844. };
  35845. return SwitchBooleanAction;
  35846. }(BABYLON.Action));
  35847. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35848. var SetStateAction = (function (_super) {
  35849. __extends(SetStateAction, _super);
  35850. function SetStateAction(triggerOptions, target, value, condition) {
  35851. var _this = _super.call(this, triggerOptions, condition) || this;
  35852. _this.value = value;
  35853. _this._target = target;
  35854. return _this;
  35855. }
  35856. SetStateAction.prototype.execute = function () {
  35857. this._target.state = this.value;
  35858. };
  35859. SetStateAction.prototype.serialize = function (parent) {
  35860. return _super.prototype._serialize.call(this, {
  35861. name: "SetStateAction",
  35862. properties: [
  35863. BABYLON.Action._GetTargetProperty(this._target),
  35864. { name: "value", value: this.value }
  35865. ]
  35866. }, parent);
  35867. };
  35868. return SetStateAction;
  35869. }(BABYLON.Action));
  35870. BABYLON.SetStateAction = SetStateAction;
  35871. var SetValueAction = (function (_super) {
  35872. __extends(SetValueAction, _super);
  35873. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35874. var _this = _super.call(this, triggerOptions, condition) || this;
  35875. _this.propertyPath = propertyPath;
  35876. _this.value = value;
  35877. _this._target = _this._effectiveTarget = target;
  35878. return _this;
  35879. }
  35880. SetValueAction.prototype._prepare = function () {
  35881. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35882. this._property = this._getProperty(this.propertyPath);
  35883. };
  35884. SetValueAction.prototype.execute = function () {
  35885. this._effectiveTarget[this._property] = this.value;
  35886. if (this._target.markAsDirty) {
  35887. this._target.markAsDirty(this._property);
  35888. }
  35889. };
  35890. SetValueAction.prototype.serialize = function (parent) {
  35891. return _super.prototype._serialize.call(this, {
  35892. name: "SetValueAction",
  35893. properties: [
  35894. BABYLON.Action._GetTargetProperty(this._target),
  35895. { name: "propertyPath", value: this.propertyPath },
  35896. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35897. ]
  35898. }, parent);
  35899. };
  35900. return SetValueAction;
  35901. }(BABYLON.Action));
  35902. BABYLON.SetValueAction = SetValueAction;
  35903. var IncrementValueAction = (function (_super) {
  35904. __extends(IncrementValueAction, _super);
  35905. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35906. var _this = _super.call(this, triggerOptions, condition) || this;
  35907. _this.propertyPath = propertyPath;
  35908. _this.value = value;
  35909. _this._target = _this._effectiveTarget = target;
  35910. return _this;
  35911. }
  35912. IncrementValueAction.prototype._prepare = function () {
  35913. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35914. this._property = this._getProperty(this.propertyPath);
  35915. if (typeof this._effectiveTarget[this._property] !== "number") {
  35916. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35917. }
  35918. };
  35919. IncrementValueAction.prototype.execute = function () {
  35920. this._effectiveTarget[this._property] += this.value;
  35921. if (this._target.markAsDirty) {
  35922. this._target.markAsDirty(this._property);
  35923. }
  35924. };
  35925. IncrementValueAction.prototype.serialize = function (parent) {
  35926. return _super.prototype._serialize.call(this, {
  35927. name: "IncrementValueAction",
  35928. properties: [
  35929. BABYLON.Action._GetTargetProperty(this._target),
  35930. { name: "propertyPath", value: this.propertyPath },
  35931. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35932. ]
  35933. }, parent);
  35934. };
  35935. return IncrementValueAction;
  35936. }(BABYLON.Action));
  35937. BABYLON.IncrementValueAction = IncrementValueAction;
  35938. var PlayAnimationAction = (function (_super) {
  35939. __extends(PlayAnimationAction, _super);
  35940. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35941. var _this = _super.call(this, triggerOptions, condition) || this;
  35942. _this.from = from;
  35943. _this.to = to;
  35944. _this.loop = loop;
  35945. _this._target = target;
  35946. return _this;
  35947. }
  35948. PlayAnimationAction.prototype._prepare = function () {
  35949. };
  35950. PlayAnimationAction.prototype.execute = function () {
  35951. var scene = this._actionManager.getScene();
  35952. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35953. };
  35954. PlayAnimationAction.prototype.serialize = function (parent) {
  35955. return _super.prototype._serialize.call(this, {
  35956. name: "PlayAnimationAction",
  35957. properties: [
  35958. BABYLON.Action._GetTargetProperty(this._target),
  35959. { name: "from", value: String(this.from) },
  35960. { name: "to", value: String(this.to) },
  35961. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35962. ]
  35963. }, parent);
  35964. };
  35965. return PlayAnimationAction;
  35966. }(BABYLON.Action));
  35967. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35968. var StopAnimationAction = (function (_super) {
  35969. __extends(StopAnimationAction, _super);
  35970. function StopAnimationAction(triggerOptions, target, condition) {
  35971. var _this = _super.call(this, triggerOptions, condition) || this;
  35972. _this._target = target;
  35973. return _this;
  35974. }
  35975. StopAnimationAction.prototype._prepare = function () {
  35976. };
  35977. StopAnimationAction.prototype.execute = function () {
  35978. var scene = this._actionManager.getScene();
  35979. scene.stopAnimation(this._target);
  35980. };
  35981. StopAnimationAction.prototype.serialize = function (parent) {
  35982. return _super.prototype._serialize.call(this, {
  35983. name: "StopAnimationAction",
  35984. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35985. }, parent);
  35986. };
  35987. return StopAnimationAction;
  35988. }(BABYLON.Action));
  35989. BABYLON.StopAnimationAction = StopAnimationAction;
  35990. var DoNothingAction = (function (_super) {
  35991. __extends(DoNothingAction, _super);
  35992. function DoNothingAction(triggerOptions, condition) {
  35993. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35994. return _super.call(this, triggerOptions, condition) || this;
  35995. }
  35996. DoNothingAction.prototype.execute = function () {
  35997. };
  35998. DoNothingAction.prototype.serialize = function (parent) {
  35999. return _super.prototype._serialize.call(this, {
  36000. name: "DoNothingAction",
  36001. properties: []
  36002. }, parent);
  36003. };
  36004. return DoNothingAction;
  36005. }(BABYLON.Action));
  36006. BABYLON.DoNothingAction = DoNothingAction;
  36007. var CombineAction = (function (_super) {
  36008. __extends(CombineAction, _super);
  36009. function CombineAction(triggerOptions, children, condition) {
  36010. var _this = _super.call(this, triggerOptions, condition) || this;
  36011. _this.children = children;
  36012. return _this;
  36013. }
  36014. CombineAction.prototype._prepare = function () {
  36015. for (var index = 0; index < this.children.length; index++) {
  36016. this.children[index]._actionManager = this._actionManager;
  36017. this.children[index]._prepare();
  36018. }
  36019. };
  36020. CombineAction.prototype.execute = function (evt) {
  36021. for (var index = 0; index < this.children.length; index++) {
  36022. this.children[index].execute(evt);
  36023. }
  36024. };
  36025. CombineAction.prototype.serialize = function (parent) {
  36026. var serializationObject = _super.prototype._serialize.call(this, {
  36027. name: "CombineAction",
  36028. properties: [],
  36029. combine: []
  36030. }, parent);
  36031. for (var i = 0; i < this.children.length; i++) {
  36032. serializationObject.combine.push(this.children[i].serialize(null));
  36033. }
  36034. return serializationObject;
  36035. };
  36036. return CombineAction;
  36037. }(BABYLON.Action));
  36038. BABYLON.CombineAction = CombineAction;
  36039. var ExecuteCodeAction = (function (_super) {
  36040. __extends(ExecuteCodeAction, _super);
  36041. function ExecuteCodeAction(triggerOptions, func, condition) {
  36042. var _this = _super.call(this, triggerOptions, condition) || this;
  36043. _this.func = func;
  36044. return _this;
  36045. }
  36046. ExecuteCodeAction.prototype.execute = function (evt) {
  36047. this.func(evt);
  36048. };
  36049. return ExecuteCodeAction;
  36050. }(BABYLON.Action));
  36051. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36052. var SetParentAction = (function (_super) {
  36053. __extends(SetParentAction, _super);
  36054. function SetParentAction(triggerOptions, target, parent, condition) {
  36055. var _this = _super.call(this, triggerOptions, condition) || this;
  36056. _this._target = target;
  36057. _this._parent = parent;
  36058. return _this;
  36059. }
  36060. SetParentAction.prototype._prepare = function () {
  36061. };
  36062. SetParentAction.prototype.execute = function () {
  36063. if (this._target.parent === this._parent) {
  36064. return;
  36065. }
  36066. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36067. invertParentWorldMatrix.invert();
  36068. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36069. this._target.parent = this._parent;
  36070. };
  36071. SetParentAction.prototype.serialize = function (parent) {
  36072. return _super.prototype._serialize.call(this, {
  36073. name: "SetParentAction",
  36074. properties: [
  36075. BABYLON.Action._GetTargetProperty(this._target),
  36076. BABYLON.Action._GetTargetProperty(this._parent),
  36077. ]
  36078. }, parent);
  36079. };
  36080. return SetParentAction;
  36081. }(BABYLON.Action));
  36082. BABYLON.SetParentAction = SetParentAction;
  36083. var PlaySoundAction = (function (_super) {
  36084. __extends(PlaySoundAction, _super);
  36085. function PlaySoundAction(triggerOptions, sound, condition) {
  36086. var _this = _super.call(this, triggerOptions, condition) || this;
  36087. _this._sound = sound;
  36088. return _this;
  36089. }
  36090. PlaySoundAction.prototype._prepare = function () {
  36091. };
  36092. PlaySoundAction.prototype.execute = function () {
  36093. if (this._sound !== undefined)
  36094. this._sound.play();
  36095. };
  36096. PlaySoundAction.prototype.serialize = function (parent) {
  36097. return _super.prototype._serialize.call(this, {
  36098. name: "PlaySoundAction",
  36099. properties: [{ name: "sound", value: this._sound.name }]
  36100. }, parent);
  36101. };
  36102. return PlaySoundAction;
  36103. }(BABYLON.Action));
  36104. BABYLON.PlaySoundAction = PlaySoundAction;
  36105. var StopSoundAction = (function (_super) {
  36106. __extends(StopSoundAction, _super);
  36107. function StopSoundAction(triggerOptions, sound, condition) {
  36108. var _this = _super.call(this, triggerOptions, condition) || this;
  36109. _this._sound = sound;
  36110. return _this;
  36111. }
  36112. StopSoundAction.prototype._prepare = function () {
  36113. };
  36114. StopSoundAction.prototype.execute = function () {
  36115. if (this._sound !== undefined)
  36116. this._sound.stop();
  36117. };
  36118. StopSoundAction.prototype.serialize = function (parent) {
  36119. return _super.prototype._serialize.call(this, {
  36120. name: "StopSoundAction",
  36121. properties: [{ name: "sound", value: this._sound.name }]
  36122. }, parent);
  36123. };
  36124. return StopSoundAction;
  36125. }(BABYLON.Action));
  36126. BABYLON.StopSoundAction = StopSoundAction;
  36127. })(BABYLON || (BABYLON = {}));
  36128. //# sourceMappingURL=babylon.directActions.js.map
  36129. var BABYLON;
  36130. (function (BABYLON) {
  36131. var Geometry = (function () {
  36132. function Geometry(id, scene, vertexData, updatable, mesh) {
  36133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36134. this._totalVertices = 0;
  36135. this._isDisposed = false;
  36136. this.id = id;
  36137. this._engine = scene.getEngine();
  36138. this._meshes = [];
  36139. this._scene = scene;
  36140. //Init vertex buffer cache
  36141. this._vertexBuffers = {};
  36142. this._indices = [];
  36143. // vertexData
  36144. if (vertexData) {
  36145. this.setAllVerticesData(vertexData, updatable);
  36146. }
  36147. else {
  36148. this._totalVertices = 0;
  36149. this._indices = [];
  36150. }
  36151. // applyToMesh
  36152. if (mesh) {
  36153. if (mesh instanceof BABYLON.LinesMesh) {
  36154. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36155. this.updateExtend();
  36156. }
  36157. this.applyToMesh(mesh);
  36158. mesh.computeWorldMatrix(true);
  36159. }
  36160. }
  36161. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36162. /**
  36163. * 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
  36164. * @returns The Bias Vector
  36165. */
  36166. get: function () {
  36167. return this._boundingBias;
  36168. },
  36169. set: function (value) {
  36170. if (this._boundingBias && this._boundingBias.equals(value)) {
  36171. return;
  36172. }
  36173. this._boundingBias = value.clone();
  36174. this.updateBoundingInfo(true, null);
  36175. },
  36176. enumerable: true,
  36177. configurable: true
  36178. });
  36179. Object.defineProperty(Geometry.prototype, "extend", {
  36180. get: function () {
  36181. return this._extend;
  36182. },
  36183. enumerable: true,
  36184. configurable: true
  36185. });
  36186. Geometry.prototype.getScene = function () {
  36187. return this._scene;
  36188. };
  36189. Geometry.prototype.getEngine = function () {
  36190. return this._engine;
  36191. };
  36192. Geometry.prototype.isReady = function () {
  36193. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36194. };
  36195. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36196. get: function () {
  36197. for (var index = 0; index < this._meshes.length; index++) {
  36198. if (!this._meshes[index].doNotSerialize) {
  36199. return false;
  36200. }
  36201. }
  36202. return true;
  36203. },
  36204. enumerable: true,
  36205. configurable: true
  36206. });
  36207. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36208. vertexData.applyToGeometry(this, updatable);
  36209. this.notifyUpdate();
  36210. };
  36211. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36212. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36213. this.setVerticesBuffer(buffer);
  36214. };
  36215. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36216. var kind = buffer.getKind();
  36217. if (this._vertexBuffers[kind]) {
  36218. this._vertexBuffers[kind].dispose();
  36219. }
  36220. this._vertexBuffers[kind] = buffer;
  36221. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36222. var data = buffer.getData();
  36223. var stride = buffer.getStrideSize();
  36224. this._totalVertices = data.length / stride;
  36225. this.updateExtend(data, stride);
  36226. var meshes = this._meshes;
  36227. var numOfMeshes = meshes.length;
  36228. for (var index = 0; index < numOfMeshes; index++) {
  36229. var mesh = meshes[index];
  36230. mesh._resetPointsArrayCache();
  36231. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36232. mesh._createGlobalSubMesh();
  36233. mesh.computeWorldMatrix(true);
  36234. }
  36235. }
  36236. this.notifyUpdate(kind);
  36237. };
  36238. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36239. var vertexBuffer = this.getVertexBuffer(kind);
  36240. if (!vertexBuffer) {
  36241. return;
  36242. }
  36243. vertexBuffer.updateDirectly(data, offset);
  36244. this.notifyUpdate(kind);
  36245. };
  36246. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36247. var vertexBuffer = this.getVertexBuffer(kind);
  36248. if (!vertexBuffer) {
  36249. return;
  36250. }
  36251. vertexBuffer.update(data);
  36252. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36253. var stride = vertexBuffer.getStrideSize();
  36254. this._totalVertices = data.length / stride;
  36255. this.updateBoundingInfo(updateExtends, data);
  36256. }
  36257. this.notifyUpdate(kind);
  36258. };
  36259. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36260. if (updateExtends) {
  36261. this.updateExtend(data);
  36262. }
  36263. var meshes = this._meshes;
  36264. var numOfMeshes = meshes.length;
  36265. for (var index = 0; index < numOfMeshes; index++) {
  36266. var mesh = meshes[index];
  36267. mesh._resetPointsArrayCache();
  36268. if (updateExtends) {
  36269. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36270. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36271. var subMesh = mesh.subMeshes[subIndex];
  36272. subMesh.refreshBoundingInfo();
  36273. }
  36274. }
  36275. }
  36276. };
  36277. Geometry.prototype.getTotalVertices = function () {
  36278. if (!this.isReady()) {
  36279. return 0;
  36280. }
  36281. return this._totalVertices;
  36282. };
  36283. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36284. var vertexBuffer = this.getVertexBuffer(kind);
  36285. if (!vertexBuffer) {
  36286. return null;
  36287. }
  36288. var orig = vertexBuffer.getData();
  36289. if (!copyWhenShared || this._meshes.length === 1) {
  36290. return orig;
  36291. }
  36292. else {
  36293. var len = orig.length;
  36294. var copy = [];
  36295. for (var i = 0; i < len; i++) {
  36296. copy.push(orig[i]);
  36297. }
  36298. return copy;
  36299. }
  36300. };
  36301. Geometry.prototype.getVertexBuffer = function (kind) {
  36302. if (!this.isReady()) {
  36303. return null;
  36304. }
  36305. return this._vertexBuffers[kind];
  36306. };
  36307. Geometry.prototype.getVertexBuffers = function () {
  36308. if (!this.isReady()) {
  36309. return null;
  36310. }
  36311. return this._vertexBuffers;
  36312. };
  36313. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36314. if (!this._vertexBuffers) {
  36315. if (this._delayInfo) {
  36316. return this._delayInfo.indexOf(kind) !== -1;
  36317. }
  36318. return false;
  36319. }
  36320. return this._vertexBuffers[kind] !== undefined;
  36321. };
  36322. Geometry.prototype.getVerticesDataKinds = function () {
  36323. var result = [];
  36324. var kind;
  36325. if (!this._vertexBuffers && this._delayInfo) {
  36326. for (kind in this._delayInfo) {
  36327. result.push(kind);
  36328. }
  36329. }
  36330. else {
  36331. for (kind in this._vertexBuffers) {
  36332. result.push(kind);
  36333. }
  36334. }
  36335. return result;
  36336. };
  36337. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36338. if (this._indexBuffer) {
  36339. this._engine._releaseBuffer(this._indexBuffer);
  36340. }
  36341. this._indices = indices;
  36342. if (this._meshes.length !== 0 && this._indices) {
  36343. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36344. }
  36345. if (totalVertices !== undefined) {
  36346. this._totalVertices = totalVertices;
  36347. }
  36348. var meshes = this._meshes;
  36349. var numOfMeshes = meshes.length;
  36350. for (var index = 0; index < numOfMeshes; index++) {
  36351. meshes[index]._createGlobalSubMesh();
  36352. }
  36353. this.notifyUpdate();
  36354. };
  36355. Geometry.prototype.getTotalIndices = function () {
  36356. if (!this.isReady()) {
  36357. return 0;
  36358. }
  36359. return this._indices.length;
  36360. };
  36361. Geometry.prototype.getIndices = function (copyWhenShared) {
  36362. if (!this.isReady()) {
  36363. return null;
  36364. }
  36365. var orig = this._indices;
  36366. if (!copyWhenShared || this._meshes.length === 1) {
  36367. return orig;
  36368. }
  36369. else {
  36370. var len = orig.length;
  36371. var copy = [];
  36372. for (var i = 0; i < len; i++) {
  36373. copy.push(orig[i]);
  36374. }
  36375. return copy;
  36376. }
  36377. };
  36378. Geometry.prototype.getIndexBuffer = function () {
  36379. if (!this.isReady()) {
  36380. return null;
  36381. }
  36382. return this._indexBuffer;
  36383. };
  36384. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36385. var meshes = this._meshes;
  36386. var index = meshes.indexOf(mesh);
  36387. if (index === -1) {
  36388. return;
  36389. }
  36390. for (var kind in this._vertexBuffers) {
  36391. this._vertexBuffers[kind].dispose();
  36392. }
  36393. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36394. this._indexBuffer = null;
  36395. }
  36396. meshes.splice(index, 1);
  36397. mesh._geometry = null;
  36398. if (meshes.length === 0 && shouldDispose) {
  36399. this.dispose();
  36400. }
  36401. };
  36402. Geometry.prototype.applyToMesh = function (mesh) {
  36403. if (mesh._geometry === this) {
  36404. return;
  36405. }
  36406. var previousGeometry = mesh._geometry;
  36407. if (previousGeometry) {
  36408. previousGeometry.releaseForMesh(mesh);
  36409. }
  36410. var meshes = this._meshes;
  36411. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36412. mesh._geometry = this;
  36413. this._scene.pushGeometry(this);
  36414. meshes.push(mesh);
  36415. if (this.isReady()) {
  36416. this._applyToMesh(mesh);
  36417. }
  36418. else {
  36419. mesh._boundingInfo = this._boundingInfo;
  36420. }
  36421. };
  36422. Geometry.prototype.updateExtend = function (data, stride) {
  36423. if (data === void 0) { data = null; }
  36424. if (!data) {
  36425. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36426. }
  36427. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36428. };
  36429. Geometry.prototype._applyToMesh = function (mesh) {
  36430. var numOfMeshes = this._meshes.length;
  36431. // vertexBuffers
  36432. for (var kind in this._vertexBuffers) {
  36433. if (numOfMeshes === 1) {
  36434. this._vertexBuffers[kind].create();
  36435. }
  36436. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36437. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36438. mesh._resetPointsArrayCache();
  36439. if (!this._extend) {
  36440. this.updateExtend(this._vertexBuffers[kind].getData());
  36441. }
  36442. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36443. mesh._createGlobalSubMesh();
  36444. //bounding info was just created again, world matrix should be applied again.
  36445. mesh._updateBoundingInfo();
  36446. }
  36447. }
  36448. // indexBuffer
  36449. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36450. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36451. }
  36452. if (this._indexBuffer) {
  36453. this._indexBuffer.references = numOfMeshes;
  36454. }
  36455. };
  36456. Geometry.prototype.notifyUpdate = function (kind) {
  36457. if (this.onGeometryUpdated) {
  36458. this.onGeometryUpdated(this, kind);
  36459. }
  36460. };
  36461. Geometry.prototype.load = function (scene, onLoaded) {
  36462. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36463. return;
  36464. }
  36465. if (this.isReady()) {
  36466. if (onLoaded) {
  36467. onLoaded();
  36468. }
  36469. return;
  36470. }
  36471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36472. this._queueLoad(scene, onLoaded);
  36473. };
  36474. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36475. var _this = this;
  36476. scene._addPendingData(this);
  36477. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36478. _this._delayLoadingFunction(JSON.parse(data), _this);
  36479. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36480. _this._delayInfo = [];
  36481. scene._removePendingData(_this);
  36482. var meshes = _this._meshes;
  36483. var numOfMeshes = meshes.length;
  36484. for (var index = 0; index < numOfMeshes; index++) {
  36485. _this._applyToMesh(meshes[index]);
  36486. }
  36487. if (onLoaded) {
  36488. onLoaded();
  36489. }
  36490. }, function () { }, scene.database);
  36491. };
  36492. /**
  36493. * Invert the geometry to move from a right handed system to a left handed one.
  36494. */
  36495. Geometry.prototype.toLeftHanded = function () {
  36496. // Flip faces
  36497. var tIndices = this.getIndices(false);
  36498. if (tIndices != null && tIndices.length > 0) {
  36499. for (var i = 0; i < tIndices.length; i += 3) {
  36500. var tTemp = tIndices[i + 0];
  36501. tIndices[i + 0] = tIndices[i + 2];
  36502. tIndices[i + 2] = tTemp;
  36503. }
  36504. this.setIndices(tIndices);
  36505. }
  36506. // Negate position.z
  36507. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36508. if (tPositions != null && tPositions.length > 0) {
  36509. for (var i = 0; i < tPositions.length; i += 3) {
  36510. tPositions[i + 2] = -tPositions[i + 2];
  36511. }
  36512. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36513. }
  36514. // Negate normal.z
  36515. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36516. if (tNormals != null && tNormals.length > 0) {
  36517. for (var i = 0; i < tNormals.length; i += 3) {
  36518. tNormals[i + 2] = -tNormals[i + 2];
  36519. }
  36520. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36521. }
  36522. };
  36523. Geometry.prototype.isDisposed = function () {
  36524. return this._isDisposed;
  36525. };
  36526. Geometry.prototype.dispose = function () {
  36527. var meshes = this._meshes;
  36528. var numOfMeshes = meshes.length;
  36529. var index;
  36530. for (index = 0; index < numOfMeshes; index++) {
  36531. this.releaseForMesh(meshes[index]);
  36532. }
  36533. this._meshes = [];
  36534. for (var kind in this._vertexBuffers) {
  36535. this._vertexBuffers[kind].dispose();
  36536. }
  36537. this._vertexBuffers = {};
  36538. this._totalVertices = 0;
  36539. if (this._indexBuffer) {
  36540. this._engine._releaseBuffer(this._indexBuffer);
  36541. }
  36542. this._indexBuffer = null;
  36543. this._indices = [];
  36544. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36545. this.delayLoadingFile = null;
  36546. this._delayLoadingFunction = null;
  36547. this._delayInfo = [];
  36548. this._boundingInfo = null;
  36549. this._scene.removeGeometry(this);
  36550. this._isDisposed = true;
  36551. };
  36552. Geometry.prototype.copy = function (id) {
  36553. var vertexData = new BABYLON.VertexData();
  36554. vertexData.indices = [];
  36555. var indices = this.getIndices();
  36556. for (var index = 0; index < indices.length; index++) {
  36557. vertexData.indices.push(indices[index]);
  36558. }
  36559. var updatable = false;
  36560. var stopChecking = false;
  36561. var kind;
  36562. for (kind in this._vertexBuffers) {
  36563. // using slice() to make a copy of the array and not just reference it
  36564. var data = this.getVerticesData(kind);
  36565. if (data instanceof Float32Array) {
  36566. vertexData.set(new Float32Array(data), kind);
  36567. }
  36568. else {
  36569. vertexData.set(data.slice(0), kind);
  36570. }
  36571. if (!stopChecking) {
  36572. updatable = this.getVertexBuffer(kind).isUpdatable();
  36573. stopChecking = !updatable;
  36574. }
  36575. }
  36576. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36577. geometry.delayLoadState = this.delayLoadState;
  36578. geometry.delayLoadingFile = this.delayLoadingFile;
  36579. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36580. for (kind in this._delayInfo) {
  36581. geometry._delayInfo = geometry._delayInfo || [];
  36582. geometry._delayInfo.push(kind);
  36583. }
  36584. // Bounding info
  36585. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36586. return geometry;
  36587. };
  36588. Geometry.prototype.serialize = function () {
  36589. var serializationObject = {};
  36590. serializationObject.id = this.id;
  36591. if (BABYLON.Tags.HasTags(this)) {
  36592. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36593. }
  36594. return serializationObject;
  36595. };
  36596. Geometry.prototype.serializeVerticeData = function () {
  36597. var serializationObject = this.serialize();
  36598. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36599. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36600. }
  36601. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36602. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36603. }
  36604. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36605. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36606. }
  36607. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36608. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36609. }
  36610. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36611. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36612. }
  36613. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36614. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36615. }
  36616. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36617. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36618. }
  36619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36620. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36621. }
  36622. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36623. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36624. }
  36625. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36626. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36627. serializationObject.matricesIndices._isExpanded = true;
  36628. }
  36629. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36630. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36631. }
  36632. serializationObject.indices = this.getIndices();
  36633. return serializationObject;
  36634. };
  36635. // Statics
  36636. Geometry.ExtractFromMesh = function (mesh, id) {
  36637. var geometry = mesh._geometry;
  36638. if (!geometry) {
  36639. return null;
  36640. }
  36641. return geometry.copy(id);
  36642. };
  36643. /**
  36644. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36645. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36646. * Be aware Math.random() could cause collisions, but:
  36647. * "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"
  36648. */
  36649. Geometry.RandomId = function () {
  36650. return BABYLON.Tools.RandomId();
  36651. };
  36652. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36653. var scene = mesh.getScene();
  36654. // Geometry
  36655. var geometryId = parsedGeometry.geometryId;
  36656. if (geometryId) {
  36657. var geometry = scene.getGeometryByID(geometryId);
  36658. if (geometry) {
  36659. geometry.applyToMesh(mesh);
  36660. }
  36661. }
  36662. else if (parsedGeometry instanceof ArrayBuffer) {
  36663. var binaryInfo = mesh._binaryInfo;
  36664. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36665. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36666. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36667. }
  36668. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36669. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36670. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36671. }
  36672. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36673. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36674. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36675. }
  36676. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36677. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36678. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36679. }
  36680. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36681. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36682. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36683. }
  36684. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36685. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36686. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36687. }
  36688. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36689. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36690. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36691. }
  36692. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36693. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36694. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36695. }
  36696. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36697. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36698. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36699. }
  36700. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36701. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36702. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36703. }
  36704. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36705. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36707. }
  36708. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36709. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36710. mesh.setIndices(indicesData);
  36711. }
  36712. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36713. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36714. mesh.subMeshes = [];
  36715. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36716. var materialIndex = subMeshesData[(i * 5) + 0];
  36717. var verticesStart = subMeshesData[(i * 5) + 1];
  36718. var verticesCount = subMeshesData[(i * 5) + 2];
  36719. var indexStart = subMeshesData[(i * 5) + 3];
  36720. var indexCount = subMeshesData[(i * 5) + 4];
  36721. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36722. }
  36723. }
  36724. }
  36725. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36726. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36727. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36728. if (parsedGeometry.uvs) {
  36729. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36730. }
  36731. if (parsedGeometry.uvs2) {
  36732. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36733. }
  36734. if (parsedGeometry.uvs3) {
  36735. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36736. }
  36737. if (parsedGeometry.uvs4) {
  36738. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36739. }
  36740. if (parsedGeometry.uvs5) {
  36741. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36742. }
  36743. if (parsedGeometry.uvs6) {
  36744. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36745. }
  36746. if (parsedGeometry.colors) {
  36747. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36748. }
  36749. if (parsedGeometry.matricesIndices) {
  36750. if (!parsedGeometry.matricesIndices._isExpanded) {
  36751. var floatIndices = [];
  36752. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36753. var matricesIndex = parsedGeometry.matricesIndices[i];
  36754. floatIndices.push(matricesIndex & 0x000000FF);
  36755. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36756. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36757. floatIndices.push(matricesIndex >> 24);
  36758. }
  36759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36760. }
  36761. else {
  36762. delete parsedGeometry.matricesIndices._isExpanded;
  36763. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36764. }
  36765. }
  36766. if (parsedGeometry.matricesIndicesExtra) {
  36767. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36768. var floatIndices = [];
  36769. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36770. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36771. floatIndices.push(matricesIndex & 0x000000FF);
  36772. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36773. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36774. floatIndices.push(matricesIndex >> 24);
  36775. }
  36776. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36777. }
  36778. else {
  36779. delete parsedGeometry.matricesIndices._isExpanded;
  36780. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36781. }
  36782. }
  36783. if (parsedGeometry.matricesWeights) {
  36784. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36785. }
  36786. if (parsedGeometry.matricesWeightsExtra) {
  36787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36788. }
  36789. mesh.setIndices(parsedGeometry.indices);
  36790. }
  36791. // SubMeshes
  36792. if (parsedGeometry.subMeshes) {
  36793. mesh.subMeshes = [];
  36794. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36795. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36796. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36797. }
  36798. }
  36799. // Flat shading
  36800. if (mesh._shouldGenerateFlatShading) {
  36801. mesh.convertToFlatShadedMesh();
  36802. delete mesh._shouldGenerateFlatShading;
  36803. }
  36804. // Update
  36805. mesh.computeWorldMatrix(true);
  36806. // Octree
  36807. if (scene['_selectionOctree']) {
  36808. scene['_selectionOctree'].addMesh(mesh);
  36809. }
  36810. };
  36811. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36812. if (scene.getGeometryByID(parsedVertexData.id)) {
  36813. return null; // null since geometry could be something else than a box...
  36814. }
  36815. var geometry = new Geometry(parsedVertexData.id, scene);
  36816. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36817. if (parsedVertexData.delayLoadingFile) {
  36818. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36819. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36820. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36821. geometry._delayInfo = [];
  36822. if (parsedVertexData.hasUVs) {
  36823. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36824. }
  36825. if (parsedVertexData.hasUVs2) {
  36826. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36827. }
  36828. if (parsedVertexData.hasUVs3) {
  36829. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36830. }
  36831. if (parsedVertexData.hasUVs4) {
  36832. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36833. }
  36834. if (parsedVertexData.hasUVs5) {
  36835. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36836. }
  36837. if (parsedVertexData.hasUVs6) {
  36838. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36839. }
  36840. if (parsedVertexData.hasColors) {
  36841. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36842. }
  36843. if (parsedVertexData.hasMatricesIndices) {
  36844. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36845. }
  36846. if (parsedVertexData.hasMatricesWeights) {
  36847. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36848. }
  36849. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36850. }
  36851. else {
  36852. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36853. }
  36854. scene.pushGeometry(geometry, true);
  36855. return geometry;
  36856. };
  36857. return Geometry;
  36858. }());
  36859. BABYLON.Geometry = Geometry;
  36860. /////// Primitives //////////////////////////////////////////////
  36861. (function (Geometry) {
  36862. var Primitives;
  36863. (function (Primitives) {
  36864. /// Abstract class
  36865. var _Primitive = (function (_super) {
  36866. __extends(_Primitive, _super);
  36867. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36868. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  36869. _this._canBeRegenerated = _canBeRegenerated;
  36870. _this._beingRegenerated = true;
  36871. _this.regenerate();
  36872. _this._beingRegenerated = false;
  36873. return _this;
  36874. }
  36875. _Primitive.prototype.canBeRegenerated = function () {
  36876. return this._canBeRegenerated;
  36877. };
  36878. _Primitive.prototype.regenerate = function () {
  36879. if (!this._canBeRegenerated) {
  36880. return;
  36881. }
  36882. this._beingRegenerated = true;
  36883. this.setAllVerticesData(this._regenerateVertexData(), false);
  36884. this._beingRegenerated = false;
  36885. };
  36886. _Primitive.prototype.asNewGeometry = function (id) {
  36887. return _super.prototype.copy.call(this, id);
  36888. };
  36889. // overrides
  36890. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36891. if (!this._beingRegenerated) {
  36892. return;
  36893. }
  36894. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36895. };
  36896. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36897. if (!this._beingRegenerated) {
  36898. return;
  36899. }
  36900. _super.prototype.setVerticesData.call(this, kind, data, false);
  36901. };
  36902. // to override
  36903. // protected
  36904. _Primitive.prototype._regenerateVertexData = function () {
  36905. throw new Error("Abstract method");
  36906. };
  36907. _Primitive.prototype.copy = function (id) {
  36908. throw new Error("Must be overriden in sub-classes.");
  36909. };
  36910. _Primitive.prototype.serialize = function () {
  36911. var serializationObject = _super.prototype.serialize.call(this);
  36912. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36913. return serializationObject;
  36914. };
  36915. return _Primitive;
  36916. }(Geometry));
  36917. Primitives._Primitive = _Primitive;
  36918. var Ribbon = (function (_super) {
  36919. __extends(Ribbon, _super);
  36920. // Members
  36921. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36922. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36923. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36924. _this.pathArray = pathArray;
  36925. _this.closeArray = closeArray;
  36926. _this.closePath = closePath;
  36927. _this.offset = offset;
  36928. _this.side = side;
  36929. return _this;
  36930. }
  36931. Ribbon.prototype._regenerateVertexData = function () {
  36932. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36933. };
  36934. Ribbon.prototype.copy = function (id) {
  36935. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36936. };
  36937. return Ribbon;
  36938. }(_Primitive));
  36939. Primitives.Ribbon = Ribbon;
  36940. var Box = (function (_super) {
  36941. __extends(Box, _super);
  36942. // Members
  36943. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36944. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36945. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36946. _this.size = size;
  36947. _this.side = side;
  36948. return _this;
  36949. }
  36950. Box.prototype._regenerateVertexData = function () {
  36951. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36952. };
  36953. Box.prototype.copy = function (id) {
  36954. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36955. };
  36956. Box.prototype.serialize = function () {
  36957. var serializationObject = _super.prototype.serialize.call(this);
  36958. serializationObject.size = this.size;
  36959. return serializationObject;
  36960. };
  36961. Box.Parse = function (parsedBox, scene) {
  36962. if (scene.getGeometryByID(parsedBox.id)) {
  36963. return null; // null since geometry could be something else than a box...
  36964. }
  36965. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36966. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36967. scene.pushGeometry(box, true);
  36968. return box;
  36969. };
  36970. return Box;
  36971. }(_Primitive));
  36972. Primitives.Box = Box;
  36973. var Sphere = (function (_super) {
  36974. __extends(Sphere, _super);
  36975. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36976. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36977. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36978. _this.segments = segments;
  36979. _this.diameter = diameter;
  36980. _this.side = side;
  36981. return _this;
  36982. }
  36983. Sphere.prototype._regenerateVertexData = function () {
  36984. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36985. };
  36986. Sphere.prototype.copy = function (id) {
  36987. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36988. };
  36989. Sphere.prototype.serialize = function () {
  36990. var serializationObject = _super.prototype.serialize.call(this);
  36991. serializationObject.segments = this.segments;
  36992. serializationObject.diameter = this.diameter;
  36993. return serializationObject;
  36994. };
  36995. Sphere.Parse = function (parsedSphere, scene) {
  36996. if (scene.getGeometryByID(parsedSphere.id)) {
  36997. return null; // null since geometry could be something else than a sphere...
  36998. }
  36999. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37000. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37001. scene.pushGeometry(sphere, true);
  37002. return sphere;
  37003. };
  37004. return Sphere;
  37005. }(_Primitive));
  37006. Primitives.Sphere = Sphere;
  37007. var Disc = (function (_super) {
  37008. __extends(Disc, _super);
  37009. // Members
  37010. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37011. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37012. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37013. _this.radius = radius;
  37014. _this.tessellation = tessellation;
  37015. _this.side = side;
  37016. return _this;
  37017. }
  37018. Disc.prototype._regenerateVertexData = function () {
  37019. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37020. };
  37021. Disc.prototype.copy = function (id) {
  37022. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37023. };
  37024. return Disc;
  37025. }(_Primitive));
  37026. Primitives.Disc = Disc;
  37027. var Cylinder = (function (_super) {
  37028. __extends(Cylinder, _super);
  37029. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37030. if (subdivisions === void 0) { subdivisions = 1; }
  37031. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37032. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37033. _this.height = height;
  37034. _this.diameterTop = diameterTop;
  37035. _this.diameterBottom = diameterBottom;
  37036. _this.tessellation = tessellation;
  37037. _this.subdivisions = subdivisions;
  37038. _this.side = side;
  37039. return _this;
  37040. }
  37041. Cylinder.prototype._regenerateVertexData = function () {
  37042. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37043. };
  37044. Cylinder.prototype.copy = function (id) {
  37045. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37046. };
  37047. Cylinder.prototype.serialize = function () {
  37048. var serializationObject = _super.prototype.serialize.call(this);
  37049. serializationObject.height = this.height;
  37050. serializationObject.diameterTop = this.diameterTop;
  37051. serializationObject.diameterBottom = this.diameterBottom;
  37052. serializationObject.tessellation = this.tessellation;
  37053. return serializationObject;
  37054. };
  37055. Cylinder.Parse = function (parsedCylinder, scene) {
  37056. if (scene.getGeometryByID(parsedCylinder.id)) {
  37057. return null; // null since geometry could be something else than a cylinder...
  37058. }
  37059. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37060. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37061. scene.pushGeometry(cylinder, true);
  37062. return cylinder;
  37063. };
  37064. return Cylinder;
  37065. }(_Primitive));
  37066. Primitives.Cylinder = Cylinder;
  37067. var Torus = (function (_super) {
  37068. __extends(Torus, _super);
  37069. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37070. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37071. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37072. _this.diameter = diameter;
  37073. _this.thickness = thickness;
  37074. _this.tessellation = tessellation;
  37075. _this.side = side;
  37076. return _this;
  37077. }
  37078. Torus.prototype._regenerateVertexData = function () {
  37079. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37080. };
  37081. Torus.prototype.copy = function (id) {
  37082. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37083. };
  37084. Torus.prototype.serialize = function () {
  37085. var serializationObject = _super.prototype.serialize.call(this);
  37086. serializationObject.diameter = this.diameter;
  37087. serializationObject.thickness = this.thickness;
  37088. serializationObject.tessellation = this.tessellation;
  37089. return serializationObject;
  37090. };
  37091. Torus.Parse = function (parsedTorus, scene) {
  37092. if (scene.getGeometryByID(parsedTorus.id)) {
  37093. return null; // null since geometry could be something else than a torus...
  37094. }
  37095. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37096. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37097. scene.pushGeometry(torus, true);
  37098. return torus;
  37099. };
  37100. return Torus;
  37101. }(_Primitive));
  37102. Primitives.Torus = Torus;
  37103. var Ground = (function (_super) {
  37104. __extends(Ground, _super);
  37105. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37106. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37107. _this.width = width;
  37108. _this.height = height;
  37109. _this.subdivisions = subdivisions;
  37110. return _this;
  37111. }
  37112. Ground.prototype._regenerateVertexData = function () {
  37113. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37114. };
  37115. Ground.prototype.copy = function (id) {
  37116. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37117. };
  37118. Ground.prototype.serialize = function () {
  37119. var serializationObject = _super.prototype.serialize.call(this);
  37120. serializationObject.width = this.width;
  37121. serializationObject.height = this.height;
  37122. serializationObject.subdivisions = this.subdivisions;
  37123. return serializationObject;
  37124. };
  37125. Ground.Parse = function (parsedGround, scene) {
  37126. if (scene.getGeometryByID(parsedGround.id)) {
  37127. return null; // null since geometry could be something else than a ground...
  37128. }
  37129. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37130. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37131. scene.pushGeometry(ground, true);
  37132. return ground;
  37133. };
  37134. return Ground;
  37135. }(_Primitive));
  37136. Primitives.Ground = Ground;
  37137. var TiledGround = (function (_super) {
  37138. __extends(TiledGround, _super);
  37139. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37140. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37141. _this.xmin = xmin;
  37142. _this.zmin = zmin;
  37143. _this.xmax = xmax;
  37144. _this.zmax = zmax;
  37145. _this.subdivisions = subdivisions;
  37146. _this.precision = precision;
  37147. return _this;
  37148. }
  37149. TiledGround.prototype._regenerateVertexData = function () {
  37150. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37151. };
  37152. TiledGround.prototype.copy = function (id) {
  37153. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37154. };
  37155. return TiledGround;
  37156. }(_Primitive));
  37157. Primitives.TiledGround = TiledGround;
  37158. var Plane = (function (_super) {
  37159. __extends(Plane, _super);
  37160. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37161. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37162. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37163. _this.size = size;
  37164. _this.side = side;
  37165. return _this;
  37166. }
  37167. Plane.prototype._regenerateVertexData = function () {
  37168. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37169. };
  37170. Plane.prototype.copy = function (id) {
  37171. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37172. };
  37173. Plane.prototype.serialize = function () {
  37174. var serializationObject = _super.prototype.serialize.call(this);
  37175. serializationObject.size = this.size;
  37176. return serializationObject;
  37177. };
  37178. Plane.Parse = function (parsedPlane, scene) {
  37179. if (scene.getGeometryByID(parsedPlane.id)) {
  37180. return null; // null since geometry could be something else than a ground...
  37181. }
  37182. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37183. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37184. scene.pushGeometry(plane, true);
  37185. return plane;
  37186. };
  37187. return Plane;
  37188. }(_Primitive));
  37189. Primitives.Plane = Plane;
  37190. var TorusKnot = (function (_super) {
  37191. __extends(TorusKnot, _super);
  37192. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37193. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37194. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37195. _this.radius = radius;
  37196. _this.tube = tube;
  37197. _this.radialSegments = radialSegments;
  37198. _this.tubularSegments = tubularSegments;
  37199. _this.p = p;
  37200. _this.q = q;
  37201. _this.side = side;
  37202. return _this;
  37203. }
  37204. TorusKnot.prototype._regenerateVertexData = function () {
  37205. 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 });
  37206. };
  37207. TorusKnot.prototype.copy = function (id) {
  37208. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37209. };
  37210. TorusKnot.prototype.serialize = function () {
  37211. var serializationObject = _super.prototype.serialize.call(this);
  37212. serializationObject.radius = this.radius;
  37213. serializationObject.tube = this.tube;
  37214. serializationObject.radialSegments = this.radialSegments;
  37215. serializationObject.tubularSegments = this.tubularSegments;
  37216. serializationObject.p = this.p;
  37217. serializationObject.q = this.q;
  37218. return serializationObject;
  37219. };
  37220. ;
  37221. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37222. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37223. return null; // null since geometry could be something else than a ground...
  37224. }
  37225. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37226. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37227. scene.pushGeometry(torusKnot, true);
  37228. return torusKnot;
  37229. };
  37230. return TorusKnot;
  37231. }(_Primitive));
  37232. Primitives.TorusKnot = TorusKnot;
  37233. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37234. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37235. })(BABYLON || (BABYLON = {}));
  37236. //# sourceMappingURL=babylon.geometry.js.map
  37237. var BABYLON;
  37238. (function (BABYLON) {
  37239. var GroundMesh = (function (_super) {
  37240. __extends(GroundMesh, _super);
  37241. function GroundMesh(name, scene) {
  37242. var _this = _super.call(this, name, scene) || this;
  37243. _this.generateOctree = false;
  37244. _this._worldInverse = new BABYLON.Matrix();
  37245. return _this;
  37246. }
  37247. GroundMesh.prototype.getClassName = function () {
  37248. return "GroundMesh";
  37249. };
  37250. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37251. get: function () {
  37252. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37258. get: function () {
  37259. return this._subdivisionsX;
  37260. },
  37261. enumerable: true,
  37262. configurable: true
  37263. });
  37264. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37265. get: function () {
  37266. return this._subdivisionsY;
  37267. },
  37268. enumerable: true,
  37269. configurable: true
  37270. });
  37271. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37272. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37273. this._subdivisionsX = chunksCount;
  37274. this._subdivisionsY = chunksCount;
  37275. this.subdivide(chunksCount);
  37276. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37277. };
  37278. /**
  37279. * Returns a height (y) value in the Worl system :
  37280. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37281. * Returns the ground y position if (x, z) are outside the ground surface.
  37282. * Not pertinent if the ground is rotated.
  37283. */
  37284. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37285. // express x and y in the ground local system
  37286. x -= this.position.x;
  37287. z -= this.position.z;
  37288. x /= this.scaling.x;
  37289. z /= this.scaling.z;
  37290. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37291. return this.position.y;
  37292. }
  37293. if (!this._heightQuads || this._heightQuads.length == 0) {
  37294. this._initHeightQuads();
  37295. this._computeHeightQuads();
  37296. }
  37297. var facet = this._getFacetAt(x, z);
  37298. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37299. // return y in the World system
  37300. return y * this.scaling.y + this.position.y;
  37301. };
  37302. /**
  37303. * Returns a normalized vector (Vector3) orthogonal to the ground
  37304. * at the ground coordinates (x, z) expressed in the World system.
  37305. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37306. * Not pertinent if the ground is rotated.
  37307. */
  37308. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37309. var normal = new BABYLON.Vector3(0, 1, 0);
  37310. this.getNormalAtCoordinatesToRef(x, z, normal);
  37311. return normal;
  37312. };
  37313. /**
  37314. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37315. * at the ground coordinates (x, z) expressed in the World system.
  37316. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37317. * Not pertinent if the ground is rotated.
  37318. */
  37319. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37320. // express x and y in the ground local system
  37321. x -= this.position.x;
  37322. z -= this.position.z;
  37323. x /= this.scaling.x;
  37324. z /= this.scaling.z;
  37325. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37326. return;
  37327. }
  37328. if (!this._heightQuads || this._heightQuads.length == 0) {
  37329. this._initHeightQuads();
  37330. this._computeHeightQuads();
  37331. }
  37332. var facet = this._getFacetAt(x, z);
  37333. ref.x = facet.x;
  37334. ref.y = facet.y;
  37335. ref.z = facet.z;
  37336. };
  37337. /**
  37338. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37339. * if the ground has been updated.
  37340. * This can be used in the render loop
  37341. */
  37342. GroundMesh.prototype.updateCoordinateHeights = function () {
  37343. if (!this._heightQuads || this._heightQuads.length == 0) {
  37344. this._initHeightQuads();
  37345. }
  37346. this._computeHeightQuads();
  37347. };
  37348. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37349. GroundMesh.prototype._getFacetAt = function (x, z) {
  37350. // retrieve col and row from x, z coordinates in the ground local system
  37351. var subdivisionsX = this._subdivisionsX;
  37352. var subdivisionsY = this._subdivisionsY;
  37353. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37354. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37355. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37356. var facet;
  37357. if (z < quad.slope.x * x + quad.slope.y) {
  37358. facet = quad.facet1;
  37359. }
  37360. else {
  37361. facet = quad.facet2;
  37362. }
  37363. return facet;
  37364. };
  37365. // Creates and populates the heightMap array with "facet" elements :
  37366. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37367. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37368. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37369. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37370. GroundMesh.prototype._initHeightQuads = function () {
  37371. var subdivisionsX = this._subdivisionsX;
  37372. var subdivisionsY = this._subdivisionsY;
  37373. this._heightQuads = new Array();
  37374. for (var row = 0; row < subdivisionsY; row++) {
  37375. for (var col = 0; col < subdivisionsX; col++) {
  37376. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37377. this._heightQuads[row * subdivisionsX + col] = quad;
  37378. }
  37379. }
  37380. };
  37381. // Compute each quad element values and update the the heightMap array :
  37382. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37383. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37384. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37385. GroundMesh.prototype._computeHeightQuads = function () {
  37386. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37387. var v1 = BABYLON.Tmp.Vector3[3];
  37388. var v2 = BABYLON.Tmp.Vector3[2];
  37389. var v3 = BABYLON.Tmp.Vector3[1];
  37390. var v4 = BABYLON.Tmp.Vector3[0];
  37391. var v1v2 = BABYLON.Tmp.Vector3[4];
  37392. var v1v3 = BABYLON.Tmp.Vector3[5];
  37393. var v1v4 = BABYLON.Tmp.Vector3[6];
  37394. var norm1 = BABYLON.Tmp.Vector3[7];
  37395. var norm2 = BABYLON.Tmp.Vector3[8];
  37396. var i = 0;
  37397. var j = 0;
  37398. var k = 0;
  37399. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37400. var h = 0;
  37401. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37402. var d2 = 0;
  37403. var subdivisionsX = this._subdivisionsX;
  37404. var subdivisionsY = this._subdivisionsY;
  37405. for (var row = 0; row < subdivisionsY; row++) {
  37406. for (var col = 0; col < subdivisionsX; col++) {
  37407. i = col * 3;
  37408. j = row * (subdivisionsX + 1) * 3;
  37409. k = (row + 1) * (subdivisionsX + 1) * 3;
  37410. v1.x = positions[j + i];
  37411. v1.y = positions[j + i + 1];
  37412. v1.z = positions[j + i + 2];
  37413. v2.x = positions[j + i + 3];
  37414. v2.y = positions[j + i + 4];
  37415. v2.z = positions[j + i + 5];
  37416. v3.x = positions[k + i];
  37417. v3.y = positions[k + i + 1];
  37418. v3.z = positions[k + i + 2];
  37419. v4.x = positions[k + i + 3];
  37420. v4.y = positions[k + i + 4];
  37421. v4.z = positions[k + i + 5];
  37422. // 2D slope V1V4
  37423. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37424. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37425. // facet equations :
  37426. // we compute each facet normal vector
  37427. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37428. // we compute the value d by applying the equation to v1 which belongs to the plane
  37429. // then we store the facet equation in a Vector4
  37430. v2.subtractToRef(v1, v1v2);
  37431. v3.subtractToRef(v1, v1v3);
  37432. v4.subtractToRef(v1, v1v4);
  37433. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37434. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37435. norm1.normalize();
  37436. norm2.normalize();
  37437. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37438. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37439. var quad = this._heightQuads[row * subdivisionsX + col];
  37440. quad.slope.copyFromFloats(cd, h);
  37441. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37442. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37443. }
  37444. }
  37445. };
  37446. return GroundMesh;
  37447. }(BABYLON.Mesh));
  37448. BABYLON.GroundMesh = GroundMesh;
  37449. })(BABYLON || (BABYLON = {}));
  37450. //# sourceMappingURL=babylon.groundMesh.js.map
  37451. var BABYLON;
  37452. (function (BABYLON) {
  37453. var LinesMesh = (function (_super) {
  37454. __extends(LinesMesh, _super);
  37455. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37456. if (parent === void 0) { parent = null; }
  37457. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  37458. _this.color = new BABYLON.Color3(1, 1, 1);
  37459. _this.alpha = 1;
  37460. _this._positionBuffer = {};
  37461. if (source) {
  37462. _this.color = source.color.clone();
  37463. _this.alpha = source.alpha;
  37464. }
  37465. _this._intersectionThreshold = 0.1;
  37466. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37467. attributes: [BABYLON.VertexBuffer.PositionKind],
  37468. uniforms: ["worldViewProjection", "color"],
  37469. needAlphaBlending: true
  37470. });
  37471. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37472. return _this;
  37473. }
  37474. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37475. /**
  37476. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37477. * This margin is expressed in world space coordinates, so its value may vary.
  37478. * Default value is 0.1
  37479. * @returns the intersection Threshold value.
  37480. */
  37481. get: function () {
  37482. return this._intersectionThreshold;
  37483. },
  37484. /**
  37485. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37486. * This margin is expressed in world space coordinates, so its value may vary.
  37487. * @param value the new threshold to apply
  37488. */
  37489. set: function (value) {
  37490. if (this._intersectionThreshold === value) {
  37491. return;
  37492. }
  37493. this._intersectionThreshold = value;
  37494. if (this.geometry) {
  37495. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37496. }
  37497. },
  37498. enumerable: true,
  37499. configurable: true
  37500. });
  37501. LinesMesh.prototype.getClassName = function () {
  37502. return "LinesMesh";
  37503. };
  37504. Object.defineProperty(LinesMesh.prototype, "material", {
  37505. get: function () {
  37506. return this._colorShader;
  37507. },
  37508. enumerable: true,
  37509. configurable: true
  37510. });
  37511. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37512. get: function () {
  37513. return false;
  37514. },
  37515. enumerable: true,
  37516. configurable: true
  37517. });
  37518. LinesMesh.prototype.createInstance = function (name) {
  37519. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37520. return null;
  37521. };
  37522. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37523. var engine = this.getScene().getEngine();
  37524. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37525. // VBOs
  37526. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37527. // Color
  37528. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37529. };
  37530. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37531. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37532. return;
  37533. }
  37534. var engine = this.getScene().getEngine();
  37535. // Draw order
  37536. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37537. };
  37538. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37539. this._colorShader.dispose();
  37540. _super.prototype.dispose.call(this, doNotRecurse);
  37541. };
  37542. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37543. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37544. };
  37545. return LinesMesh;
  37546. }(BABYLON.Mesh));
  37547. BABYLON.LinesMesh = LinesMesh;
  37548. })(BABYLON || (BABYLON = {}));
  37549. //# sourceMappingURL=babylon.linesMesh.js.map
  37550. var BABYLON;
  37551. (function (BABYLON) {
  37552. var DefaultLoadingScreen = (function () {
  37553. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37554. if (_loadingText === void 0) { _loadingText = ""; }
  37555. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37556. var _this = this;
  37557. this._renderingCanvas = _renderingCanvas;
  37558. this._loadingText = _loadingText;
  37559. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37560. // Resize
  37561. this._resizeLoadingUI = function () {
  37562. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37563. _this._loadingDiv.style.position = "absolute";
  37564. _this._loadingDiv.style.left = canvasRect.left + "px";
  37565. _this._loadingDiv.style.top = canvasRect.top + "px";
  37566. _this._loadingDiv.style.width = canvasRect.width + "px";
  37567. _this._loadingDiv.style.height = canvasRect.height + "px";
  37568. };
  37569. }
  37570. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37571. var _this = this;
  37572. if (this._loadingDiv) {
  37573. // Do not add a loading screen if there is already one
  37574. return;
  37575. }
  37576. this._loadingDiv = document.createElement("div");
  37577. this._loadingDiv.id = "babylonjsLoadingDiv";
  37578. this._loadingDiv.style.opacity = "0";
  37579. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37580. // Loading text
  37581. this._loadingTextDiv = document.createElement("div");
  37582. this._loadingTextDiv.style.position = "absolute";
  37583. this._loadingTextDiv.style.left = "0";
  37584. this._loadingTextDiv.style.top = "50%";
  37585. this._loadingTextDiv.style.marginTop = "80px";
  37586. this._loadingTextDiv.style.width = "100%";
  37587. this._loadingTextDiv.style.height = "20px";
  37588. this._loadingTextDiv.style.fontFamily = "Arial";
  37589. this._loadingTextDiv.style.fontSize = "14px";
  37590. this._loadingTextDiv.style.color = "white";
  37591. this._loadingTextDiv.style.textAlign = "center";
  37592. this._loadingTextDiv.innerHTML = "Loading";
  37593. this._loadingDiv.appendChild(this._loadingTextDiv);
  37594. //set the predefined text
  37595. this._loadingTextDiv.innerHTML = this._loadingText;
  37596. // Loading img
  37597. var imgBack = new Image();
  37598. 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==";
  37599. imgBack.style.position = "absolute";
  37600. imgBack.style.left = "50%";
  37601. imgBack.style.top = "50%";
  37602. imgBack.style.marginLeft = "-50px";
  37603. imgBack.style.marginTop = "-50px";
  37604. imgBack.style.transition = "transform 1.0s ease";
  37605. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37606. var deg = 360;
  37607. var onTransitionEnd = function () {
  37608. deg += 360;
  37609. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37610. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37611. };
  37612. imgBack.addEventListener("transitionend", onTransitionEnd);
  37613. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37614. this._loadingDiv.appendChild(imgBack);
  37615. // front image
  37616. var imgFront = new Image();
  37617. 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=";
  37618. imgFront.style.position = "absolute";
  37619. imgFront.style.left = "50%";
  37620. imgFront.style.top = "50%";
  37621. imgFront.style.marginLeft = "-50px";
  37622. imgFront.style.marginTop = "-50px";
  37623. this._loadingDiv.appendChild(imgFront);
  37624. this._resizeLoadingUI();
  37625. window.addEventListener("resize", this._resizeLoadingUI);
  37626. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37627. document.body.appendChild(this._loadingDiv);
  37628. setTimeout(function () {
  37629. _this._loadingDiv.style.opacity = "1";
  37630. imgBack.style.transform = "rotateZ(360deg)";
  37631. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37632. }, 0);
  37633. };
  37634. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37635. var _this = this;
  37636. if (!this._loadingDiv) {
  37637. return;
  37638. }
  37639. var onTransitionEnd = function () {
  37640. if (!_this._loadingDiv) {
  37641. return;
  37642. }
  37643. document.body.removeChild(_this._loadingDiv);
  37644. window.removeEventListener("resize", _this._resizeLoadingUI);
  37645. _this._loadingDiv = null;
  37646. };
  37647. this._loadingDiv.style.opacity = "0";
  37648. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37649. };
  37650. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37651. set: function (text) {
  37652. this._loadingText = text;
  37653. if (this._loadingTextDiv) {
  37654. this._loadingTextDiv.innerHTML = this._loadingText;
  37655. }
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37661. get: function () {
  37662. return this._loadingDivBackgroundColor;
  37663. },
  37664. set: function (color) {
  37665. this._loadingDivBackgroundColor = color;
  37666. if (!this._loadingDiv) {
  37667. return;
  37668. }
  37669. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37670. },
  37671. enumerable: true,
  37672. configurable: true
  37673. });
  37674. return DefaultLoadingScreen;
  37675. }());
  37676. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37677. })(BABYLON || (BABYLON = {}));
  37678. //# sourceMappingURL=babylon.loadingScreen.js.map
  37679. var BABYLON;
  37680. (function (BABYLON) {
  37681. var AudioEngine = (function () {
  37682. function AudioEngine() {
  37683. this._audioContext = null;
  37684. this._audioContextInitialized = false;
  37685. this.canUseWebAudio = false;
  37686. this.WarnedWebAudioUnsupported = false;
  37687. this.unlocked = false;
  37688. this.isMP3supported = false;
  37689. this.isOGGsupported = false;
  37690. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37691. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37692. this.canUseWebAudio = true;
  37693. }
  37694. var audioElem = document.createElement('audio');
  37695. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37696. this.isMP3supported = true;
  37697. }
  37698. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37699. this.isOGGsupported = true;
  37700. }
  37701. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37702. this._unlockiOSaudio();
  37703. }
  37704. else {
  37705. this.unlocked = true;
  37706. }
  37707. }
  37708. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37709. get: function () {
  37710. if (!this._audioContextInitialized) {
  37711. this._initializeAudioContext();
  37712. }
  37713. return this._audioContext;
  37714. },
  37715. enumerable: true,
  37716. configurable: true
  37717. });
  37718. AudioEngine.prototype._unlockiOSaudio = function () {
  37719. var _this = this;
  37720. var unlockaudio = function () {
  37721. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37722. var source = _this.audioContext.createBufferSource();
  37723. source.buffer = buffer;
  37724. source.connect(_this.audioContext.destination);
  37725. source.start(0);
  37726. setTimeout(function () {
  37727. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37728. _this.unlocked = true;
  37729. window.removeEventListener('touchend', unlockaudio, false);
  37730. if (_this.onAudioUnlocked) {
  37731. _this.onAudioUnlocked();
  37732. }
  37733. }
  37734. }, 0);
  37735. };
  37736. window.addEventListener('touchend', unlockaudio, false);
  37737. };
  37738. AudioEngine.prototype._initializeAudioContext = function () {
  37739. try {
  37740. if (this.canUseWebAudio) {
  37741. this._audioContext = new AudioContext();
  37742. // create a global volume gain node
  37743. this.masterGain = this._audioContext.createGain();
  37744. this.masterGain.gain.value = 1;
  37745. this.masterGain.connect(this._audioContext.destination);
  37746. this._audioContextInitialized = true;
  37747. }
  37748. }
  37749. catch (e) {
  37750. this.canUseWebAudio = false;
  37751. BABYLON.Tools.Error("Web Audio: " + e.message);
  37752. }
  37753. };
  37754. AudioEngine.prototype.dispose = function () {
  37755. if (this.canUseWebAudio && this._audioContextInitialized) {
  37756. if (this._connectedAnalyser) {
  37757. this._connectedAnalyser.stopDebugCanvas();
  37758. this._connectedAnalyser.dispose();
  37759. this.masterGain.disconnect();
  37760. this.masterGain.connect(this._audioContext.destination);
  37761. this._connectedAnalyser = null;
  37762. }
  37763. this.masterGain.gain.value = 1;
  37764. }
  37765. this.WarnedWebAudioUnsupported = false;
  37766. };
  37767. AudioEngine.prototype.getGlobalVolume = function () {
  37768. if (this.canUseWebAudio && this._audioContextInitialized) {
  37769. return this.masterGain.gain.value;
  37770. }
  37771. else {
  37772. return -1;
  37773. }
  37774. };
  37775. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37776. if (this.canUseWebAudio && this._audioContextInitialized) {
  37777. this.masterGain.gain.value = newVolume;
  37778. }
  37779. };
  37780. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37781. if (this._connectedAnalyser) {
  37782. this._connectedAnalyser.stopDebugCanvas();
  37783. }
  37784. if (this.canUseWebAudio && this._audioContextInitialized) {
  37785. this._connectedAnalyser = analyser;
  37786. this.masterGain.disconnect();
  37787. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37788. }
  37789. };
  37790. return AudioEngine;
  37791. }());
  37792. BABYLON.AudioEngine = AudioEngine;
  37793. })(BABYLON || (BABYLON = {}));
  37794. //# sourceMappingURL=babylon.audioEngine.js.map
  37795. var BABYLON;
  37796. (function (BABYLON) {
  37797. var Sound = (function () {
  37798. /**
  37799. * Create a sound and attach it to a scene
  37800. * @param name Name of your sound
  37801. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37802. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37803. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37804. */
  37805. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37806. var _this = this;
  37807. this.autoplay = false;
  37808. this.loop = false;
  37809. this.useCustomAttenuation = false;
  37810. this.spatialSound = false;
  37811. this.refDistance = 1;
  37812. this.rolloffFactor = 1;
  37813. this.maxDistance = 100;
  37814. this.distanceModel = "linear";
  37815. this._panningModel = "equalpower";
  37816. this._playbackRate = 1;
  37817. this._streaming = false;
  37818. this._startTime = 0;
  37819. this._startOffset = 0;
  37820. this._position = BABYLON.Vector3.Zero();
  37821. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37822. this._volume = 1;
  37823. this._isLoaded = false;
  37824. this._isReadyToPlay = false;
  37825. this.isPlaying = false;
  37826. this.isPaused = false;
  37827. this._isDirectional = false;
  37828. // Used if you'd like to create a directional sound.
  37829. // If not set, the sound will be omnidirectional
  37830. this._coneInnerAngle = 360;
  37831. this._coneOuterAngle = 360;
  37832. this._coneOuterGain = 0;
  37833. this._isOutputConnected = false;
  37834. this._urlType = "Unknown";
  37835. this.name = name;
  37836. this._scene = scene;
  37837. this._readyToPlayCallback = readyToPlayCallback;
  37838. // Default custom attenuation function is a linear attenuation
  37839. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37840. if (currentDistance < maxDistance) {
  37841. return currentVolume * (1 - currentDistance / maxDistance);
  37842. }
  37843. else {
  37844. return 0;
  37845. }
  37846. };
  37847. if (options) {
  37848. this.autoplay = options.autoplay || false;
  37849. this.loop = options.loop || false;
  37850. // if volume === 0, we need another way to check this option
  37851. if (options.volume !== undefined) {
  37852. this._volume = options.volume;
  37853. }
  37854. this.spatialSound = options.spatialSound || false;
  37855. this.maxDistance = options.maxDistance || 100;
  37856. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37857. this.rolloffFactor = options.rolloffFactor || 1;
  37858. this.refDistance = options.refDistance || 1;
  37859. this.distanceModel = options.distanceModel || "linear";
  37860. this._playbackRate = options.playbackRate || 1;
  37861. this._streaming = options.streaming || false;
  37862. }
  37863. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37864. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37865. this._soundGain.gain.value = this._volume;
  37866. this._inputAudioNode = this._soundGain;
  37867. this._ouputAudioNode = this._soundGain;
  37868. if (this.spatialSound) {
  37869. this._createSpatialParameters();
  37870. }
  37871. this._scene.mainSoundTrack.AddSound(this);
  37872. var validParameter = true;
  37873. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37874. if (urlOrArrayBuffer) {
  37875. if (typeof (urlOrArrayBuffer) === "string")
  37876. this._urlType = "String";
  37877. if (Array.isArray(urlOrArrayBuffer))
  37878. this._urlType = "Array";
  37879. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37880. this._urlType = "ArrayBuffer";
  37881. var urls = [];
  37882. var codecSupportedFound = false;
  37883. switch (this._urlType) {
  37884. case "ArrayBuffer":
  37885. if (urlOrArrayBuffer.byteLength > 0) {
  37886. codecSupportedFound = true;
  37887. this._soundLoaded(urlOrArrayBuffer);
  37888. }
  37889. break;
  37890. case "String":
  37891. urls.push(urlOrArrayBuffer);
  37892. case "Array":
  37893. if (urls.length === 0)
  37894. urls = urlOrArrayBuffer;
  37895. // If we found a supported format, we load it immediately and stop the loop
  37896. for (var i = 0; i < urls.length; i++) {
  37897. var url = urls[i];
  37898. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37899. codecSupportedFound = true;
  37900. }
  37901. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37902. codecSupportedFound = true;
  37903. }
  37904. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37905. codecSupportedFound = true;
  37906. }
  37907. if (codecSupportedFound) {
  37908. // Loading sound using XHR2
  37909. if (!this._streaming) {
  37910. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37911. }
  37912. else {
  37913. this._htmlAudioElement = new Audio(url);
  37914. this._htmlAudioElement.controls = false;
  37915. this._htmlAudioElement.loop = this.loop;
  37916. this._htmlAudioElement.crossOrigin = "anonymous";
  37917. this._htmlAudioElement.preload = "auto";
  37918. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37919. _this._isReadyToPlay = true;
  37920. if (_this.autoplay) {
  37921. _this.play();
  37922. }
  37923. if (_this._readyToPlayCallback) {
  37924. _this._readyToPlayCallback();
  37925. }
  37926. });
  37927. document.body.appendChild(this._htmlAudioElement);
  37928. }
  37929. break;
  37930. }
  37931. }
  37932. break;
  37933. default:
  37934. validParameter = false;
  37935. break;
  37936. }
  37937. if (!validParameter) {
  37938. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37939. }
  37940. else {
  37941. if (!codecSupportedFound) {
  37942. this._isReadyToPlay = true;
  37943. // Simulating a ready to play event to avoid breaking code path
  37944. if (this._readyToPlayCallback) {
  37945. window.setTimeout(function () {
  37946. _this._readyToPlayCallback();
  37947. }, 1000);
  37948. }
  37949. }
  37950. }
  37951. }
  37952. }
  37953. else {
  37954. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37955. this._scene.mainSoundTrack.AddSound(this);
  37956. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37957. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37958. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37959. }
  37960. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37961. if (this._readyToPlayCallback) {
  37962. window.setTimeout(function () {
  37963. _this._readyToPlayCallback();
  37964. }, 1000);
  37965. }
  37966. }
  37967. }
  37968. Sound.prototype.dispose = function () {
  37969. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37970. if (this.isPlaying) {
  37971. this.stop();
  37972. }
  37973. this._isReadyToPlay = false;
  37974. if (this.soundTrackId === -1) {
  37975. this._scene.mainSoundTrack.RemoveSound(this);
  37976. }
  37977. else {
  37978. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37979. }
  37980. if (this._soundGain) {
  37981. this._soundGain.disconnect();
  37982. this._soundGain = null;
  37983. }
  37984. if (this._soundPanner) {
  37985. this._soundPanner.disconnect();
  37986. this._soundPanner = null;
  37987. }
  37988. if (this._soundSource) {
  37989. this._soundSource.disconnect();
  37990. this._soundSource = null;
  37991. }
  37992. this._audioBuffer = null;
  37993. if (this._htmlAudioElement) {
  37994. this._htmlAudioElement.pause();
  37995. this._htmlAudioElement.src = "";
  37996. document.body.removeChild(this._htmlAudioElement);
  37997. }
  37998. if (this._connectedMesh) {
  37999. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38000. this._connectedMesh = null;
  38001. }
  38002. }
  38003. };
  38004. Sound.prototype._soundLoaded = function (audioData) {
  38005. var _this = this;
  38006. this._isLoaded = true;
  38007. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38008. _this._audioBuffer = buffer;
  38009. _this._isReadyToPlay = true;
  38010. if (_this.autoplay) {
  38011. _this.play();
  38012. }
  38013. if (_this._readyToPlayCallback) {
  38014. _this._readyToPlayCallback();
  38015. }
  38016. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38017. };
  38018. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38019. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38020. this._audioBuffer = audioBuffer;
  38021. this._isReadyToPlay = true;
  38022. }
  38023. };
  38024. Sound.prototype.updateOptions = function (options) {
  38025. if (options) {
  38026. this.loop = options.loop || this.loop;
  38027. this.maxDistance = options.maxDistance || this.maxDistance;
  38028. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38029. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38030. this.refDistance = options.refDistance || this.refDistance;
  38031. this.distanceModel = options.distanceModel || this.distanceModel;
  38032. this._playbackRate = options.playbackRate || this._playbackRate;
  38033. this._updateSpatialParameters();
  38034. if (this.isPlaying) {
  38035. if (this._streaming) {
  38036. this._htmlAudioElement.playbackRate = this._playbackRate;
  38037. }
  38038. else {
  38039. this._soundSource.playbackRate.value = this._playbackRate;
  38040. }
  38041. }
  38042. }
  38043. };
  38044. Sound.prototype._createSpatialParameters = function () {
  38045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38046. if (this._scene.headphone) {
  38047. this._panningModel = "HRTF";
  38048. }
  38049. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38050. this._updateSpatialParameters();
  38051. this._soundPanner.connect(this._ouputAudioNode);
  38052. this._inputAudioNode = this._soundPanner;
  38053. }
  38054. };
  38055. Sound.prototype._updateSpatialParameters = function () {
  38056. if (this.spatialSound) {
  38057. if (this.useCustomAttenuation) {
  38058. // Tricks to disable in a way embedded Web Audio attenuation
  38059. this._soundPanner.distanceModel = "linear";
  38060. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38061. this._soundPanner.refDistance = 1;
  38062. this._soundPanner.rolloffFactor = 1;
  38063. this._soundPanner.panningModel = this._panningModel;
  38064. }
  38065. else {
  38066. this._soundPanner.distanceModel = this.distanceModel;
  38067. this._soundPanner.maxDistance = this.maxDistance;
  38068. this._soundPanner.refDistance = this.refDistance;
  38069. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38070. this._soundPanner.panningModel = this._panningModel;
  38071. }
  38072. }
  38073. };
  38074. Sound.prototype.switchPanningModelToHRTF = function () {
  38075. this._panningModel = "HRTF";
  38076. this._switchPanningModel();
  38077. };
  38078. Sound.prototype.switchPanningModelToEqualPower = function () {
  38079. this._panningModel = "equalpower";
  38080. this._switchPanningModel();
  38081. };
  38082. Sound.prototype._switchPanningModel = function () {
  38083. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38084. this._soundPanner.panningModel = this._panningModel;
  38085. }
  38086. };
  38087. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  38088. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38089. if (this._isOutputConnected) {
  38090. this._ouputAudioNode.disconnect();
  38091. }
  38092. this._ouputAudioNode.connect(soundTrackAudioNode);
  38093. this._isOutputConnected = true;
  38094. }
  38095. };
  38096. /**
  38097. * Transform this sound into a directional source
  38098. * @param coneInnerAngle Size of the inner cone in degree
  38099. * @param coneOuterAngle Size of the outer cone in degree
  38100. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  38101. */
  38102. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  38103. if (coneOuterAngle < coneInnerAngle) {
  38104. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  38105. return;
  38106. }
  38107. this._coneInnerAngle = coneInnerAngle;
  38108. this._coneOuterAngle = coneOuterAngle;
  38109. this._coneOuterGain = coneOuterGain;
  38110. this._isDirectional = true;
  38111. if (this.isPlaying && this.loop) {
  38112. this.stop();
  38113. this.play();
  38114. }
  38115. };
  38116. Sound.prototype.setPosition = function (newPosition) {
  38117. this._position = newPosition;
  38118. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38119. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38120. }
  38121. };
  38122. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38123. this._localDirection = newLocalDirection;
  38124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38125. this._updateDirection();
  38126. }
  38127. };
  38128. Sound.prototype._updateDirection = function () {
  38129. var mat = this._connectedMesh.getWorldMatrix();
  38130. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38131. direction.normalize();
  38132. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38133. };
  38134. Sound.prototype.updateDistanceFromListener = function () {
  38135. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38136. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38137. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38138. }
  38139. };
  38140. Sound.prototype.setAttenuationFunction = function (callback) {
  38141. this._customAttenuationFunction = callback;
  38142. };
  38143. /**
  38144. * Play the sound
  38145. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38146. * @param offset (optional) Start the sound setting it at a specific time
  38147. */
  38148. Sound.prototype.play = function (time, offset) {
  38149. var _this = this;
  38150. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38151. try {
  38152. if (this._startOffset < 0) {
  38153. time = -this._startOffset;
  38154. this._startOffset = 0;
  38155. }
  38156. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38157. if (!this._soundSource || !this._streamingSource) {
  38158. if (this.spatialSound) {
  38159. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38160. if (this._isDirectional) {
  38161. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38162. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38163. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38164. if (this._connectedMesh) {
  38165. this._updateDirection();
  38166. }
  38167. else {
  38168. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38169. }
  38170. }
  38171. }
  38172. }
  38173. if (this._streaming) {
  38174. if (!this._streamingSource) {
  38175. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38176. this._htmlAudioElement.onended = function () { _this._onended(); };
  38177. this._htmlAudioElement.playbackRate = this._playbackRate;
  38178. }
  38179. this._streamingSource.disconnect();
  38180. this._streamingSource.connect(this._inputAudioNode);
  38181. this._htmlAudioElement.play();
  38182. }
  38183. else {
  38184. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38185. this._soundSource.buffer = this._audioBuffer;
  38186. this._soundSource.connect(this._inputAudioNode);
  38187. this._soundSource.loop = this.loop;
  38188. this._soundSource.playbackRate.value = this._playbackRate;
  38189. this._soundSource.onended = function () { _this._onended(); };
  38190. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38191. }
  38192. this._startTime = startTime;
  38193. this.isPlaying = true;
  38194. this.isPaused = false;
  38195. }
  38196. catch (ex) {
  38197. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38198. }
  38199. }
  38200. };
  38201. Sound.prototype._onended = function () {
  38202. this.isPlaying = false;
  38203. if (this.onended) {
  38204. this.onended();
  38205. }
  38206. };
  38207. /**
  38208. * Stop the sound
  38209. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38210. */
  38211. Sound.prototype.stop = function (time) {
  38212. if (this.isPlaying) {
  38213. if (this._streaming) {
  38214. this._htmlAudioElement.pause();
  38215. // Test needed for Firefox or it will generate an Invalid State Error
  38216. if (this._htmlAudioElement.currentTime > 0) {
  38217. this._htmlAudioElement.currentTime = 0;
  38218. }
  38219. }
  38220. else {
  38221. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38222. this._soundSource.stop(stopTime);
  38223. this._soundSource.onended = null;
  38224. if (!this.isPaused) {
  38225. this._startOffset = 0;
  38226. }
  38227. }
  38228. this.isPlaying = false;
  38229. }
  38230. };
  38231. Sound.prototype.pause = function () {
  38232. if (this.isPlaying) {
  38233. this.isPaused = true;
  38234. if (this._streaming) {
  38235. this._htmlAudioElement.pause();
  38236. }
  38237. else {
  38238. this.stop(0);
  38239. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38240. }
  38241. }
  38242. };
  38243. Sound.prototype.setVolume = function (newVolume, time) {
  38244. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38245. if (time) {
  38246. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38247. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38248. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38249. }
  38250. else {
  38251. this._soundGain.gain.value = newVolume;
  38252. }
  38253. }
  38254. this._volume = newVolume;
  38255. };
  38256. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38257. this._playbackRate = newPlaybackRate;
  38258. if (this.isPlaying) {
  38259. if (this._streaming) {
  38260. this._htmlAudioElement.playbackRate = this._playbackRate;
  38261. }
  38262. else {
  38263. this._soundSource.playbackRate.value = this._playbackRate;
  38264. }
  38265. }
  38266. };
  38267. Sound.prototype.getVolume = function () {
  38268. return this._volume;
  38269. };
  38270. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38271. var _this = this;
  38272. if (this._connectedMesh) {
  38273. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38274. this._registerFunc = null;
  38275. }
  38276. this._connectedMesh = meshToConnectTo;
  38277. if (!this.spatialSound) {
  38278. this.spatialSound = true;
  38279. this._createSpatialParameters();
  38280. if (this.isPlaying && this.loop) {
  38281. this.stop();
  38282. this.play();
  38283. }
  38284. }
  38285. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38286. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38287. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38288. };
  38289. Sound.prototype.detachFromMesh = function () {
  38290. if (this._connectedMesh) {
  38291. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38292. this._registerFunc = null;
  38293. this._connectedMesh = null;
  38294. }
  38295. };
  38296. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38297. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38298. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38299. this._updateDirection();
  38300. }
  38301. };
  38302. Sound.prototype.clone = function () {
  38303. var _this = this;
  38304. if (!this._streaming) {
  38305. var setBufferAndRun = function () {
  38306. if (_this._isReadyToPlay) {
  38307. clonedSound._audioBuffer = _this.getAudioBuffer();
  38308. clonedSound._isReadyToPlay = true;
  38309. if (clonedSound.autoplay) {
  38310. clonedSound.play();
  38311. }
  38312. }
  38313. else {
  38314. window.setTimeout(setBufferAndRun, 300);
  38315. }
  38316. };
  38317. var currentOptions = {
  38318. autoplay: this.autoplay, loop: this.loop,
  38319. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38320. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38321. refDistance: this.refDistance, distanceModel: this.distanceModel
  38322. };
  38323. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38324. if (this.useCustomAttenuation) {
  38325. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38326. }
  38327. clonedSound.setPosition(this._position);
  38328. clonedSound.setPlaybackRate(this._playbackRate);
  38329. setBufferAndRun();
  38330. return clonedSound;
  38331. }
  38332. else {
  38333. return null;
  38334. }
  38335. };
  38336. Sound.prototype.getAudioBuffer = function () {
  38337. return this._audioBuffer;
  38338. };
  38339. Sound.prototype.serialize = function () {
  38340. var serializationObject = {
  38341. name: this.name,
  38342. url: this.name,
  38343. autoplay: this.autoplay,
  38344. loop: this.loop,
  38345. volume: this._volume,
  38346. spatialSound: this.spatialSound,
  38347. maxDistance: this.maxDistance,
  38348. rolloffFactor: this.rolloffFactor,
  38349. refDistance: this.refDistance,
  38350. distanceModel: this.distanceModel,
  38351. playbackRate: this._playbackRate,
  38352. panningModel: this._panningModel,
  38353. soundTrackId: this.soundTrackId
  38354. };
  38355. if (this.spatialSound) {
  38356. if (this._connectedMesh)
  38357. serializationObject.connectedMeshId = this._connectedMesh.id;
  38358. serializationObject.position = this._position.asArray();
  38359. serializationObject.refDistance = this.refDistance;
  38360. serializationObject.distanceModel = this.distanceModel;
  38361. serializationObject.isDirectional = this._isDirectional;
  38362. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38363. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38364. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38365. serializationObject.coneOuterGain = this._coneOuterGain;
  38366. }
  38367. return serializationObject;
  38368. };
  38369. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38370. var soundName = parsedSound.name;
  38371. var soundUrl;
  38372. if (parsedSound.url) {
  38373. soundUrl = rootUrl + parsedSound.url;
  38374. }
  38375. else {
  38376. soundUrl = rootUrl + soundName;
  38377. }
  38378. var options = {
  38379. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38380. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38381. rolloffFactor: parsedSound.rolloffFactor,
  38382. refDistance: parsedSound.refDistance,
  38383. distanceModel: parsedSound.distanceModel,
  38384. playbackRate: parsedSound.playbackRate
  38385. };
  38386. var newSound;
  38387. if (!sourceSound) {
  38388. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38389. scene._addPendingData(newSound);
  38390. }
  38391. else {
  38392. var setBufferAndRun = function () {
  38393. if (sourceSound._isReadyToPlay) {
  38394. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38395. newSound._isReadyToPlay = true;
  38396. if (newSound.autoplay) {
  38397. newSound.play();
  38398. }
  38399. }
  38400. else {
  38401. window.setTimeout(setBufferAndRun, 300);
  38402. }
  38403. };
  38404. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38405. setBufferAndRun();
  38406. }
  38407. if (parsedSound.position) {
  38408. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38409. newSound.setPosition(soundPosition);
  38410. }
  38411. if (parsedSound.isDirectional) {
  38412. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38413. if (parsedSound.localDirectionToMesh) {
  38414. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38415. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38416. }
  38417. }
  38418. if (parsedSound.connectedMeshId) {
  38419. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38420. if (connectedMesh) {
  38421. newSound.attachToMesh(connectedMesh);
  38422. }
  38423. }
  38424. return newSound;
  38425. };
  38426. return Sound;
  38427. }());
  38428. BABYLON.Sound = Sound;
  38429. })(BABYLON || (BABYLON = {}));
  38430. //# sourceMappingURL=babylon.sound.js.map
  38431. var BABYLON;
  38432. (function (BABYLON) {
  38433. var SoundTrack = (function () {
  38434. function SoundTrack(scene, options) {
  38435. this.id = -1;
  38436. this._isMainTrack = false;
  38437. this._isInitialized = false;
  38438. this._scene = scene;
  38439. this.soundCollection = new Array();
  38440. this._options = options;
  38441. if (!this._isMainTrack) {
  38442. this._scene.soundTracks.push(this);
  38443. this.id = this._scene.soundTracks.length - 1;
  38444. }
  38445. }
  38446. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38447. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38448. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38449. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38450. if (this._options) {
  38451. if (this._options.volume) {
  38452. this._outputAudioNode.gain.value = this._options.volume;
  38453. }
  38454. if (this._options.mainTrack) {
  38455. this._isMainTrack = this._options.mainTrack;
  38456. }
  38457. }
  38458. this._isInitialized = true;
  38459. }
  38460. };
  38461. SoundTrack.prototype.dispose = function () {
  38462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38463. if (this._connectedAnalyser) {
  38464. this._connectedAnalyser.stopDebugCanvas();
  38465. }
  38466. while (this.soundCollection.length) {
  38467. this.soundCollection[0].dispose();
  38468. }
  38469. if (this._outputAudioNode) {
  38470. this._outputAudioNode.disconnect();
  38471. }
  38472. this._outputAudioNode = null;
  38473. }
  38474. };
  38475. SoundTrack.prototype.AddSound = function (sound) {
  38476. if (!this._isInitialized) {
  38477. this._initializeSoundTrackAudioGraph();
  38478. }
  38479. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38480. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38481. }
  38482. if (sound.soundTrackId) {
  38483. if (sound.soundTrackId === -1) {
  38484. this._scene.mainSoundTrack.RemoveSound(sound);
  38485. }
  38486. else {
  38487. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38488. }
  38489. }
  38490. this.soundCollection.push(sound);
  38491. sound.soundTrackId = this.id;
  38492. };
  38493. SoundTrack.prototype.RemoveSound = function (sound) {
  38494. var index = this.soundCollection.indexOf(sound);
  38495. if (index !== -1) {
  38496. this.soundCollection.splice(index, 1);
  38497. }
  38498. };
  38499. SoundTrack.prototype.setVolume = function (newVolume) {
  38500. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38501. this._outputAudioNode.gain.value = newVolume;
  38502. }
  38503. };
  38504. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38505. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38506. for (var i = 0; i < this.soundCollection.length; i++) {
  38507. this.soundCollection[i].switchPanningModelToHRTF();
  38508. }
  38509. }
  38510. };
  38511. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38512. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38513. for (var i = 0; i < this.soundCollection.length; i++) {
  38514. this.soundCollection[i].switchPanningModelToEqualPower();
  38515. }
  38516. }
  38517. };
  38518. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38519. if (this._connectedAnalyser) {
  38520. this._connectedAnalyser.stopDebugCanvas();
  38521. }
  38522. this._connectedAnalyser = analyser;
  38523. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38524. this._outputAudioNode.disconnect();
  38525. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38526. }
  38527. };
  38528. return SoundTrack;
  38529. }());
  38530. BABYLON.SoundTrack = SoundTrack;
  38531. })(BABYLON || (BABYLON = {}));
  38532. //# sourceMappingURL=babylon.soundtrack.js.map
  38533. var BABYLON;
  38534. (function (BABYLON) {
  38535. /**
  38536. * Special Glow Blur post process only blurring the alpha channel
  38537. * It enforces keeping the most luminous color in the color channel.
  38538. */
  38539. var GlowBlurPostProcess = (function (_super) {
  38540. __extends(GlowBlurPostProcess, _super);
  38541. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38542. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38543. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  38544. _this.direction = direction;
  38545. _this.blurWidth = blurWidth;
  38546. _this.onApplyObservable.add(function (effect) {
  38547. effect.setFloat2("screenSize", _this.width, _this.height);
  38548. effect.setVector2("direction", _this.direction);
  38549. effect.setFloat("blurWidth", _this.blurWidth);
  38550. });
  38551. return _this;
  38552. }
  38553. return GlowBlurPostProcess;
  38554. }(BABYLON.PostProcess));
  38555. /**
  38556. * The highlight layer Helps adding a glow effect around a mesh.
  38557. *
  38558. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38559. * glowy meshes to your scene.
  38560. *
  38561. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38562. */
  38563. var HighlightLayer = (function () {
  38564. /**
  38565. * Instantiates a new highlight Layer and references it to the scene..
  38566. * @param name The name of the layer
  38567. * @param scene The scene to use the layer in
  38568. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38569. */
  38570. function HighlightLayer(name, scene, options) {
  38571. this._vertexBuffers = {};
  38572. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38573. this._meshes = {};
  38574. this._maxSize = 0;
  38575. this._shouldRender = false;
  38576. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38577. this._excludedMeshes = {};
  38578. /**
  38579. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38580. */
  38581. this.innerGlow = true;
  38582. /**
  38583. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38584. */
  38585. this.outerGlow = true;
  38586. /**
  38587. * Specifies wether the highlight layer is enabled or not.
  38588. */
  38589. this.isEnabled = true;
  38590. /**
  38591. * An event triggered when the highlight layer has been disposed.
  38592. * @type {BABYLON.Observable}
  38593. */
  38594. this.onDisposeObservable = new BABYLON.Observable();
  38595. /**
  38596. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38597. * @type {BABYLON.Observable}
  38598. */
  38599. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38600. /**
  38601. * An event triggered when the highlight layer is being blurred.
  38602. * @type {BABYLON.Observable}
  38603. */
  38604. this.onBeforeBlurObservable = new BABYLON.Observable();
  38605. /**
  38606. * An event triggered when the highlight layer has been blurred.
  38607. * @type {BABYLON.Observable}
  38608. */
  38609. this.onAfterBlurObservable = new BABYLON.Observable();
  38610. /**
  38611. * An event triggered when the glowing blurred texture is being merged in the scene.
  38612. * @type {BABYLON.Observable}
  38613. */
  38614. this.onBeforeComposeObservable = new BABYLON.Observable();
  38615. /**
  38616. * An event triggered when the glowing blurred texture has been merged in the scene.
  38617. * @type {BABYLON.Observable}
  38618. */
  38619. this.onAfterComposeObservable = new BABYLON.Observable();
  38620. /**
  38621. * An event triggered when the highlight layer changes its size.
  38622. * @type {BABYLON.Observable}
  38623. */
  38624. this.onSizeChangedObservable = new BABYLON.Observable();
  38625. this._scene = scene;
  38626. var engine = scene.getEngine();
  38627. this._engine = engine;
  38628. this._maxSize = this._engine.getCaps().maxTextureSize;
  38629. this._scene.highlightLayers.push(this);
  38630. // Warn on stencil.
  38631. if (!this._engine.isStencilEnable) {
  38632. 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 }");
  38633. }
  38634. // Adapt options
  38635. this._options = options || {
  38636. mainTextureRatio: 0.25,
  38637. blurTextureSizeRatio: 0.5,
  38638. blurHorizontalSize: 1,
  38639. blurVerticalSize: 1,
  38640. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38641. };
  38642. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38643. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38644. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38645. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38646. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38647. // VBO
  38648. var vertices = [];
  38649. vertices.push(1, 1);
  38650. vertices.push(-1, 1);
  38651. vertices.push(-1, -1);
  38652. vertices.push(1, -1);
  38653. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38654. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38655. // Indices
  38656. var indices = [];
  38657. indices.push(0);
  38658. indices.push(1);
  38659. indices.push(2);
  38660. indices.push(0);
  38661. indices.push(2);
  38662. indices.push(3);
  38663. this._indexBuffer = engine.createIndexBuffer(indices);
  38664. // Effect
  38665. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38666. // Render target
  38667. this.setMainTextureSize();
  38668. // Create Textures and post processes
  38669. this.createTextureAndPostProcesses();
  38670. }
  38671. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38672. /**
  38673. * Gets the horizontal size of the blur.
  38674. */
  38675. get: function () {
  38676. return this._horizontalBlurPostprocess.blurWidth;
  38677. },
  38678. /**
  38679. * Specifies the horizontal size of the blur.
  38680. */
  38681. set: function (value) {
  38682. this._horizontalBlurPostprocess.blurWidth = value;
  38683. },
  38684. enumerable: true,
  38685. configurable: true
  38686. });
  38687. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38688. /**
  38689. * Gets the vertical size of the blur.
  38690. */
  38691. get: function () {
  38692. return this._verticalBlurPostprocess.blurWidth;
  38693. },
  38694. /**
  38695. * Specifies the vertical size of the blur.
  38696. */
  38697. set: function (value) {
  38698. this._verticalBlurPostprocess.blurWidth = value;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38704. /**
  38705. * Gets the camera attached to the layer.
  38706. */
  38707. get: function () {
  38708. return this._options.camera;
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. /**
  38714. * Creates the render target textures and post processes used in the highlight layer.
  38715. */
  38716. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38717. var _this = this;
  38718. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38719. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38720. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38721. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38722. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38723. width: this._mainTextureDesiredSize.width,
  38724. height: this._mainTextureDesiredSize.height
  38725. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38726. this._mainTexture.activeCamera = this._options.camera;
  38727. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38728. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38729. this._mainTexture.anisotropicFilteringLevel = 1;
  38730. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38731. this._mainTexture.renderParticles = false;
  38732. this._mainTexture.renderList = null;
  38733. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38734. width: blurTextureWidth,
  38735. height: blurTextureHeight
  38736. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38737. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38738. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38739. this._blurTexture.anisotropicFilteringLevel = 16;
  38740. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38741. this._blurTexture.renderParticles = false;
  38742. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38743. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38744. effect.setTexture("textureSampler", _this._mainTexture);
  38745. });
  38746. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38747. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38748. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38749. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38750. });
  38751. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38752. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38753. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38754. });
  38755. }
  38756. else {
  38757. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38758. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38759. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38760. });
  38761. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38762. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38763. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38764. });
  38765. }
  38766. this._mainTexture.onAfterUnbindObservable.add(function () {
  38767. _this.onBeforeBlurObservable.notifyObservers(_this);
  38768. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38769. _this.onAfterBlurObservable.notifyObservers(_this);
  38770. });
  38771. // Custom render function
  38772. var renderSubMesh = function (subMesh) {
  38773. var mesh = subMesh.getRenderingMesh();
  38774. var scene = _this._scene;
  38775. var engine = scene.getEngine();
  38776. // Culling
  38777. engine.setState(subMesh.getMaterial().backFaceCulling);
  38778. // Managing instances
  38779. var batch = mesh._getInstancesRenderList(subMesh._id);
  38780. if (batch.mustReturn) {
  38781. return;
  38782. }
  38783. // Excluded Mesh
  38784. if (_this._excludedMeshes[mesh.uniqueId]) {
  38785. return;
  38786. }
  38787. ;
  38788. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38789. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  38790. var material = subMesh.getMaterial();
  38791. var emissiveTexture = null;
  38792. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38793. emissiveTexture = material.emissiveTexture;
  38794. }
  38795. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38796. engine.enableEffect(_this._glowMapGenerationEffect);
  38797. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38798. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38799. if (highlightLayerMesh) {
  38800. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38801. }
  38802. else {
  38803. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38804. }
  38805. // Alpha test
  38806. if (material && material.needAlphaTesting()) {
  38807. var alphaTexture = material.getAlphaTestTexture();
  38808. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38809. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38810. }
  38811. // Glow emissive only
  38812. if (emissiveTexture) {
  38813. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38814. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38815. }
  38816. // Bones
  38817. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38818. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38819. }
  38820. // Draw
  38821. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38822. }
  38823. else {
  38824. // Need to reset refresh rate of the shadowMap
  38825. _this._mainTexture.resetRefreshCounter();
  38826. }
  38827. };
  38828. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38829. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38830. var index;
  38831. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38832. renderSubMesh(opaqueSubMeshes.data[index]);
  38833. }
  38834. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38835. renderSubMesh(alphaTestSubMeshes.data[index]);
  38836. }
  38837. for (index = 0; index < transparentSubMeshes.length; index++) {
  38838. renderSubMesh(transparentSubMeshes.data[index]);
  38839. }
  38840. };
  38841. this._mainTexture.onClearObservable.add(function (engine) {
  38842. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38843. });
  38844. };
  38845. /**
  38846. * Checks for the readiness of the element composing the layer.
  38847. * @param subMesh the mesh to check for
  38848. * @param useInstances specify wether or not to use instances to render the mesh
  38849. * @param emissiveTexture the associated emissive texture used to generate the glow
  38850. * @return true if ready otherwise, false
  38851. */
  38852. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38853. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38854. return false;
  38855. }
  38856. var defines = [];
  38857. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38858. var mesh = subMesh.getMesh();
  38859. var material = subMesh.getMaterial();
  38860. var uv1 = false;
  38861. var uv2 = false;
  38862. // Alpha test
  38863. if (material && material.needAlphaTesting()) {
  38864. var alphaTexture = material.getAlphaTestTexture();
  38865. if (alphaTexture) {
  38866. defines.push("#define ALPHATEST");
  38867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38868. alphaTexture.coordinatesIndex === 1) {
  38869. defines.push("#define DIFFUSEUV2");
  38870. uv2 = true;
  38871. }
  38872. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38873. defines.push("#define DIFFUSEUV1");
  38874. uv1 = true;
  38875. }
  38876. }
  38877. }
  38878. // Emissive
  38879. if (emissiveTexture) {
  38880. defines.push("#define EMISSIVE");
  38881. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38882. emissiveTexture.coordinatesIndex === 1) {
  38883. defines.push("#define EMISSIVEUV2");
  38884. uv2 = true;
  38885. }
  38886. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38887. defines.push("#define EMISSIVEUV1");
  38888. uv1 = true;
  38889. }
  38890. }
  38891. if (uv1) {
  38892. attribs.push(BABYLON.VertexBuffer.UVKind);
  38893. defines.push("#define UV1");
  38894. }
  38895. if (uv2) {
  38896. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38897. defines.push("#define UV2");
  38898. }
  38899. // Bones
  38900. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38903. if (mesh.numBoneInfluencers > 4) {
  38904. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38905. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38906. }
  38907. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38908. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38909. }
  38910. else {
  38911. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38912. }
  38913. // Instances
  38914. if (useInstances) {
  38915. defines.push("#define INSTANCES");
  38916. attribs.push("world0");
  38917. attribs.push("world1");
  38918. attribs.push("world2");
  38919. attribs.push("world3");
  38920. }
  38921. // Get correct effect
  38922. var join = defines.join("\n");
  38923. if (this._cachedDefines !== join) {
  38924. this._cachedDefines = join;
  38925. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38926. }
  38927. return this._glowMapGenerationEffect.isReady();
  38928. };
  38929. /**
  38930. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38931. */
  38932. HighlightLayer.prototype.render = function () {
  38933. var currentEffect = this._glowMapMergeEffect;
  38934. // Check
  38935. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38936. return;
  38937. var engine = this._scene.getEngine();
  38938. this.onBeforeComposeObservable.notifyObservers(this);
  38939. // Render
  38940. engine.enableEffect(currentEffect);
  38941. engine.setState(false);
  38942. // Cache
  38943. var previousStencilBuffer = engine.getStencilBuffer();
  38944. var previousStencilFunction = engine.getStencilFunction();
  38945. var previousStencilMask = engine.getStencilMask();
  38946. var previousAlphaMode = engine.getAlphaMode();
  38947. // Texture
  38948. currentEffect.setTexture("textureSampler", this._blurTexture);
  38949. // VBOs
  38950. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38951. // Draw order
  38952. engine.setAlphaMode(this._options.alphaBlendingMode);
  38953. engine.setStencilMask(0x00);
  38954. engine.setStencilBuffer(true);
  38955. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38956. if (this.outerGlow) {
  38957. currentEffect.setFloat("offset", 0);
  38958. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38959. engine.draw(true, 0, 6);
  38960. }
  38961. if (this.innerGlow) {
  38962. currentEffect.setFloat("offset", 1);
  38963. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38964. engine.draw(true, 0, 6);
  38965. }
  38966. // Restore Cache
  38967. engine.setStencilFunction(previousStencilFunction);
  38968. engine.setStencilMask(previousStencilMask);
  38969. engine.setAlphaMode(previousAlphaMode);
  38970. engine.setStencilBuffer(previousStencilBuffer);
  38971. this.onAfterComposeObservable.notifyObservers(this);
  38972. // Handle size changes.
  38973. var size = this._mainTexture.getSize();
  38974. this.setMainTextureSize();
  38975. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38976. // Recreate RTT and post processes on size change.
  38977. this.onSizeChangedObservable.notifyObservers(this);
  38978. this.disposeTextureAndPostProcesses();
  38979. this.createTextureAndPostProcesses();
  38980. }
  38981. };
  38982. /**
  38983. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38984. * @param mesh The mesh to exclude from the highlight layer
  38985. */
  38986. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38987. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  38988. if (!meshExcluded) {
  38989. this._excludedMeshes[mesh.uniqueId] = {
  38990. mesh: mesh,
  38991. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38992. mesh.getEngine().setStencilBuffer(false);
  38993. }),
  38994. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38995. mesh.getEngine().setStencilBuffer(true);
  38996. }),
  38997. };
  38998. }
  38999. };
  39000. /**
  39001. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39002. * @param mesh The mesh to highlight
  39003. */
  39004. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39005. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39006. if (meshExcluded) {
  39007. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39008. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39009. }
  39010. this._excludedMeshes[mesh.uniqueId] = undefined;
  39011. };
  39012. /**
  39013. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39014. * @param mesh The mesh to highlight
  39015. * @param color The color of the highlight
  39016. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39017. */
  39018. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39019. var _this = this;
  39020. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39021. var meshHighlight = this._meshes[mesh.uniqueId];
  39022. if (meshHighlight) {
  39023. meshHighlight.color = color;
  39024. }
  39025. else {
  39026. this._meshes[mesh.uniqueId] = {
  39027. mesh: mesh,
  39028. color: color,
  39029. // Lambda required for capture due to Observable this context
  39030. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39031. if (_this._excludedMeshes[mesh.uniqueId]) {
  39032. _this.defaultStencilReference(mesh);
  39033. }
  39034. else {
  39035. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39036. }
  39037. }),
  39038. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39039. glowEmissiveOnly: glowEmissiveOnly
  39040. };
  39041. }
  39042. this._shouldRender = true;
  39043. };
  39044. /**
  39045. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39046. * @param mesh The mesh to highlight
  39047. */
  39048. HighlightLayer.prototype.removeMesh = function (mesh) {
  39049. var meshHighlight = this._meshes[mesh.uniqueId];
  39050. if (meshHighlight) {
  39051. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39052. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39053. }
  39054. this._meshes[mesh.uniqueId] = undefined;
  39055. this._shouldRender = false;
  39056. for (var meshHighlightToCheck in this._meshes) {
  39057. if (meshHighlightToCheck) {
  39058. this._shouldRender = true;
  39059. break;
  39060. }
  39061. }
  39062. };
  39063. /**
  39064. * Returns true if the layer contains information to display, otherwise false.
  39065. */
  39066. HighlightLayer.prototype.shouldRender = function () {
  39067. return this.isEnabled && this._shouldRender;
  39068. };
  39069. /**
  39070. * Sets the main texture desired size which is the closest power of two
  39071. * of the engine canvas size.
  39072. */
  39073. HighlightLayer.prototype.setMainTextureSize = function () {
  39074. if (this._options.mainTextureFixedSize) {
  39075. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39076. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39077. }
  39078. else {
  39079. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  39080. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  39081. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  39082. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  39083. }
  39084. };
  39085. /**
  39086. * Force the stencil to the normal expected value for none glowing parts
  39087. */
  39088. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  39089. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  39090. };
  39091. /**
  39092. * Dispose only the render target textures and post process.
  39093. */
  39094. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39095. this._blurTexture.dispose();
  39096. this._mainTexture.dispose();
  39097. this._downSamplePostprocess.dispose();
  39098. this._horizontalBlurPostprocess.dispose();
  39099. this._verticalBlurPostprocess.dispose();
  39100. };
  39101. /**
  39102. * Dispose the highlight layer and free resources.
  39103. */
  39104. HighlightLayer.prototype.dispose = function () {
  39105. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39106. if (vertexBuffer) {
  39107. vertexBuffer.dispose();
  39108. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39109. }
  39110. if (this._indexBuffer) {
  39111. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39112. this._indexBuffer = null;
  39113. }
  39114. // Clean textures and post processes
  39115. this.disposeTextureAndPostProcesses();
  39116. // Clean mesh references
  39117. for (var id in this._meshes) {
  39118. var meshHighlight = this._meshes[id];
  39119. if (meshHighlight && meshHighlight.mesh) {
  39120. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39121. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39122. }
  39123. }
  39124. this._meshes = null;
  39125. for (var id in this._excludedMeshes) {
  39126. var meshHighlight = this._excludedMeshes[id];
  39127. if (meshHighlight) {
  39128. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39129. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39130. }
  39131. }
  39132. this._excludedMeshes = null;
  39133. // Remove from scene
  39134. var index = this._scene.highlightLayers.indexOf(this, 0);
  39135. if (index > -1) {
  39136. this._scene.highlightLayers.splice(index, 1);
  39137. }
  39138. // Callback
  39139. this.onDisposeObservable.notifyObservers(this);
  39140. this.onDisposeObservable.clear();
  39141. this.onBeforeRenderMainTextureObservable.clear();
  39142. this.onBeforeBlurObservable.clear();
  39143. this.onBeforeComposeObservable.clear();
  39144. this.onAfterComposeObservable.clear();
  39145. this.onSizeChangedObservable.clear();
  39146. };
  39147. return HighlightLayer;
  39148. }());
  39149. /**
  39150. * The neutral color used during the preparation of the glow effect.
  39151. * This is black by default as the blend operation is a blend operation.
  39152. */
  39153. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39154. /**
  39155. * Stencil value used for glowing meshes.
  39156. */
  39157. HighlightLayer.glowingMeshStencilReference = 0x02;
  39158. /**
  39159. * Stencil value used for the other meshes in the scene.
  39160. */
  39161. HighlightLayer.normalMeshStencilReference = 0x01;
  39162. BABYLON.HighlightLayer = HighlightLayer;
  39163. })(BABYLON || (BABYLON = {}));
  39164. //# sourceMappingURL=babylon.highlightlayer.js.map
  39165. var BABYLON;
  39166. (function (BABYLON) {
  39167. var SIMDVector3 = (function () {
  39168. function SIMDVector3() {
  39169. }
  39170. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39171. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39172. };
  39173. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39174. var m = transformation.m;
  39175. var m0 = SIMD.Float32x4.load(m, 0);
  39176. var m1 = SIMD.Float32x4.load(m, 4);
  39177. var m2 = SIMD.Float32x4.load(m, 8);
  39178. var m3 = SIMD.Float32x4.load(m, 12);
  39179. 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));
  39180. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39181. result.x = SIMD.Float32x4.extractLane(r, 0);
  39182. result.y = SIMD.Float32x4.extractLane(r, 1);
  39183. result.z = SIMD.Float32x4.extractLane(r, 2);
  39184. };
  39185. return SIMDVector3;
  39186. }());
  39187. var SIMDMatrix = (function () {
  39188. function SIMDMatrix() {
  39189. }
  39190. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39191. var tm = this.m;
  39192. var om = other.m;
  39193. var m0 = SIMD.Float32x4.load(om, 0);
  39194. var m1 = SIMD.Float32x4.load(om, 4);
  39195. var m2 = SIMD.Float32x4.load(om, 8);
  39196. var m3 = SIMD.Float32x4.load(om, 12);
  39197. for (var i = 0; i < 16; i += 4) {
  39198. 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)))));
  39199. }
  39200. return this;
  39201. };
  39202. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39203. var src = this.m;
  39204. var dest = other.m;
  39205. // Load the 4 rows
  39206. var src0 = SIMD.Float32x4.load(src, 0);
  39207. var src1 = SIMD.Float32x4.load(src, 4);
  39208. var src2 = SIMD.Float32x4.load(src, 8);
  39209. var src3 = SIMD.Float32x4.load(src, 12);
  39210. // Transpose the source matrix. Sort of. Not a true transpose operation
  39211. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39212. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39213. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39214. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39215. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39216. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39217. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39218. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39219. // This is a true transposition, but it will lead to an incorrect result
  39220. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39221. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39222. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39223. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39224. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39225. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39226. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39227. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39228. // ----
  39229. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39230. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39231. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39232. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39233. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39234. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39235. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39236. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39237. // ----
  39238. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39239. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39240. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39241. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39242. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39243. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39244. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39245. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39246. // ----
  39247. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39248. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39249. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39250. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39251. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39252. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39253. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39254. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39255. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39256. // ----
  39257. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39258. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39259. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39260. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39261. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39262. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39263. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39264. // ----
  39265. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39266. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39267. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39268. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39269. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39270. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39271. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39272. // ----
  39273. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39274. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39275. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39276. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39277. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39278. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39279. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39280. // Compute determinant
  39281. var det = SIMD.Float32x4.mul(row0, minor0);
  39282. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39283. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39284. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39285. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39286. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39287. // These shuffles aren't necessary if the faulty transposition is done
  39288. // up at the top of this function.
  39289. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39290. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39291. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39292. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39293. // Compute final values by multiplying with 1/det
  39294. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39295. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39296. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39297. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39298. return this;
  39299. };
  39300. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39301. var out = result.m;
  39302. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39303. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39304. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39305. // cc.kmVec3Subtract(f, pCenter, pEye);
  39306. var f = SIMD.Float32x4.sub(center, eye);
  39307. // cc.kmVec3Normalize(f, f);
  39308. var tmp = SIMD.Float32x4.mul(f, f);
  39309. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39310. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39311. // cc.kmVec3Assign(up, pUp);
  39312. // cc.kmVec3Normalize(up, up);
  39313. tmp = SIMD.Float32x4.mul(up, up);
  39314. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39315. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39316. // cc.kmVec3Cross(s, f, up);
  39317. 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)));
  39318. // cc.kmVec3Normalize(s, s);
  39319. tmp = SIMD.Float32x4.mul(s, s);
  39320. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39321. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39322. // cc.kmVec3Cross(u, s, f);
  39323. 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)));
  39324. // cc.kmVec3Normalize(s, s);
  39325. tmp = SIMD.Float32x4.mul(s, s);
  39326. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39327. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39328. var zero = SIMD.Float32x4.splat(0.0);
  39329. s = SIMD.Float32x4.neg(s);
  39330. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39331. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39332. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39333. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39334. 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);
  39335. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39336. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39337. 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)))));
  39338. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39339. 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)))));
  39340. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39341. 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)))));
  39342. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39343. 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)))));
  39344. };
  39345. return SIMDMatrix;
  39346. }());
  39347. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39348. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39349. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39350. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39351. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39352. var SIMDHelper = (function () {
  39353. function SIMDHelper() {
  39354. }
  39355. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39356. get: function () {
  39357. return SIMDHelper._isEnabled;
  39358. },
  39359. enumerable: true,
  39360. configurable: true
  39361. });
  39362. SIMDHelper.DisableSIMD = function () {
  39363. // Replace functions
  39364. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39365. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39366. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39367. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39368. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39369. SIMDHelper._isEnabled = false;
  39370. };
  39371. SIMDHelper.EnableSIMD = function () {
  39372. if (self.SIMD === undefined) {
  39373. return;
  39374. }
  39375. // check if polyfills needed
  39376. if (!self.Math.fround) {
  39377. self.Math.fround = (function (array) { return function (x) {
  39378. return array[0] = x, array[0];
  39379. }; })(new Float32Array(1));
  39380. }
  39381. if (!self.Math.imul) {
  39382. self.Math.imul = function (a, b) {
  39383. var ah = (a >>> 16) & 0xffff;
  39384. var al = a & 0xffff;
  39385. var bh = (b >>> 16) & 0xffff;
  39386. var bl = b & 0xffff;
  39387. // the shift by 0 fixes the sign on the high part
  39388. // the final |0 converts the unsigned value into a signed value
  39389. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39390. };
  39391. }
  39392. // Replace functions
  39393. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39394. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39395. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39396. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39397. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39398. SIMDHelper._isEnabled = true;
  39399. };
  39400. return SIMDHelper;
  39401. }());
  39402. SIMDHelper._isEnabled = false;
  39403. BABYLON.SIMDHelper = SIMDHelper;
  39404. })(BABYLON || (BABYLON = {}));
  39405. //# sourceMappingURL=babylon.math.SIMD.js.map
  39406. var BABYLON;
  39407. (function (BABYLON) {
  39408. /**
  39409. * This class describe a rectangle that were added to the map.
  39410. * You have access to its coordinates either in pixel or normalized (UV)
  39411. */
  39412. var PackedRect = (function () {
  39413. function PackedRect(root, parent, pos, size) {
  39414. this._pos = pos;
  39415. this._size = size;
  39416. this._root = root;
  39417. this._parent = parent;
  39418. this._contentSize = null;
  39419. this._bottomNode = null;
  39420. this._leftNode = null;
  39421. this._initialSize = null;
  39422. this._rightNode = null;
  39423. }
  39424. Object.defineProperty(PackedRect.prototype, "pos", {
  39425. /**
  39426. * @returns the position of this node into the map
  39427. */
  39428. get: function () {
  39429. return this._pos;
  39430. },
  39431. enumerable: true,
  39432. configurable: true
  39433. });
  39434. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39435. /**
  39436. * @returns the size of the rectangle this node handles
  39437. */
  39438. get: function () {
  39439. return this._contentSize;
  39440. },
  39441. enumerable: true,
  39442. configurable: true
  39443. });
  39444. Object.defineProperty(PackedRect.prototype, "UVs", {
  39445. /**
  39446. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39447. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39448. */
  39449. get: function () {
  39450. return this.getUVsForCustomSize(this._root._size);
  39451. },
  39452. enumerable: true,
  39453. configurable: true
  39454. });
  39455. /**
  39456. * 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.
  39457. * This method will return the UVs for this part by given the custom size of what you really use
  39458. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39459. */
  39460. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39461. var mainWidth = this._root._size.width;
  39462. var mainHeight = this._root._size.height;
  39463. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39464. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39465. var uvs = new Array();
  39466. uvs.push(topLeft);
  39467. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39468. uvs.push(rightBottom);
  39469. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39470. return uvs;
  39471. };
  39472. /**
  39473. * Free this rectangle from the map.
  39474. * Call this method when you no longer need the rectangle to be in the map.
  39475. */
  39476. PackedRect.prototype.freeContent = function () {
  39477. if (!this.contentSize) {
  39478. return;
  39479. }
  39480. this._contentSize = null;
  39481. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39482. this.attemptDefrag();
  39483. };
  39484. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39485. get: function () {
  39486. return this._contentSize != null || this._leftNode != null;
  39487. },
  39488. enumerable: true,
  39489. configurable: true
  39490. });
  39491. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39492. var node = this.findNode(contentSize);
  39493. // Not enough space...
  39494. if (!node) {
  39495. return null;
  39496. }
  39497. node.splitNode(contentSize);
  39498. return node;
  39499. };
  39500. PackedRect.prototype.findNode = function (size) {
  39501. var resNode = null;
  39502. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39503. if (this.isUsed) {
  39504. if (this._leftNode) {
  39505. resNode = this._leftNode.findNode(size);
  39506. }
  39507. if (!resNode && this._rightNode) {
  39508. resNode = this._rightNode.findNode(size);
  39509. }
  39510. if (!resNode && this._bottomNode) {
  39511. resNode = this._bottomNode.findNode(size);
  39512. }
  39513. }
  39514. else if (this._initialSize) {
  39515. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39516. resNode = this;
  39517. }
  39518. else {
  39519. return null;
  39520. }
  39521. }
  39522. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39523. resNode = this;
  39524. }
  39525. return resNode;
  39526. };
  39527. PackedRect.prototype.splitNode = function (contentSize) {
  39528. // 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)
  39529. if (!this._contentSize && this._initialSize) {
  39530. this._contentSize = contentSize.clone();
  39531. 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));
  39532. return this._leftNode.splitNode(contentSize);
  39533. }
  39534. else {
  39535. this._contentSize = contentSize.clone();
  39536. this._initialSize = contentSize.clone();
  39537. if (contentSize.width !== this._size.width) {
  39538. 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));
  39539. }
  39540. if (contentSize.height !== this._size.height) {
  39541. 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));
  39542. }
  39543. return this;
  39544. }
  39545. };
  39546. PackedRect.prototype.attemptDefrag = function () {
  39547. if (!this.isUsed && this.isRecursiveFree) {
  39548. this.clearNode();
  39549. if (this._parent) {
  39550. this._parent.attemptDefrag();
  39551. }
  39552. }
  39553. };
  39554. PackedRect.prototype.clearNode = function () {
  39555. this._initialSize = null;
  39556. this._rightNode = null;
  39557. this._bottomNode = null;
  39558. };
  39559. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39560. get: function () {
  39561. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39562. },
  39563. enumerable: true,
  39564. configurable: true
  39565. });
  39566. PackedRect.prototype.evalFreeSize = function (size) {
  39567. var levelSize = 0;
  39568. if (!this.isUsed) {
  39569. if (this._initialSize) {
  39570. levelSize = this._initialSize.surface;
  39571. }
  39572. else {
  39573. levelSize = this._size.surface;
  39574. }
  39575. }
  39576. if (this._rightNode) {
  39577. levelSize += this._rightNode.evalFreeSize(0);
  39578. }
  39579. if (this._bottomNode) {
  39580. levelSize += this._bottomNode.evalFreeSize(0);
  39581. }
  39582. return levelSize + size;
  39583. };
  39584. return PackedRect;
  39585. }());
  39586. BABYLON.PackedRect = PackedRect;
  39587. /**
  39588. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39589. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39590. * 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.
  39591. */
  39592. var RectPackingMap = (function (_super) {
  39593. __extends(RectPackingMap, _super);
  39594. /**
  39595. * Create an instance of the object with a dimension using the given size
  39596. * @param size The dimension of the rectangle that will contain all the sub ones.
  39597. */
  39598. function RectPackingMap(size) {
  39599. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  39600. _this._root = _this;
  39601. return _this;
  39602. }
  39603. /**
  39604. * Add a rectangle, finding the best location to store it into the map
  39605. * @param size the dimension of the rectangle to store
  39606. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39607. */
  39608. RectPackingMap.prototype.addRect = function (size) {
  39609. var node = this.findAndSplitNode(size);
  39610. return node;
  39611. };
  39612. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39613. /**
  39614. * Return the current space free normalized between [0;1]
  39615. * @returns {}
  39616. */
  39617. get: function () {
  39618. var freeSize = 0;
  39619. freeSize = this.evalFreeSize(freeSize);
  39620. return freeSize / (this._size.width * this._size.height);
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. return RectPackingMap;
  39626. }(PackedRect));
  39627. BABYLON.RectPackingMap = RectPackingMap;
  39628. })(BABYLON || (BABYLON = {}));
  39629. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39630. var BABYLON;
  39631. (function (BABYLON) {
  39632. var DynamicFloatArrayElementInfo = (function () {
  39633. function DynamicFloatArrayElementInfo() {
  39634. }
  39635. return DynamicFloatArrayElementInfo;
  39636. }());
  39637. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39638. /**
  39639. * 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.
  39640. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39641. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39642. * 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.
  39643. * 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.
  39644. * 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".
  39645. */
  39646. var DynamicFloatArray = (function () {
  39647. /**
  39648. * Construct an instance of the dynamic float array
  39649. * @param stride size of one element in float (i.e. not bytes!)
  39650. * @param initialElementCount the number of available entries at construction
  39651. */
  39652. function DynamicFloatArray(stride, initialElementCount) {
  39653. this.compareValueOffset = null;
  39654. this.sortingAscending = true;
  39655. this._stride = stride;
  39656. this.buffer = new Float32Array(stride * initialElementCount);
  39657. this._lastUsed = 0;
  39658. this._firstFree = 0;
  39659. this._allEntries = new Array(initialElementCount);
  39660. this._freeEntries = new Array(initialElementCount);
  39661. for (var i = 0; i < initialElementCount; i++) {
  39662. var element = new DynamicFloatArrayElementInfo();
  39663. element.offset = i * stride;
  39664. this._allEntries[i] = element;
  39665. this._freeEntries[initialElementCount - i - 1] = element;
  39666. }
  39667. }
  39668. /**
  39669. * Allocate an element in the array.
  39670. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39671. * Beware, this offset may change when you call pack()
  39672. */
  39673. DynamicFloatArray.prototype.allocElement = function () {
  39674. if (this._freeEntries.length === 0) {
  39675. this._growBuffer();
  39676. }
  39677. var el = this._freeEntries.pop();
  39678. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39679. if (el.offset === this._firstFree) {
  39680. if (this._freeEntries.length > 0) {
  39681. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39682. }
  39683. else {
  39684. this._firstFree += this._stride;
  39685. }
  39686. }
  39687. return el;
  39688. };
  39689. /**
  39690. * Free the element corresponding to the given element info
  39691. * @param elInfo the element that describe the allocated element
  39692. */
  39693. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39694. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39695. this._freeEntries.push(elInfo);
  39696. };
  39697. /**
  39698. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39699. * 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().
  39700. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39701. */
  39702. DynamicFloatArray.prototype.pack = function () {
  39703. // no free slot? no need to pack
  39704. if (this._freeEntries.length === 0) {
  39705. return this.buffer;
  39706. }
  39707. // If the buffer is already packed the last used will always be lower than the first free
  39708. // 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.
  39709. if (this._lastUsed < this._firstFree) {
  39710. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39711. return elementsBuffer_1;
  39712. }
  39713. var s = this._stride;
  39714. // 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
  39715. var lastFree = new DynamicFloatArrayElementInfo();
  39716. lastFree.offset = this.totalElementCount * s;
  39717. this._freeEntries.push(lastFree);
  39718. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39719. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39720. var firstFreeSlotOffset = sortedFree[0].offset;
  39721. var freeZoneSize = 1;
  39722. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39723. var prevOffset = sortedFree[0].offset;
  39724. for (var i = 1; i < sortedFree.length; i++) {
  39725. // 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
  39726. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39727. break;
  39728. }
  39729. var curFree = sortedFree[i];
  39730. var curOffset = curFree.offset;
  39731. // Compute the distance between this offset and the previous
  39732. var distance = curOffset - prevOffset;
  39733. // If the distance is the stride size, they are adjacent, it good, move to the next
  39734. if (distance === s) {
  39735. // Free zone is one element bigger
  39736. ++freeZoneSize;
  39737. // as we're about to iterate to the next, the cur becomes the previous...
  39738. prevOffset = curOffset;
  39739. continue;
  39740. }
  39741. // Distance is bigger, which means there's x element between the previous free and this one
  39742. var usedRange = (distance / s) - 1;
  39743. // Two cases the free zone is smaller than the data to move or bigger
  39744. // Copy what can fit in the free zone
  39745. var curMoveOffset = curOffset - s;
  39746. var copyCount = Math.min(freeZoneSize, usedRange);
  39747. for (var j = 0; j < copyCount; j++) {
  39748. var freeI = firstFreeSlotOffset / s;
  39749. var curI = curMoveOffset / s;
  39750. var moveEl = sortedAll[curI];
  39751. this._moveElement(moveEl, firstFreeSlotOffset);
  39752. var replacedEl = sortedAll[freeI];
  39753. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39754. replacedEl.offset = curMoveOffset;
  39755. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39756. sortedAll[freeI] = moveEl;
  39757. sortedAll[curI] = replacedEl;
  39758. curMoveOffset -= s;
  39759. firstFreeSlotOffset += s;
  39760. }
  39761. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39762. if (freeZoneSize <= usedRange) {
  39763. firstFreeSlotOffset = curMoveOffset + s;
  39764. freeZoneSize = 1 + copyCount;
  39765. }
  39766. else {
  39767. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39768. }
  39769. // as we're about to iterate to the next, the cur becomes the previous...
  39770. prevOffset = curOffset;
  39771. }
  39772. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39773. this._lastUsed = firstFreeSlotOffset - s;
  39774. this._firstFree = firstFreeSlotOffset;
  39775. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39776. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39777. this._allEntries = sortedAll;
  39778. return elementsBuffer;
  39779. };
  39780. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39781. for (var i = 0; i < this._stride; i++) {
  39782. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39783. }
  39784. element.offset = destOffset;
  39785. };
  39786. DynamicFloatArray.prototype._growBuffer = function () {
  39787. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39788. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39789. var newBuffer = new Float32Array(newElCount * this._stride);
  39790. newBuffer.set(this.buffer);
  39791. var curCount = this.totalElementCount;
  39792. var addedCount = newElCount - this.totalElementCount;
  39793. for (var i = 0; i < addedCount; i++) {
  39794. var element = new DynamicFloatArrayElementInfo();
  39795. element.offset = (curCount + i) * this.stride;
  39796. this._allEntries.push(element);
  39797. this._freeEntries[addedCount - i - 1] = element;
  39798. }
  39799. this._firstFree = curCount * this.stride;
  39800. this.buffer = newBuffer;
  39801. };
  39802. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39803. /**
  39804. * Get the total count of entries that can fit in the current buffer
  39805. * @returns the elements count
  39806. */
  39807. get: function () {
  39808. return this._allEntries.length;
  39809. },
  39810. enumerable: true,
  39811. configurable: true
  39812. });
  39813. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39814. /**
  39815. * Get the count of free entries that can still be allocated without resizing the buffer
  39816. * @returns the free elements count
  39817. */
  39818. get: function () {
  39819. return this._freeEntries.length;
  39820. },
  39821. enumerable: true,
  39822. configurable: true
  39823. });
  39824. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39825. /**
  39826. * Get the count of allocated elements
  39827. * @returns the allocated elements count
  39828. */
  39829. get: function () {
  39830. return this._allEntries.length - this._freeEntries.length;
  39831. },
  39832. enumerable: true,
  39833. configurable: true
  39834. });
  39835. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39836. /**
  39837. * Return the size of one element in float
  39838. * @returns the size in float
  39839. */
  39840. get: function () {
  39841. return this._stride;
  39842. },
  39843. enumerable: true,
  39844. configurable: true
  39845. });
  39846. DynamicFloatArray.prototype.sort = function () {
  39847. var _this = this;
  39848. if (!this.compareValueOffset) {
  39849. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39850. }
  39851. var count = this.usedElementCount;
  39852. // Do we have to (re)create the sort table?
  39853. if (!this._sortTable || this._sortTable.length < count) {
  39854. // 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...
  39855. var newCount = Math.min(this.totalElementCount, count * 2);
  39856. this._sortTable = new Array(newCount);
  39857. }
  39858. if (!this._sortedTable || this._sortedTable.length !== count) {
  39859. this._sortedTable = new Array(count);
  39860. }
  39861. // Because, you know...
  39862. this.pack();
  39863. //let stride = this.stride;
  39864. //for (let i = 0; i < count; i++) {
  39865. // let si = this._sortTable[i];
  39866. // if (!si) {
  39867. // si = new SortInfo();
  39868. // this._sortTable[i] = si;
  39869. // }
  39870. // si.entry = this._allEntries[i];
  39871. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39872. // si.swapedOffset = null;
  39873. // this._sortedTable[i] = si;
  39874. //}
  39875. var curOffset = 0;
  39876. var stride = this.stride;
  39877. for (var i = 0; i < count; i++, curOffset += stride) {
  39878. var si = this._sortTable[i];
  39879. if (!si) {
  39880. si = new SortInfo();
  39881. this._sortTable[i] = si;
  39882. }
  39883. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39884. si.offset = curOffset;
  39885. si.swapedOffset = null;
  39886. this._sortedTable[i] = si;
  39887. }
  39888. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39889. if (this.sortingAscending) {
  39890. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39891. }
  39892. else {
  39893. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39894. }
  39895. var swapElements = function (src, dst) {
  39896. for (var i = 0; i < stride; i++) {
  39897. var tps = _this.buffer[dst + i];
  39898. _this.buffer[dst + i] = _this.buffer[src + i];
  39899. _this.buffer[src + i] = tps;
  39900. }
  39901. };
  39902. // 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:
  39903. // 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),
  39904. // and I still want something with a good algorithm complexity.
  39905. // 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,
  39906. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39907. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39908. // 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
  39909. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39910. // 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
  39911. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39912. for (var i = 0; i < count; i++) {
  39913. // Get the element to move
  39914. var sourceSI = this._sortedTable[i];
  39915. var destSI = this._sortTable[i];
  39916. var sourceOff = sourceSI.offset;
  39917. // If the source changed location, find the new one
  39918. if (sourceSI.swapedOffset) {
  39919. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39920. var curSI = sourceSI;
  39921. while (curSI.swapedOffset) {
  39922. curSI = this._sortTable[curSI.swapedOffset / stride];
  39923. }
  39924. // Finally get the right location
  39925. sourceOff = curSI.offset;
  39926. }
  39927. // Tag the element being replaced with its new location
  39928. destSI.swapedOffset = sourceOff;
  39929. // Swap elements (only if needed)
  39930. if (sourceOff !== destSI.offset) {
  39931. swapElements(sourceOff, destSI.offset);
  39932. }
  39933. // Update the offset in the corresponding DFAE
  39934. //sourceSI.entry.offset = destSI.entry.offset;
  39935. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39936. }
  39937. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39938. return true;
  39939. };
  39940. return DynamicFloatArray;
  39941. }());
  39942. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39943. var SortInfo = (function () {
  39944. function SortInfo() {
  39945. this.compareData = this.offset = this.swapedOffset = null;
  39946. }
  39947. return SortInfo;
  39948. }());
  39949. })(BABYLON || (BABYLON = {}));
  39950. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39951. var BABYLON;
  39952. (function (BABYLON) {
  39953. /**
  39954. * This class given information about a given character.
  39955. */
  39956. var CharInfo = (function () {
  39957. function CharInfo() {
  39958. }
  39959. return CharInfo;
  39960. }());
  39961. BABYLON.CharInfo = CharInfo;
  39962. var FontTexture = (function (_super) {
  39963. __extends(FontTexture, _super);
  39964. /**
  39965. * Create a new instance of the FontTexture class
  39966. * @param name the name of the texture
  39967. * @param font the font to use, use the W3C CSS notation
  39968. * @param scene the scene that owns the texture
  39969. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  39970. * @param samplingMode the texture sampling mode
  39971. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  39972. */
  39973. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39974. if (maxCharCount === void 0) { maxCharCount = 200; }
  39975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39976. if (superSample === void 0) { superSample = false; }
  39977. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39978. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  39979. _this._charInfos = {};
  39980. _this._curCharCount = 0;
  39981. _this._lastUpdateCharCount = -1;
  39982. _this._usedCounter = 1;
  39983. _this.name = name;
  39984. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39985. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39986. _this._sdfScale = 8;
  39987. _this._signedDistanceField = signedDistanceField;
  39988. _this._superSample = false;
  39989. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39990. if (superSample || signedDistanceField) {
  39991. var sfont = _this.getSuperSampleFont(font);
  39992. if (sfont) {
  39993. _this._superSample = true;
  39994. font = sfont;
  39995. }
  39996. }
  39997. // First canvas creation to determine the size of the texture to create
  39998. _this._canvas = document.createElement("canvas");
  39999. _this._context = _this._canvas.getContext("2d");
  40000. _this._context.font = font;
  40001. _this._context.fillStyle = "white";
  40002. _this._context.textBaseline = "top";
  40003. _this._cachedFontId = null;
  40004. var res = _this.getFontHeight(font);
  40005. _this._lineHeightSuper = res.height + 4;
  40006. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  40007. _this._offset = res.offset - 1;
  40008. _this._xMargin = 1 + Math.ceil(_this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  40009. _this._yMargin = _this._xMargin;
  40010. var maxCharWidth = _this._context.measureText("W").width;
  40011. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  40012. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  40013. // This is an approximate size, but should always be able to fit at least the maxCharCount
  40014. var totalEstSurface = (_this._lineHeightSuper + _this._yMargin) * (maxCharWidth + _this._xMargin) * maxCharCount;
  40015. var edge = Math.sqrt(totalEstSurface);
  40016. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  40017. // Create the texture that will store the font characters
  40018. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  40019. var textureSize = _this.getSize();
  40020. _this.hasAlpha = _this._signedDistanceField === false;
  40021. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  40022. _this._canvas = document.createElement("canvas");
  40023. _this._canvas.width = textureSize.width;
  40024. _this._canvas.height = textureSize.height;
  40025. _this._context = _this._canvas.getContext("2d");
  40026. _this._context.textBaseline = "top";
  40027. _this._context.font = font;
  40028. _this._context.fillStyle = "white";
  40029. _this._context.imageSmoothingEnabled = false;
  40030. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  40031. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  40032. // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
  40033. // So you can see this context as an intermediate one, because it is.
  40034. if (_this._signedDistanceField) {
  40035. var sdfC = document.createElement("canvas");
  40036. var s = _this._sdfScale;
  40037. sdfC.width = maxCharWidth * s;
  40038. sdfC.height = _this._lineHeightSuper * s;
  40039. var sdfCtx = sdfC.getContext("2d");
  40040. sdfCtx.scale(s, s);
  40041. sdfCtx.textBaseline = "top";
  40042. sdfCtx.font = font;
  40043. sdfCtx.fillStyle = "white";
  40044. sdfCtx.imageSmoothingEnabled = false;
  40045. _this._sdfCanvas = sdfC;
  40046. _this._sdfContext = sdfCtx;
  40047. }
  40048. _this._currentFreePosition = BABYLON.Vector2.Zero();
  40049. // Add the basic ASCII based characters
  40050. for (var i = 0x20; i < 0x7F; i++) {
  40051. var c = String.fromCharCode(i);
  40052. _this.getChar(c);
  40053. }
  40054. _this.update();
  40055. return _this;
  40056. }
  40057. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  40058. get: function () {
  40059. return this._superSample;
  40060. },
  40061. enumerable: true,
  40062. configurable: true
  40063. });
  40064. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  40065. get: function () {
  40066. return this._signedDistanceField;
  40067. },
  40068. enumerable: true,
  40069. configurable: true
  40070. });
  40071. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  40072. get: function () {
  40073. return this._spaceWidth;
  40074. },
  40075. enumerable: true,
  40076. configurable: true
  40077. });
  40078. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  40079. get: function () {
  40080. return this._lineHeight;
  40081. },
  40082. enumerable: true,
  40083. configurable: true
  40084. });
  40085. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40086. if (supersample === void 0) { supersample = false; }
  40087. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40088. var s = scene;
  40089. if (!s.__fontTextureCache__) {
  40090. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  40091. }
  40092. var dic = s.__fontTextureCache__;
  40093. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40094. var ft = dic.get(lfn);
  40095. if (ft) {
  40096. ++ft._usedCounter;
  40097. return ft;
  40098. }
  40099. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  40100. ft._cachedFontId = lfn;
  40101. dic.add(lfn, ft);
  40102. return ft;
  40103. };
  40104. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40105. if (supersample === void 0) { supersample = false; }
  40106. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40107. var s = scene;
  40108. var dic = s.__fontTextureCache__;
  40109. if (!dic) {
  40110. return;
  40111. }
  40112. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40113. var font = dic.get(lfn);
  40114. if (--font._usedCounter === 0) {
  40115. dic.remove(lfn);
  40116. font.dispose();
  40117. }
  40118. };
  40119. /**
  40120. * Make sure the given char is present in the font map.
  40121. * @param char the character to get or add
  40122. * @return the CharInfo instance corresponding to the given character
  40123. */
  40124. FontTexture.prototype.getChar = function (char) {
  40125. if (char.length !== 1) {
  40126. return null;
  40127. }
  40128. var info = this._charInfos[char];
  40129. if (info) {
  40130. return info;
  40131. }
  40132. info = new CharInfo();
  40133. var measure = this._context.measureText(char);
  40134. var textureSize = this.getSize();
  40135. // we reached the end of the current line?
  40136. var width = Math.round(measure.width);
  40137. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40138. this._currentFreePosition.x = 0;
  40139. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40140. // No more room?
  40141. if (this._currentFreePosition.y > textureSize.height) {
  40142. return this.getChar("!");
  40143. }
  40144. }
  40145. // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
  40146. if (this._signedDistanceField) {
  40147. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40148. this._sdfContext.fillText(char, 0, -this._offset);
  40149. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40150. var res = this._computeSDFChar(data);
  40151. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40152. }
  40153. else {
  40154. // Draw the character in the HTML canvas
  40155. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40156. }
  40157. // Fill the CharInfo object
  40158. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40159. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40160. if (this._signedDistanceField) {
  40161. var off = 1 / textureSize.width;
  40162. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40163. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40164. }
  40165. info.charWidth = this._superSample ? (width / 2) : width;
  40166. // Add the info structure
  40167. this._charInfos[char] = info;
  40168. this._curCharCount++;
  40169. // Set the next position
  40170. this._currentFreePosition.x += width + this._xMargin;
  40171. return info;
  40172. };
  40173. FontTexture.prototype._computeSDFChar = function (source) {
  40174. var scl = this._sdfScale;
  40175. var sw = source.width;
  40176. var sh = source.height;
  40177. var dw = sw / scl;
  40178. var dh = sh / scl;
  40179. var roffx = 0;
  40180. var roffy = 0;
  40181. // We shouldn't look beyond half of the biggest between width and height
  40182. var radius = scl;
  40183. var br = radius - 1;
  40184. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40185. var sx = dx * scl;
  40186. var sy = dy * scl;
  40187. // Looking out of the area? return true to make the test going on
  40188. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40189. return true;
  40190. }
  40191. // Get the pixel we want
  40192. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40193. var res = (val > 0) === lookVis;
  40194. if (!res) {
  40195. roffx = offX;
  40196. roffy = offY;
  40197. }
  40198. return res;
  40199. };
  40200. var lookupArea = function (dx, dy, lookVis) {
  40201. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  40202. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40203. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40204. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40205. lookupSrc(dx, dy, br, 0, lookVis)) {
  40206. return 0;
  40207. }
  40208. for (var i = 1; i <= radius; i++) {
  40209. // Quick test N, S, W, E
  40210. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  40211. return i * i; // Squared Distance is simple to compute in this case
  40212. }
  40213. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40214. for (var j = 1; j <= i; j++) {
  40215. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40216. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40217. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40218. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40219. // We found the nearest texel having and opposite state, store the squared length
  40220. var res_1 = (i * i) + (j * j);
  40221. var count = 1;
  40222. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  40223. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40224. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40225. ++count;
  40226. }
  40227. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40228. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40229. ++count;
  40230. }
  40231. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40232. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40233. ++count;
  40234. }
  40235. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40236. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40237. ++count;
  40238. }
  40239. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40240. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40241. ++count;
  40242. }
  40243. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40244. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40245. ++count;
  40246. }
  40247. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40248. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40249. ++count;
  40250. }
  40251. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40252. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40253. ++count;
  40254. }
  40255. // Compute the average based on the accumulated distance
  40256. return res_1 / count;
  40257. }
  40258. }
  40259. }
  40260. return 0;
  40261. };
  40262. var tmp = new Array(dw * dh);
  40263. for (var y = 0; y < dh; y++) {
  40264. for (var x = 0; x < dw; x++) {
  40265. var curState = lookupSrc(x, y, 0, 0, true);
  40266. var d = lookupArea(x, y, curState);
  40267. if (d === 0) {
  40268. d = radius * radius * 2;
  40269. }
  40270. tmp[(y * dw) + x] = curState ? d : -d;
  40271. }
  40272. }
  40273. var res = this._context.createImageData(dw, dh);
  40274. var size = dw * dh;
  40275. for (var j = 0; j < size; j++) {
  40276. var d = tmp[j];
  40277. var sign = (d < 0) ? -1 : 1;
  40278. d = Math.sqrt(Math.abs(d)) * sign;
  40279. d *= 127.5 / radius;
  40280. d += 127.5;
  40281. if (d < 0) {
  40282. d = 0;
  40283. }
  40284. else if (d > 255) {
  40285. d = 255;
  40286. }
  40287. d += 0.5;
  40288. res.data[j * 4 + 0] = d;
  40289. res.data[j * 4 + 1] = d;
  40290. res.data[j * 4 + 2] = d;
  40291. res.data[j * 4 + 3] = 255;
  40292. }
  40293. return res;
  40294. };
  40295. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40296. if (tabulationSize === void 0) { tabulationSize = 4; }
  40297. var maxWidth = 0;
  40298. var curWidth = 0;
  40299. var lineCount = 1;
  40300. var charxpos = 0;
  40301. // Parse each char of the string
  40302. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40303. var char = text_1[_i];
  40304. // Next line feed?
  40305. if (char === "\n") {
  40306. maxWidth = Math.max(maxWidth, curWidth);
  40307. charxpos = 0;
  40308. curWidth = 0;
  40309. ++lineCount;
  40310. continue;
  40311. }
  40312. // Tabulation ?
  40313. if (char === "\t") {
  40314. var nextPos = charxpos + tabulationSize;
  40315. nextPos = nextPos - (nextPos % tabulationSize);
  40316. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40317. charxpos = nextPos;
  40318. continue;
  40319. }
  40320. if (char < " ") {
  40321. continue;
  40322. }
  40323. curWidth += this.getChar(char).charWidth;
  40324. ++charxpos;
  40325. }
  40326. maxWidth = Math.max(maxWidth, curWidth);
  40327. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40328. };
  40329. FontTexture.prototype.getSuperSampleFont = function (font) {
  40330. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40331. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  40332. var res = font.toLocaleLowerCase().match(regex);
  40333. if (res == null) {
  40334. return null;
  40335. }
  40336. var size = parseInt(res[4]);
  40337. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40338. var newFont = "";
  40339. for (var j = 1; j < res.length; j++) {
  40340. if (res[j] != null) {
  40341. newFont += res[j] + " ";
  40342. }
  40343. }
  40344. return newFont;
  40345. };
  40346. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40347. FontTexture.prototype.getFontHeight = function (font) {
  40348. var fontDraw = document.createElement("canvas");
  40349. var ctx = fontDraw.getContext('2d');
  40350. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40351. ctx.textBaseline = 'top';
  40352. ctx.fillStyle = 'white';
  40353. ctx.font = font;
  40354. ctx.fillText('jH|', 0, 0);
  40355. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40356. var start = -1;
  40357. var end = -1;
  40358. for (var row = 0; row < fontDraw.height; row++) {
  40359. for (var column = 0; column < fontDraw.width; column++) {
  40360. var index = (row * fontDraw.width + column) * 4;
  40361. if (pixels[index] === 0) {
  40362. if (column === fontDraw.width - 1 && start !== -1) {
  40363. end = row;
  40364. row = fontDraw.height;
  40365. break;
  40366. }
  40367. continue;
  40368. }
  40369. else {
  40370. if (start === -1) {
  40371. start = row;
  40372. }
  40373. break;
  40374. }
  40375. }
  40376. }
  40377. return { height: (end - start) + 1, offset: start - 1 };
  40378. };
  40379. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40380. get: function () {
  40381. return false;
  40382. },
  40383. enumerable: true,
  40384. configurable: true
  40385. });
  40386. FontTexture.prototype.getContext = function () {
  40387. return this._context;
  40388. };
  40389. /**
  40390. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40391. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40392. */
  40393. FontTexture.prototype.update = function () {
  40394. // Update only if there's new char added since the previous update
  40395. if (this._lastUpdateCharCount < this._curCharCount) {
  40396. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40397. this._lastUpdateCharCount = this._curCharCount;
  40398. }
  40399. };
  40400. // cloning should be prohibited, there's no point to duplicate this texture at all
  40401. FontTexture.prototype.clone = function () {
  40402. return null;
  40403. };
  40404. /**
  40405. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40406. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40407. */
  40408. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40409. ++this._usedCounter;
  40410. };
  40411. /**
  40412. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40413. */
  40414. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40415. var s = this.getScene();
  40416. var dic = s.__fontTextureCache__;
  40417. if (!dic) {
  40418. return;
  40419. }
  40420. if (--this._usedCounter === 0) {
  40421. dic.remove(this._cachedFontId);
  40422. this.dispose();
  40423. }
  40424. };
  40425. return FontTexture;
  40426. }(BABYLON.Texture));
  40427. BABYLON.FontTexture = FontTexture;
  40428. })(BABYLON || (BABYLON = {}));
  40429. //# sourceMappingURL=babylon.fontTexture.js.map
  40430. var BABYLON;
  40431. (function (BABYLON) {
  40432. var MapTexture = (function (_super) {
  40433. __extends(MapTexture, _super);
  40434. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40436. if (useMipMap === void 0) { useMipMap = false; }
  40437. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40438. _this.name = name;
  40439. _this._size = size;
  40440. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40441. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40442. // Create the rectPackMap that will allocate portion of the texture
  40443. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40444. // Create the texture that will store the content
  40445. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40446. return _this;
  40447. }
  40448. /**
  40449. * Allocate a rectangle of a given size in the texture map
  40450. * @param size the size of the rectangle to allocation
  40451. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40452. */
  40453. MapTexture.prototype.allocateRect = function (size) {
  40454. return this._rectPackingMap.addRect(size);
  40455. };
  40456. /**
  40457. * Free a given rectangle from the texture map
  40458. * @param rectInfo the instance corresponding to the rect to free.
  40459. */
  40460. MapTexture.prototype.freeRect = function (rectInfo) {
  40461. if (rectInfo) {
  40462. rectInfo.freeContent();
  40463. }
  40464. };
  40465. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40466. /**
  40467. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40468. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40469. * @returns {}
  40470. */
  40471. get: function () {
  40472. return this._rectPackingMap.freeSpace;
  40473. },
  40474. enumerable: true,
  40475. configurable: true
  40476. });
  40477. /**
  40478. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40479. * 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.
  40480. * Don't forget to call unbindTexture when you're done rendering
  40481. * @param rect the zone to render to
  40482. * @param clear true to clear the portion's color/depth data
  40483. */
  40484. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40485. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40486. };
  40487. /**
  40488. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40489. * 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.
  40490. * Don't forget to call unbindTexture when you're done rendering
  40491. * @param pos the position into the texture
  40492. * @param size the portion to fit the clip space to
  40493. * @param clear true to clear the portion's color/depth data
  40494. */
  40495. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40496. var engine = this.getScene().getEngine();
  40497. engine.bindFramebuffer(this._texture);
  40498. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40499. if (clear) {
  40500. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40501. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40502. }
  40503. };
  40504. /**
  40505. * Unbind the texture map from the rendering engine.
  40506. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40507. * @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.
  40508. */
  40509. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40510. // Dump ?
  40511. if (dumpForDebug) {
  40512. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40513. }
  40514. var engine = this.getScene().getEngine();
  40515. if (this._replacedViewport) {
  40516. engine.setViewport(this._replacedViewport);
  40517. this._replacedViewport = null;
  40518. }
  40519. engine.unBindFramebuffer(this._texture);
  40520. };
  40521. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40522. get: function () {
  40523. return false;
  40524. },
  40525. enumerable: true,
  40526. configurable: true
  40527. });
  40528. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40529. // Anyway, there's not much point to use this method for this kind of texture I guess
  40530. MapTexture.prototype.clone = function () {
  40531. return null;
  40532. };
  40533. return MapTexture;
  40534. }(BABYLON.Texture));
  40535. BABYLON.MapTexture = MapTexture;
  40536. })(BABYLON || (BABYLON = {}));
  40537. //# sourceMappingURL=babylon.mapTexture.js.map
  40538. var BABYLON;
  40539. (function (BABYLON) {
  40540. var ShaderMaterial = (function (_super) {
  40541. __extends(ShaderMaterial, _super);
  40542. function ShaderMaterial(name, scene, shaderPath, options) {
  40543. var _this = _super.call(this, name, scene) || this;
  40544. _this._textures = {};
  40545. _this._textureArrays = {};
  40546. _this._floats = {};
  40547. _this._floatsArrays = {};
  40548. _this._colors3 = {};
  40549. _this._colors4 = {};
  40550. _this._vectors2 = {};
  40551. _this._vectors3 = {};
  40552. _this._vectors4 = {};
  40553. _this._matrices = {};
  40554. _this._matrices3x3 = {};
  40555. _this._matrices2x2 = {};
  40556. _this._vectors3Arrays = {};
  40557. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40558. _this._shaderPath = shaderPath;
  40559. options.needAlphaBlending = options.needAlphaBlending || false;
  40560. options.needAlphaTesting = options.needAlphaTesting || false;
  40561. options.attributes = options.attributes || ["position", "normal", "uv"];
  40562. options.uniforms = options.uniforms || ["worldViewProjection"];
  40563. options.samplers = options.samplers || [];
  40564. options.defines = options.defines || [];
  40565. _this._options = options;
  40566. return _this;
  40567. }
  40568. ShaderMaterial.prototype.getClassName = function () {
  40569. return "ShaderMaterial";
  40570. };
  40571. ShaderMaterial.prototype.needAlphaBlending = function () {
  40572. return this._options.needAlphaBlending;
  40573. };
  40574. ShaderMaterial.prototype.needAlphaTesting = function () {
  40575. return this._options.needAlphaTesting;
  40576. };
  40577. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40578. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40579. this._options.uniforms.push(uniformName);
  40580. }
  40581. };
  40582. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40583. if (this._options.samplers.indexOf(name) === -1) {
  40584. this._options.samplers.push(name);
  40585. }
  40586. this._textures[name] = texture;
  40587. return this;
  40588. };
  40589. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40590. if (this._options.samplers.indexOf(name) === -1) {
  40591. this._options.samplers.push(name);
  40592. }
  40593. this._checkUniform(name);
  40594. this._textureArrays[name] = textures;
  40595. return this;
  40596. };
  40597. ShaderMaterial.prototype.setFloat = function (name, value) {
  40598. this._checkUniform(name);
  40599. this._floats[name] = value;
  40600. return this;
  40601. };
  40602. ShaderMaterial.prototype.setFloats = function (name, value) {
  40603. this._checkUniform(name);
  40604. this._floatsArrays[name] = value;
  40605. return this;
  40606. };
  40607. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40608. this._checkUniform(name);
  40609. this._colors3[name] = value;
  40610. return this;
  40611. };
  40612. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40613. this._checkUniform(name);
  40614. this._colors4[name] = value;
  40615. return this;
  40616. };
  40617. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40618. this._checkUniform(name);
  40619. this._vectors2[name] = value;
  40620. return this;
  40621. };
  40622. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40623. this._checkUniform(name);
  40624. this._vectors3[name] = value;
  40625. return this;
  40626. };
  40627. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40628. this._checkUniform(name);
  40629. this._vectors4[name] = value;
  40630. return this;
  40631. };
  40632. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40633. this._checkUniform(name);
  40634. this._matrices[name] = value;
  40635. return this;
  40636. };
  40637. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40638. this._checkUniform(name);
  40639. this._matrices3x3[name] = value;
  40640. return this;
  40641. };
  40642. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40643. this._checkUniform(name);
  40644. this._matrices2x2[name] = value;
  40645. return this;
  40646. };
  40647. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40648. this._checkUniform(name);
  40649. this._vectors3Arrays[name] = value;
  40650. return this;
  40651. };
  40652. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40653. if (!mesh) {
  40654. return true;
  40655. }
  40656. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40657. return false;
  40658. }
  40659. return false;
  40660. };
  40661. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40662. var scene = this.getScene();
  40663. var engine = scene.getEngine();
  40664. if (!this.checkReadyOnEveryCall) {
  40665. if (this._renderId === scene.getRenderId()) {
  40666. if (this._checkCache(scene, mesh, useInstances)) {
  40667. return true;
  40668. }
  40669. }
  40670. }
  40671. // Instances
  40672. var defines = [];
  40673. var fallbacks = new BABYLON.EffectFallbacks();
  40674. if (useInstances) {
  40675. defines.push("#define INSTANCES");
  40676. }
  40677. for (var index = 0; index < this._options.defines.length; index++) {
  40678. defines.push(this._options.defines[index]);
  40679. }
  40680. // Bones
  40681. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40682. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40683. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40684. fallbacks.addCPUSkinningFallback(0, mesh);
  40685. }
  40686. // Alpha test
  40687. if (engine.getAlphaTesting()) {
  40688. defines.push("#define ALPHATEST");
  40689. }
  40690. var previousEffect = this._effect;
  40691. var join = defines.join("\n");
  40692. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40693. if (!this._effect.isReady()) {
  40694. return false;
  40695. }
  40696. if (previousEffect !== this._effect) {
  40697. scene.resetCachedMaterial();
  40698. }
  40699. this._renderId = scene.getRenderId();
  40700. return true;
  40701. };
  40702. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40703. var scene = this.getScene();
  40704. if (this._options.uniforms.indexOf("world") !== -1) {
  40705. this._effect.setMatrix("world", world);
  40706. }
  40707. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40708. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40709. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40710. }
  40711. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40712. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40713. }
  40714. };
  40715. ShaderMaterial.prototype.bind = function (world, mesh) {
  40716. // Std values
  40717. this.bindOnlyWorldMatrix(world);
  40718. if (this.getScene().getCachedMaterial() !== this) {
  40719. if (this._options.uniforms.indexOf("view") !== -1) {
  40720. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40721. }
  40722. if (this._options.uniforms.indexOf("projection") !== -1) {
  40723. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40724. }
  40725. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40726. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40727. }
  40728. // Bones
  40729. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40730. var name;
  40731. // Texture
  40732. for (name in this._textures) {
  40733. this._effect.setTexture(name, this._textures[name]);
  40734. }
  40735. // Texture arrays
  40736. for (name in this._textureArrays) {
  40737. this._effect.setTextureArray(name, this._textureArrays[name]);
  40738. }
  40739. // Float
  40740. for (name in this._floats) {
  40741. this._effect.setFloat(name, this._floats[name]);
  40742. }
  40743. // Float s
  40744. for (name in this._floatsArrays) {
  40745. this._effect.setArray(name, this._floatsArrays[name]);
  40746. }
  40747. // Color3
  40748. for (name in this._colors3) {
  40749. this._effect.setColor3(name, this._colors3[name]);
  40750. }
  40751. // Color4
  40752. for (name in this._colors4) {
  40753. var color = this._colors4[name];
  40754. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40755. }
  40756. // Vector2
  40757. for (name in this._vectors2) {
  40758. this._effect.setVector2(name, this._vectors2[name]);
  40759. }
  40760. // Vector3
  40761. for (name in this._vectors3) {
  40762. this._effect.setVector3(name, this._vectors3[name]);
  40763. }
  40764. // Vector4
  40765. for (name in this._vectors4) {
  40766. this._effect.setVector4(name, this._vectors4[name]);
  40767. }
  40768. // Matrix
  40769. for (name in this._matrices) {
  40770. this._effect.setMatrix(name, this._matrices[name]);
  40771. }
  40772. // Matrix 3x3
  40773. for (name in this._matrices3x3) {
  40774. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40775. }
  40776. // Matrix 2x2
  40777. for (name in this._matrices2x2) {
  40778. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40779. }
  40780. // Vector3Array
  40781. for (name in this._vectors3Arrays) {
  40782. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40783. }
  40784. }
  40785. _super.prototype.bind.call(this, world, mesh);
  40786. };
  40787. ShaderMaterial.prototype.clone = function (name) {
  40788. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40789. return newShaderMaterial;
  40790. };
  40791. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40792. if (forceDisposeTextures) {
  40793. var name;
  40794. for (name in this._textures) {
  40795. this._textures[name].dispose();
  40796. }
  40797. for (name in this._textureArrays) {
  40798. var array = this._textureArrays[name];
  40799. for (var index = 0; index < array.length; index++) {
  40800. array[index].dispose();
  40801. }
  40802. }
  40803. }
  40804. this._textures = {};
  40805. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40806. };
  40807. ShaderMaterial.prototype.serialize = function () {
  40808. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40809. serializationObject.customType = "BABYLON.ShaderMaterial";
  40810. serializationObject.options = this._options;
  40811. serializationObject.shaderPath = this._shaderPath;
  40812. var name;
  40813. // Texture
  40814. serializationObject.textures = {};
  40815. for (name in this._textures) {
  40816. serializationObject.textures[name] = this._textures[name].serialize();
  40817. }
  40818. // Texture arrays
  40819. serializationObject.textureArrays = {};
  40820. for (name in this._textureArrays) {
  40821. serializationObject.textureArrays[name] = [];
  40822. var array = this._textureArrays[name];
  40823. for (var index = 0; index < array.length; index++) {
  40824. serializationObject.textureArrays[name].push(array[index].serialize());
  40825. }
  40826. }
  40827. // Float
  40828. serializationObject.floats = {};
  40829. for (name in this._floats) {
  40830. serializationObject.floats[name] = this._floats[name];
  40831. }
  40832. // Float s
  40833. serializationObject.floatArrays = {};
  40834. for (name in this._floatsArrays) {
  40835. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40836. }
  40837. // Color3
  40838. serializationObject.colors3 = {};
  40839. for (name in this._colors3) {
  40840. serializationObject.colors3[name] = this._colors3[name].asArray();
  40841. }
  40842. // Color4
  40843. serializationObject.colors4 = {};
  40844. for (name in this._colors4) {
  40845. serializationObject.colors4[name] = this._colors4[name].asArray();
  40846. }
  40847. // Vector2
  40848. serializationObject.vectors2 = {};
  40849. for (name in this._vectors2) {
  40850. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40851. }
  40852. // Vector3
  40853. serializationObject.vectors3 = {};
  40854. for (name in this._vectors3) {
  40855. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40856. }
  40857. // Vector4
  40858. serializationObject.vectors4 = {};
  40859. for (name in this._vectors4) {
  40860. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40861. }
  40862. // Matrix
  40863. serializationObject.matrices = {};
  40864. for (name in this._matrices) {
  40865. serializationObject.matrices[name] = this._matrices[name].asArray();
  40866. }
  40867. // Matrix 3x3
  40868. serializationObject.matrices3x3 = {};
  40869. for (name in this._matrices3x3) {
  40870. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40871. }
  40872. // Matrix 2x2
  40873. serializationObject.matrices2x2 = {};
  40874. for (name in this._matrices2x2) {
  40875. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40876. }
  40877. // Vector3Array
  40878. serializationObject.vectors3Arrays = {};
  40879. for (name in this._vectors3Arrays) {
  40880. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40881. }
  40882. return serializationObject;
  40883. };
  40884. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40885. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40886. var name;
  40887. // Texture
  40888. for (name in source.textures) {
  40889. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40890. }
  40891. // Texture arrays
  40892. for (name in source.textureArrays) {
  40893. var array = source.textureArrays[name];
  40894. var textureArray = new Array();
  40895. for (var index = 0; index < array.length; index++) {
  40896. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40897. }
  40898. material.setTextureArray(name, textureArray);
  40899. }
  40900. // Float
  40901. for (name in source.floats) {
  40902. material.setFloat(name, source.floats[name]);
  40903. }
  40904. // Float s
  40905. for (name in source.floatsArrays) {
  40906. material.setFloats(name, source.floatsArrays[name]);
  40907. }
  40908. // Color3
  40909. for (name in source.colors3) {
  40910. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40911. }
  40912. // Color4
  40913. for (name in source.colors4) {
  40914. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40915. }
  40916. // Vector2
  40917. for (name in source.vectors2) {
  40918. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40919. }
  40920. // Vector3
  40921. for (name in source.vectors3) {
  40922. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40923. }
  40924. // Vector4
  40925. for (name in source.vectors4) {
  40926. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40927. }
  40928. // Matrix
  40929. for (name in source.matrices) {
  40930. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40931. }
  40932. // Matrix 3x3
  40933. for (name in source.matrices3x3) {
  40934. material.setMatrix3x3(name, source.matrices3x3[name]);
  40935. }
  40936. // Matrix 2x2
  40937. for (name in source.matrices2x2) {
  40938. material.setMatrix2x2(name, source.matrices2x2[name]);
  40939. }
  40940. // Vector3Array
  40941. for (name in source.vectors3Arrays) {
  40942. material.setArray3(name, source.vectors3Arrays[name]);
  40943. }
  40944. return material;
  40945. };
  40946. return ShaderMaterial;
  40947. }(BABYLON.Material));
  40948. BABYLON.ShaderMaterial = ShaderMaterial;
  40949. })(BABYLON || (BABYLON = {}));
  40950. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40951. var BABYLON;
  40952. (function (BABYLON) {
  40953. var Internals;
  40954. (function (Internals) {
  40955. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40956. // All values and structures referenced from:
  40957. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40958. var DDS_MAGIC = 0x20534444;
  40959. 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;
  40960. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40961. 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;
  40962. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40963. function FourCCToInt32(value) {
  40964. return value.charCodeAt(0) +
  40965. (value.charCodeAt(1) << 8) +
  40966. (value.charCodeAt(2) << 16) +
  40967. (value.charCodeAt(3) << 24);
  40968. }
  40969. function Int32ToFourCC(value) {
  40970. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40971. }
  40972. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40973. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40974. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40975. var headerLengthInt = 31; // The header length in 32 bit ints
  40976. // Offsets into the header array
  40977. var off_magic = 0;
  40978. var off_size = 1;
  40979. var off_flags = 2;
  40980. var off_height = 3;
  40981. var off_width = 4;
  40982. var off_mipmapCount = 7;
  40983. var off_pfFlags = 20;
  40984. var off_pfFourCC = 21;
  40985. var off_RGBbpp = 22;
  40986. var off_RMask = 23;
  40987. var off_GMask = 24;
  40988. var off_BMask = 25;
  40989. var off_AMask = 26;
  40990. var off_caps1 = 27;
  40991. var off_caps2 = 28;
  40992. ;
  40993. var DDSTools = (function () {
  40994. function DDSTools() {
  40995. }
  40996. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40997. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40998. var mipmapCount = 1;
  40999. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41000. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41001. }
  41002. return {
  41003. width: header[off_width],
  41004. height: header[off_height],
  41005. mipmapCount: mipmapCount,
  41006. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41007. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41008. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41009. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41010. };
  41011. };
  41012. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41013. var byteArray = new Uint8Array(dataLength);
  41014. var srcData = new Uint8Array(arrayBuffer);
  41015. var index = 0;
  41016. for (var y = height - 1; y >= 0; y--) {
  41017. for (var x = 0; x < width; x++) {
  41018. var srcPos = dataOffset + (x + y * width) * 4;
  41019. byteArray[index + 2] = srcData[srcPos];
  41020. byteArray[index + 1] = srcData[srcPos + 1];
  41021. byteArray[index] = srcData[srcPos + 2];
  41022. byteArray[index + 3] = srcData[srcPos + 3];
  41023. index += 4;
  41024. }
  41025. }
  41026. return byteArray;
  41027. };
  41028. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41029. var byteArray = new Uint8Array(dataLength);
  41030. var srcData = new Uint8Array(arrayBuffer);
  41031. var index = 0;
  41032. for (var y = height - 1; y >= 0; y--) {
  41033. for (var x = 0; x < width; x++) {
  41034. var srcPos = dataOffset + (x + y * width) * 3;
  41035. byteArray[index + 2] = srcData[srcPos];
  41036. byteArray[index + 1] = srcData[srcPos + 1];
  41037. byteArray[index] = srcData[srcPos + 2];
  41038. index += 3;
  41039. }
  41040. }
  41041. return byteArray;
  41042. };
  41043. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41044. var byteArray = new Uint8Array(dataLength);
  41045. var srcData = new Uint8Array(arrayBuffer);
  41046. var index = 0;
  41047. for (var y = height - 1; y >= 0; y--) {
  41048. for (var x = 0; x < width; x++) {
  41049. var srcPos = dataOffset + (x + y * width);
  41050. byteArray[index] = srcData[srcPos];
  41051. index++;
  41052. }
  41053. }
  41054. return byteArray;
  41055. };
  41056. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41057. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41058. if (header[off_magic] != DDS_MAGIC) {
  41059. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41060. return;
  41061. }
  41062. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41063. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41064. return;
  41065. }
  41066. if (info.isFourCC) {
  41067. fourCC = header[off_pfFourCC];
  41068. switch (fourCC) {
  41069. case FOURCC_DXT1:
  41070. blockBytes = 8;
  41071. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41072. break;
  41073. case FOURCC_DXT3:
  41074. blockBytes = 16;
  41075. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41076. break;
  41077. case FOURCC_DXT5:
  41078. blockBytes = 16;
  41079. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41080. break;
  41081. default:
  41082. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41083. return;
  41084. }
  41085. }
  41086. mipmapCount = 1;
  41087. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41088. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41089. }
  41090. var bpp = header[off_RGBbpp];
  41091. for (var face = 0; face < faces; face++) {
  41092. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41093. width = header[off_width];
  41094. height = header[off_height];
  41095. dataOffset = header[off_size] + 4;
  41096. for (i = 0; i < mipmapCount; ++i) {
  41097. if (info.isRGB) {
  41098. if (bpp === 24) {
  41099. dataLength = width * height * 3;
  41100. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41101. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41102. }
  41103. else {
  41104. dataLength = width * height * 4;
  41105. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41106. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41107. }
  41108. }
  41109. else if (info.isLuminance) {
  41110. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41111. var unpaddedRowSize = width;
  41112. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41113. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41114. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41115. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41116. }
  41117. else {
  41118. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41119. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41120. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41121. }
  41122. dataOffset += dataLength;
  41123. width *= 0.5;
  41124. height *= 0.5;
  41125. width = Math.max(1.0, width);
  41126. height = Math.max(1.0, height);
  41127. }
  41128. }
  41129. };
  41130. return DDSTools;
  41131. }());
  41132. Internals.DDSTools = DDSTools;
  41133. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41134. })(BABYLON || (BABYLON = {}));
  41135. //# sourceMappingURL=babylon.tools.dds.js.map
  41136. var BABYLON;
  41137. (function (BABYLON) {
  41138. var CannonJSPlugin = (function () {
  41139. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41140. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41141. if (iterations === void 0) { iterations = 10; }
  41142. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41143. this.name = "CannonJSPlugin";
  41144. this._physicsMaterials = [];
  41145. this._fixedTimeStep = 1 / 60;
  41146. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41147. this._currentCollisionGroup = 2;
  41148. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41149. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41150. this._tmpPosition = BABYLON.Vector3.Zero();
  41151. this._tmpQuaternion = new BABYLON.Quaternion();
  41152. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41153. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41154. this._tmpUnityRotation = new BABYLON.Quaternion();
  41155. if (!this.isSupported()) {
  41156. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41157. return;
  41158. }
  41159. this.world = new CANNON.World();
  41160. this.world.broadphase = new CANNON.NaiveBroadphase();
  41161. this.world.solver.iterations = iterations;
  41162. }
  41163. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41164. this.world.gravity.copy(gravity);
  41165. };
  41166. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41167. this._fixedTimeStep = timeStep;
  41168. };
  41169. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41170. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41171. };
  41172. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41173. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41174. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41175. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41176. };
  41177. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41178. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41179. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41180. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41181. };
  41182. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41183. //parent-child relationship. Does this impostor has a parent impostor?
  41184. if (impostor.parent) {
  41185. if (impostor.physicsBody) {
  41186. this.removePhysicsBody(impostor);
  41187. //TODO is that needed?
  41188. impostor.forceUpdate();
  41189. }
  41190. return;
  41191. }
  41192. //should a new body be created for this impostor?
  41193. if (impostor.isBodyInitRequired()) {
  41194. var shape = this._createShape(impostor);
  41195. //unregister events, if body is being changed
  41196. var oldBody = impostor.physicsBody;
  41197. if (oldBody) {
  41198. this.removePhysicsBody(impostor);
  41199. }
  41200. //create the body and material
  41201. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41202. var bodyCreationObject = {
  41203. mass: impostor.getParam("mass"),
  41204. material: material
  41205. };
  41206. // A simple extend, in case native options were used.
  41207. var nativeOptions = impostor.getParam("nativeOptions");
  41208. for (var key in nativeOptions) {
  41209. if (nativeOptions.hasOwnProperty(key)) {
  41210. bodyCreationObject[key] = nativeOptions[key];
  41211. }
  41212. }
  41213. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41214. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41215. this.world.addEventListener("preStep", impostor.beforeStep);
  41216. this.world.addEventListener("postStep", impostor.afterStep);
  41217. impostor.physicsBody.addShape(shape);
  41218. this.world.add(impostor.physicsBody);
  41219. //try to keep the body moving in the right direction by taking old properties.
  41220. //Should be tested!
  41221. if (oldBody) {
  41222. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41223. impostor.physicsBody[param].copy(oldBody[param]);
  41224. });
  41225. }
  41226. this._processChildMeshes(impostor);
  41227. }
  41228. //now update the body's transformation
  41229. this._updatePhysicsBodyTransformation(impostor);
  41230. };
  41231. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41232. var _this = this;
  41233. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41234. if (meshChildren.length) {
  41235. var processMesh = function (localPosition, mesh) {
  41236. var childImpostor = mesh.getPhysicsImpostor();
  41237. if (childImpostor) {
  41238. var parent = childImpostor.parent;
  41239. if (parent !== mainImpostor) {
  41240. var localPosition = mesh.position;
  41241. if (childImpostor.physicsBody) {
  41242. _this.removePhysicsBody(childImpostor);
  41243. childImpostor.physicsBody = null;
  41244. }
  41245. childImpostor.parent = mainImpostor;
  41246. childImpostor.resetUpdateFlags();
  41247. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41248. //Add the mass of the children.
  41249. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41250. }
  41251. }
  41252. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41253. };
  41254. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41255. }
  41256. };
  41257. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41258. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41259. this.world.removeEventListener("preStep", impostor.beforeStep);
  41260. this.world.removeEventListener("postStep", impostor.afterStep);
  41261. this.world.remove(impostor.physicsBody);
  41262. };
  41263. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41264. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41265. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41266. if (!mainBody || !connectedBody) {
  41267. return;
  41268. }
  41269. var constraint;
  41270. var jointData = impostorJoint.joint.jointData;
  41271. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41272. var constraintData = {
  41273. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41274. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41275. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41276. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41277. maxForce: jointData.nativeParams.maxForce,
  41278. collideConnected: !!jointData.collision
  41279. };
  41280. //Not needed, Cannon has a collideConnected flag
  41281. /*if (!jointData.collision) {
  41282. //add 1st body to a collision group of its own, if it is not in 1
  41283. if (mainBody.collisionFilterGroup === 1) {
  41284. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41285. this._currentCollisionGroup <<= 1;
  41286. }
  41287. if (connectedBody.collisionFilterGroup === 1) {
  41288. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41289. this._currentCollisionGroup <<= 1;
  41290. }
  41291. //add their mask to the collisionFilterMask of each other:
  41292. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41293. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41294. }*/
  41295. switch (impostorJoint.joint.type) {
  41296. case BABYLON.PhysicsJoint.HingeJoint:
  41297. case BABYLON.PhysicsJoint.Hinge2Joint:
  41298. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41299. break;
  41300. case BABYLON.PhysicsJoint.DistanceJoint:
  41301. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41302. break;
  41303. case BABYLON.PhysicsJoint.SpringJoint:
  41304. var springData = jointData;
  41305. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41306. restLength: springData.length,
  41307. stiffness: springData.stiffness,
  41308. damping: springData.damping,
  41309. localAnchorA: constraintData.pivotA,
  41310. localAnchorB: constraintData.pivotB
  41311. });
  41312. break;
  41313. case BABYLON.PhysicsJoint.LockJoint:
  41314. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41315. break;
  41316. case BABYLON.PhysicsJoint.PointToPointJoint:
  41317. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41318. default:
  41319. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41320. break;
  41321. }
  41322. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41323. constraint.collideConnected = !!jointData.collision;
  41324. impostorJoint.joint.physicsJoint = constraint;
  41325. //don't add spring as constraint, as it is not one.
  41326. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41327. this.world.addConstraint(constraint);
  41328. }
  41329. else {
  41330. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41331. constraint.applyForce();
  41332. });
  41333. }
  41334. };
  41335. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41336. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41337. };
  41338. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41339. var index;
  41340. var mat;
  41341. for (index = 0; index < this._physicsMaterials.length; index++) {
  41342. mat = this._physicsMaterials[index];
  41343. if (mat.friction === friction && mat.restitution === restitution) {
  41344. return mat;
  41345. }
  41346. }
  41347. var currentMat = new CANNON.Material(name);
  41348. currentMat.friction = friction;
  41349. currentMat.restitution = restitution;
  41350. this._physicsMaterials.push(currentMat);
  41351. return currentMat;
  41352. };
  41353. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41354. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41355. };
  41356. CannonJSPlugin.prototype._createShape = function (impostor) {
  41357. var object = impostor.object;
  41358. var returnValue;
  41359. var extendSize = impostor.getObjectExtendSize();
  41360. switch (impostor.type) {
  41361. case BABYLON.PhysicsEngine.SphereImpostor:
  41362. var radiusX = extendSize.x;
  41363. var radiusY = extendSize.y;
  41364. var radiusZ = extendSize.z;
  41365. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41366. break;
  41367. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41368. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41369. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41370. break;
  41371. case BABYLON.PhysicsImpostor.BoxImpostor:
  41372. var box = extendSize.scale(0.5);
  41373. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41374. break;
  41375. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41376. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41377. returnValue = new CANNON.Plane();
  41378. break;
  41379. case BABYLON.PhysicsImpostor.MeshImpostor:
  41380. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41381. var rawFaces = object.getIndices ? object.getIndices() : [];
  41382. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41383. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41384. break;
  41385. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41386. returnValue = this._createHeightmap(object);
  41387. break;
  41388. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41389. returnValue = new CANNON.Particle();
  41390. break;
  41391. }
  41392. return returnValue;
  41393. };
  41394. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41395. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41396. var matrix = [];
  41397. //For now pointDepth will not be used and will be automatically calculated.
  41398. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41399. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41400. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41401. var elementSize = dim * 2 / arraySize;
  41402. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41403. for (var i = 0; i < pos.length; i = i + 3) {
  41404. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41405. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41406. var y = pos[i + 1] + minY;
  41407. if (!matrix[x]) {
  41408. matrix[x] = [];
  41409. }
  41410. if (!matrix[x][z]) {
  41411. matrix[x][z] = y;
  41412. }
  41413. matrix[x][z] = Math.max(y, matrix[x][z]);
  41414. }
  41415. for (var x = 0; x <= arraySize; ++x) {
  41416. if (!matrix[x]) {
  41417. var loc = 1;
  41418. while (!matrix[(x + loc) % arraySize]) {
  41419. loc++;
  41420. }
  41421. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41422. }
  41423. for (var z = 0; z <= arraySize; ++z) {
  41424. if (!matrix[x][z]) {
  41425. var loc = 1;
  41426. var newValue;
  41427. while (newValue === undefined) {
  41428. newValue = matrix[x][(z + loc++) % arraySize];
  41429. }
  41430. matrix[x][z] = newValue;
  41431. }
  41432. }
  41433. }
  41434. var shape = new CANNON.Heightfield(matrix, {
  41435. elementSize: elementSize
  41436. });
  41437. //For future reference, needed for body transformation
  41438. shape.minY = minY;
  41439. return shape;
  41440. };
  41441. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41442. var object = impostor.object;
  41443. //make sure it is updated...
  41444. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41445. // The delta between the mesh position and the mesh bounding box center
  41446. var center = impostor.getObjectCenter();
  41447. var extendSize = impostor.getObjectExtendSize();
  41448. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41449. this._tmpPosition.copyFrom(center);
  41450. var quaternion = object.rotationQuaternion;
  41451. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41452. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41453. //-90 DEG in X, precalculated
  41454. quaternion = quaternion.multiply(this._minus90X);
  41455. //Invert! (Precalculated, 90 deg in X)
  41456. //No need to clone. this will never change.
  41457. impostor.setDeltaRotation(this._plus90X);
  41458. }
  41459. //If it is a heightfield, if should be centered.
  41460. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41461. var mesh = object;
  41462. //calculate the correct body position:
  41463. var rotationQuaternion = mesh.rotationQuaternion;
  41464. mesh.rotationQuaternion = this._tmpUnityRotation;
  41465. mesh.computeWorldMatrix(true);
  41466. //get original center with no rotation
  41467. var c = center.clone();
  41468. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41469. //rotation is back
  41470. mesh.rotationQuaternion = rotationQuaternion;
  41471. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41472. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41473. mesh.setPivotMatrix(p);
  41474. mesh.computeWorldMatrix(true);
  41475. //calculate the translation
  41476. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41477. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41478. //add it inverted to the delta
  41479. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41480. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41481. mesh.setPivotMatrix(oldPivot);
  41482. mesh.computeWorldMatrix(true);
  41483. }
  41484. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41485. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41486. this._tmpPosition.copyFrom(object.position);
  41487. }
  41488. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41489. //Now update the impostor object
  41490. impostor.physicsBody.position.copy(this._tmpPosition);
  41491. impostor.physicsBody.quaternion.copy(quaternion);
  41492. };
  41493. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41494. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41495. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41496. };
  41497. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41498. impostor.physicsBody.position.copy(newPosition);
  41499. impostor.physicsBody.quaternion.copy(newRotation);
  41500. };
  41501. CannonJSPlugin.prototype.isSupported = function () {
  41502. return window.CANNON !== undefined;
  41503. };
  41504. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41505. impostor.physicsBody.velocity.copy(velocity);
  41506. };
  41507. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41508. impostor.physicsBody.angularVelocity.copy(velocity);
  41509. };
  41510. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41511. var v = impostor.physicsBody.velocity;
  41512. if (!v)
  41513. return null;
  41514. return new BABYLON.Vector3(v.x, v.y, v.z);
  41515. };
  41516. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41517. var v = impostor.physicsBody.angularVelocity;
  41518. if (!v)
  41519. return null;
  41520. return new BABYLON.Vector3(v.x, v.y, v.z);
  41521. };
  41522. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41523. impostor.physicsBody.mass = mass;
  41524. impostor.physicsBody.updateMassProperties();
  41525. };
  41526. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41527. impostor.physicsBody.sleep();
  41528. };
  41529. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41530. impostor.physicsBody.wakeUp();
  41531. };
  41532. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41533. joint.physicsJoint.distance = maxDistance;
  41534. };
  41535. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41536. if (!motorIndex) {
  41537. joint.physicsJoint.enableMotor();
  41538. }
  41539. };
  41540. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41541. if (!motorIndex) {
  41542. joint.physicsJoint.disableMotor();
  41543. }
  41544. };
  41545. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41546. if (!motorIndex) {
  41547. joint.physicsJoint.enableMotor();
  41548. joint.physicsJoint.setMotorSpeed(speed);
  41549. if (maxForce) {
  41550. this.setLimit(joint, maxForce);
  41551. }
  41552. }
  41553. };
  41554. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41555. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41556. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41557. };
  41558. CannonJSPlugin.prototype.dispose = function () {
  41559. //nothing to do, actually.
  41560. };
  41561. return CannonJSPlugin;
  41562. }());
  41563. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41564. })(BABYLON || (BABYLON = {}));
  41565. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41566. var BABYLON;
  41567. (function (BABYLON) {
  41568. var OimoJSPlugin = (function () {
  41569. function OimoJSPlugin(iterations) {
  41570. this.name = "OimoJSPlugin";
  41571. this._tmpImpostorsArray = [];
  41572. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41573. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41574. this.world.worldscale(1);
  41575. this.world.clear();
  41576. //making sure no stats are calculated
  41577. this.world.isNoStat = true;
  41578. }
  41579. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41580. this.world.gravity.copy(gravity);
  41581. };
  41582. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41583. this.world.timeStep = timeStep;
  41584. };
  41585. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41586. var _this = this;
  41587. impostors.forEach(function (impostor) {
  41588. impostor.beforeStep();
  41589. });
  41590. this.world.step();
  41591. impostors.forEach(function (impostor) {
  41592. impostor.afterStep();
  41593. //update the ordered impostors array
  41594. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41595. });
  41596. //check for collisions
  41597. var contact = this.world.contacts;
  41598. while (contact !== null) {
  41599. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41600. contact = contact.next;
  41601. continue;
  41602. }
  41603. //is this body colliding with any other? get the impostor
  41604. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41605. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41606. if (!mainImpostor || !collidingImpostor) {
  41607. contact = contact.next;
  41608. continue;
  41609. }
  41610. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41611. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41612. contact = contact.next;
  41613. }
  41614. };
  41615. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41616. var mass = impostor.physicsBody.massInfo.mass;
  41617. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41618. };
  41619. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41620. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41621. this.applyImpulse(impostor, force, contactPoint);
  41622. };
  41623. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41624. var _this = this;
  41625. //parent-child relationship. Does this impostor has a parent impostor?
  41626. if (impostor.parent) {
  41627. if (impostor.physicsBody) {
  41628. this.removePhysicsBody(impostor);
  41629. //TODO is that needed?
  41630. impostor.forceUpdate();
  41631. }
  41632. return;
  41633. }
  41634. if (impostor.isBodyInitRequired()) {
  41635. var bodyConfig = {
  41636. name: impostor.uniqueId,
  41637. //Oimo must have mass, also for static objects.
  41638. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41639. size: [],
  41640. type: [],
  41641. pos: [],
  41642. rot: [],
  41643. move: impostor.getParam("mass") !== 0,
  41644. //Supporting older versions of Oimo
  41645. world: this.world
  41646. };
  41647. var impostors = [impostor];
  41648. var addToArray = function (parent) {
  41649. if (!parent.getChildMeshes)
  41650. return;
  41651. parent.getChildMeshes().forEach(function (m) {
  41652. if (m.physicsImpostor) {
  41653. impostors.push(m.physicsImpostor);
  41654. m.physicsImpostor._init();
  41655. }
  41656. });
  41657. };
  41658. addToArray(impostor.object);
  41659. var checkWithEpsilon_1 = function (value) {
  41660. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41661. };
  41662. impostors.forEach(function (i) {
  41663. //get the correct bounding box
  41664. var oldQuaternion = i.object.rotationQuaternion;
  41665. var rot = new OIMO.Euler().setFromQuaternion({
  41666. x: impostor.object.rotationQuaternion.x,
  41667. y: impostor.object.rotationQuaternion.y,
  41668. z: impostor.object.rotationQuaternion.z,
  41669. s: impostor.object.rotationQuaternion.w
  41670. });
  41671. var extendSize = i.getObjectExtendSize();
  41672. if (i === impostor) {
  41673. var center = impostor.getObjectCenter();
  41674. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41675. //Can also use Array.prototype.push.apply
  41676. bodyConfig.pos.push(center.x);
  41677. bodyConfig.pos.push(center.y);
  41678. bodyConfig.pos.push(center.z);
  41679. //tmp solution
  41680. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41681. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41682. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41683. }
  41684. else {
  41685. bodyConfig.pos.push(i.object.position.x);
  41686. bodyConfig.pos.push(i.object.position.y);
  41687. bodyConfig.pos.push(i.object.position.z);
  41688. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41689. bodyConfig.rot.push(0);
  41690. bodyConfig.rot.push(0);
  41691. bodyConfig.rot.push(0);
  41692. }
  41693. // register mesh
  41694. switch (i.type) {
  41695. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41696. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41697. case BABYLON.PhysicsImpostor.SphereImpostor:
  41698. var radiusX = extendSize.x;
  41699. var radiusY = extendSize.y;
  41700. var radiusZ = extendSize.z;
  41701. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41702. bodyConfig.type.push('sphere');
  41703. //due to the way oimo works with compounds, add 3 times
  41704. bodyConfig.size.push(size);
  41705. bodyConfig.size.push(size);
  41706. bodyConfig.size.push(size);
  41707. break;
  41708. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41709. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41710. var sizeY = checkWithEpsilon_1(extendSize.y);
  41711. bodyConfig.type.push('cylinder');
  41712. bodyConfig.size.push(sizeX);
  41713. bodyConfig.size.push(sizeY);
  41714. //due to the way oimo works with compounds, add one more value.
  41715. bodyConfig.size.push(sizeY);
  41716. break;
  41717. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41718. case BABYLON.PhysicsImpostor.BoxImpostor:
  41719. default:
  41720. var sizeX = checkWithEpsilon_1(extendSize.x);
  41721. var sizeY = checkWithEpsilon_1(extendSize.y);
  41722. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41723. bodyConfig.type.push('box');
  41724. bodyConfig.size.push(sizeX);
  41725. bodyConfig.size.push(sizeY);
  41726. bodyConfig.size.push(sizeZ);
  41727. break;
  41728. }
  41729. //actually not needed, but hey...
  41730. i.object.rotationQuaternion = oldQuaternion;
  41731. });
  41732. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41733. }
  41734. else {
  41735. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41736. }
  41737. impostor.setDeltaPosition(this._tmpPositionVector);
  41738. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41739. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41740. };
  41741. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41742. //impostor.physicsBody.dispose();
  41743. //Same as : (older oimo versions)
  41744. this.world.removeRigidBody(impostor.physicsBody);
  41745. };
  41746. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41747. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41748. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41749. if (!mainBody || !connectedBody) {
  41750. return;
  41751. }
  41752. var jointData = impostorJoint.joint.jointData;
  41753. var options = jointData.nativeParams || {};
  41754. var type;
  41755. var nativeJointData = {
  41756. body1: mainBody,
  41757. body2: connectedBody,
  41758. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41759. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41760. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41761. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41762. min: options.min,
  41763. max: options.max,
  41764. collision: options.collision || jointData.collision,
  41765. spring: options.spring,
  41766. //supporting older version of Oimo
  41767. world: this.world
  41768. };
  41769. switch (impostorJoint.joint.type) {
  41770. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41771. type = "jointBall";
  41772. break;
  41773. case BABYLON.PhysicsJoint.SpringJoint:
  41774. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41775. var springData = jointData;
  41776. nativeJointData.min = springData.length || nativeJointData.min;
  41777. //Max should also be set, just make sure it is at least min
  41778. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41779. case BABYLON.PhysicsJoint.DistanceJoint:
  41780. type = "jointDistance";
  41781. nativeJointData.max = jointData.maxDistance;
  41782. break;
  41783. case BABYLON.PhysicsJoint.PrismaticJoint:
  41784. type = "jointPrisme";
  41785. break;
  41786. case BABYLON.PhysicsJoint.SliderJoint:
  41787. type = "jointSlide";
  41788. break;
  41789. case BABYLON.PhysicsJoint.WheelJoint:
  41790. type = "jointWheel";
  41791. break;
  41792. case BABYLON.PhysicsJoint.HingeJoint:
  41793. default:
  41794. type = "jointHinge";
  41795. break;
  41796. }
  41797. nativeJointData.type = type;
  41798. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41799. };
  41800. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41801. //Bug in Oimo prevents us from disposing a joint in the playground
  41802. //joint.joint.physicsJoint.dispose();
  41803. //So we will bruteforce it!
  41804. try {
  41805. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41806. }
  41807. catch (e) {
  41808. BABYLON.Tools.Warn(e);
  41809. }
  41810. };
  41811. OimoJSPlugin.prototype.isSupported = function () {
  41812. return OIMO !== undefined;
  41813. };
  41814. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41815. if (!impostor.physicsBody.sleeping) {
  41816. //TODO check that
  41817. if (impostor.physicsBody.shapes.next) {
  41818. var parentShape = this._getLastShape(impostor.physicsBody);
  41819. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41820. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41821. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41822. }
  41823. else {
  41824. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41825. }
  41826. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41827. impostor.object.rotationQuaternion.normalize();
  41828. }
  41829. };
  41830. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41831. var body = impostor.physicsBody;
  41832. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41833. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41834. body.syncShapes();
  41835. body.awake();
  41836. };
  41837. OimoJSPlugin.prototype._getLastShape = function (body) {
  41838. var lastShape = body.shapes;
  41839. while (lastShape.next) {
  41840. lastShape = lastShape.next;
  41841. }
  41842. return lastShape;
  41843. };
  41844. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41845. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41846. };
  41847. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41848. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41849. };
  41850. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41851. var v = impostor.physicsBody.linearVelocity;
  41852. if (!v)
  41853. return null;
  41854. return new BABYLON.Vector3(v.x, v.y, v.z);
  41855. };
  41856. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41857. var v = impostor.physicsBody.angularVelocity;
  41858. if (!v)
  41859. return null;
  41860. return new BABYLON.Vector3(v.x, v.y, v.z);
  41861. };
  41862. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41863. var staticBody = mass === 0;
  41864. //this will actually set the body's density and not its mass.
  41865. //But this is how oimo treats the mass variable.
  41866. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41867. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41868. };
  41869. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41870. impostor.physicsBody.sleep();
  41871. };
  41872. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41873. impostor.physicsBody.awake();
  41874. };
  41875. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41876. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41877. if (minDistance !== void 0) {
  41878. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41879. }
  41880. };
  41881. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41882. //TODO separate rotational and transational motors.
  41883. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41884. if (motor) {
  41885. motor.setMotor(speed, maxForce);
  41886. }
  41887. };
  41888. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41889. //TODO separate rotational and transational motors.
  41890. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41891. if (motor) {
  41892. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41893. }
  41894. };
  41895. OimoJSPlugin.prototype.dispose = function () {
  41896. this.world.clear();
  41897. };
  41898. return OimoJSPlugin;
  41899. }());
  41900. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41901. })(BABYLON || (BABYLON = {}));
  41902. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41903. var BABYLON;
  41904. (function (BABYLON) {
  41905. var DisplayPassPostProcess = (function (_super) {
  41906. __extends(DisplayPassPostProcess, _super);
  41907. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41908. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  41909. }
  41910. return DisplayPassPostProcess;
  41911. }(BABYLON.PostProcess));
  41912. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41913. })(BABYLON || (BABYLON = {}));
  41914. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41915. var BABYLON;
  41916. (function (BABYLON) {
  41917. var SimplificationSettings = (function () {
  41918. function SimplificationSettings(quality, distance, optimizeMesh) {
  41919. this.quality = quality;
  41920. this.distance = distance;
  41921. this.optimizeMesh = optimizeMesh;
  41922. }
  41923. return SimplificationSettings;
  41924. }());
  41925. BABYLON.SimplificationSettings = SimplificationSettings;
  41926. var SimplificationQueue = (function () {
  41927. function SimplificationQueue() {
  41928. this.running = false;
  41929. this._simplificationArray = [];
  41930. }
  41931. SimplificationQueue.prototype.addTask = function (task) {
  41932. this._simplificationArray.push(task);
  41933. };
  41934. SimplificationQueue.prototype.executeNext = function () {
  41935. var task = this._simplificationArray.pop();
  41936. if (task) {
  41937. this.running = true;
  41938. this.runSimplification(task);
  41939. }
  41940. else {
  41941. this.running = false;
  41942. }
  41943. };
  41944. SimplificationQueue.prototype.runSimplification = function (task) {
  41945. var _this = this;
  41946. if (task.parallelProcessing) {
  41947. //parallel simplifier
  41948. task.settings.forEach(function (setting) {
  41949. var simplifier = _this.getSimplifier(task);
  41950. simplifier.simplify(setting, function (newMesh) {
  41951. task.mesh.addLODLevel(setting.distance, newMesh);
  41952. newMesh.isVisible = true;
  41953. //check if it is the last
  41954. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41955. //all done, run the success callback.
  41956. task.successCallback();
  41957. }
  41958. _this.executeNext();
  41959. });
  41960. });
  41961. }
  41962. else {
  41963. //single simplifier.
  41964. var simplifier = this.getSimplifier(task);
  41965. var runDecimation = function (setting, callback) {
  41966. simplifier.simplify(setting, function (newMesh) {
  41967. task.mesh.addLODLevel(setting.distance, newMesh);
  41968. newMesh.isVisible = true;
  41969. //run the next quality level
  41970. callback();
  41971. });
  41972. };
  41973. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41974. runDecimation(task.settings[loop.index], function () {
  41975. loop.executeNext();
  41976. });
  41977. }, function () {
  41978. //execution ended, run the success callback.
  41979. if (task.successCallback) {
  41980. task.successCallback();
  41981. }
  41982. _this.executeNext();
  41983. });
  41984. }
  41985. };
  41986. SimplificationQueue.prototype.getSimplifier = function (task) {
  41987. switch (task.simplificationType) {
  41988. case SimplificationType.QUADRATIC:
  41989. default:
  41990. return new QuadraticErrorSimplification(task.mesh);
  41991. }
  41992. };
  41993. return SimplificationQueue;
  41994. }());
  41995. BABYLON.SimplificationQueue = SimplificationQueue;
  41996. /**
  41997. * The implemented types of simplification.
  41998. * At the moment only Quadratic Error Decimation is implemented.
  41999. */
  42000. var SimplificationType;
  42001. (function (SimplificationType) {
  42002. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42003. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42004. var DecimationTriangle = (function () {
  42005. function DecimationTriangle(vertices) {
  42006. this.vertices = vertices;
  42007. this.error = new Array(4);
  42008. this.deleted = false;
  42009. this.isDirty = false;
  42010. this.deletePending = false;
  42011. this.borderFactor = 0;
  42012. }
  42013. return DecimationTriangle;
  42014. }());
  42015. BABYLON.DecimationTriangle = DecimationTriangle;
  42016. var DecimationVertex = (function () {
  42017. function DecimationVertex(position, id) {
  42018. this.position = position;
  42019. this.id = id;
  42020. this.isBorder = true;
  42021. this.q = new QuadraticMatrix();
  42022. this.triangleCount = 0;
  42023. this.triangleStart = 0;
  42024. this.originalOffsets = [];
  42025. }
  42026. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42027. this.position.copyFrom(newPosition);
  42028. };
  42029. return DecimationVertex;
  42030. }());
  42031. BABYLON.DecimationVertex = DecimationVertex;
  42032. var QuadraticMatrix = (function () {
  42033. function QuadraticMatrix(data) {
  42034. this.data = new Array(10);
  42035. for (var i = 0; i < 10; ++i) {
  42036. if (data && data[i]) {
  42037. this.data[i] = data[i];
  42038. }
  42039. else {
  42040. this.data[i] = 0;
  42041. }
  42042. }
  42043. }
  42044. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42045. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42046. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42047. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42048. return det;
  42049. };
  42050. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42051. for (var i = 0; i < 10; ++i) {
  42052. this.data[i] += matrix.data[i];
  42053. }
  42054. };
  42055. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42056. for (var i = 0; i < 10; ++i) {
  42057. this.data[i] += data[i];
  42058. }
  42059. };
  42060. QuadraticMatrix.prototype.add = function (matrix) {
  42061. var m = new QuadraticMatrix();
  42062. for (var i = 0; i < 10; ++i) {
  42063. m.data[i] = this.data[i] + matrix.data[i];
  42064. }
  42065. return m;
  42066. };
  42067. QuadraticMatrix.FromData = function (a, b, c, d) {
  42068. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42069. };
  42070. //returning an array to avoid garbage collection
  42071. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42072. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42073. };
  42074. return QuadraticMatrix;
  42075. }());
  42076. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42077. var Reference = (function () {
  42078. function Reference(vertexId, triangleId) {
  42079. this.vertexId = vertexId;
  42080. this.triangleId = triangleId;
  42081. }
  42082. return Reference;
  42083. }());
  42084. BABYLON.Reference = Reference;
  42085. /**
  42086. * An implementation of the Quadratic Error simplification algorithm.
  42087. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42088. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42089. * @author RaananW
  42090. */
  42091. var QuadraticErrorSimplification = (function () {
  42092. function QuadraticErrorSimplification(_mesh) {
  42093. this._mesh = _mesh;
  42094. this.initialized = false;
  42095. this.syncIterations = 5000;
  42096. this.aggressiveness = 7;
  42097. this.decimationIterations = 100;
  42098. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42099. }
  42100. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42101. var _this = this;
  42102. this.initDecimatedMesh();
  42103. //iterating through the submeshes array, one after the other.
  42104. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42105. _this.initWithMesh(loop.index, function () {
  42106. _this.runDecimation(settings, loop.index, function () {
  42107. loop.executeNext();
  42108. });
  42109. }, settings.optimizeMesh);
  42110. }, function () {
  42111. setTimeout(function () {
  42112. successCallback(_this._reconstructedMesh);
  42113. }, 0);
  42114. });
  42115. };
  42116. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42117. var _this = this;
  42118. var gCount = 0;
  42119. triangle.vertices.forEach(function (vertex) {
  42120. var count = 0;
  42121. var vPos = vertex.position;
  42122. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42123. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42124. ++count;
  42125. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42126. ++count;
  42127. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42128. ++count;
  42129. if (count > 1) {
  42130. ++gCount;
  42131. }
  42132. ;
  42133. });
  42134. if (gCount > 1) {
  42135. console.log(triangle, gCount);
  42136. }
  42137. return gCount > 1;
  42138. };
  42139. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42140. var _this = this;
  42141. var targetCount = ~~(this.triangles.length * settings.quality);
  42142. var deletedTriangles = 0;
  42143. var triangleCount = this.triangles.length;
  42144. var iterationFunction = function (iteration, callback) {
  42145. setTimeout(function () {
  42146. if (iteration % 5 === 0) {
  42147. _this.updateMesh(iteration === 0);
  42148. }
  42149. for (var i = 0; i < _this.triangles.length; ++i) {
  42150. _this.triangles[i].isDirty = false;
  42151. }
  42152. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42153. var trianglesIterator = function (i) {
  42154. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42155. var t = _this.triangles[tIdx];
  42156. if (!t)
  42157. return;
  42158. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42159. return;
  42160. }
  42161. for (var j = 0; j < 3; ++j) {
  42162. if (t.error[j] < threshold) {
  42163. var deleted0 = [];
  42164. var deleted1 = [];
  42165. var v0 = t.vertices[j];
  42166. var v1 = t.vertices[(j + 1) % 3];
  42167. if (v0.isBorder || v1.isBorder)
  42168. continue;
  42169. var p = BABYLON.Vector3.Zero();
  42170. var n = BABYLON.Vector3.Zero();
  42171. var uv = BABYLON.Vector2.Zero();
  42172. var color = new BABYLON.Color4(0, 0, 0, 1);
  42173. _this.calculateError(v0, v1, p, n, uv, color);
  42174. var delTr = [];
  42175. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42176. continue;
  42177. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42178. continue;
  42179. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42180. continue;
  42181. var uniqueArray = [];
  42182. delTr.forEach(function (deletedT) {
  42183. if (uniqueArray.indexOf(deletedT) === -1) {
  42184. deletedT.deletePending = true;
  42185. uniqueArray.push(deletedT);
  42186. }
  42187. });
  42188. if (uniqueArray.length % 2 !== 0) {
  42189. continue;
  42190. }
  42191. v0.q = v1.q.add(v0.q);
  42192. v0.updatePosition(p);
  42193. var tStart = _this.references.length;
  42194. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42195. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42196. var tCount = _this.references.length - tStart;
  42197. if (tCount <= v0.triangleCount) {
  42198. if (tCount) {
  42199. for (var c = 0; c < tCount; c++) {
  42200. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42201. }
  42202. }
  42203. }
  42204. else {
  42205. v0.triangleStart = tStart;
  42206. }
  42207. v0.triangleCount = tCount;
  42208. break;
  42209. }
  42210. }
  42211. };
  42212. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42213. }, 0);
  42214. };
  42215. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42216. if (triangleCount - deletedTriangles <= targetCount)
  42217. loop.breakLoop();
  42218. else {
  42219. iterationFunction(loop.index, function () {
  42220. loop.executeNext();
  42221. });
  42222. }
  42223. }, function () {
  42224. setTimeout(function () {
  42225. //reconstruct this part of the mesh
  42226. _this.reconstructMesh(submeshIndex);
  42227. successCallback();
  42228. }, 0);
  42229. });
  42230. };
  42231. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42232. var _this = this;
  42233. this.vertices = [];
  42234. this.triangles = [];
  42235. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42236. var indices = this._mesh.getIndices();
  42237. var submesh = this._mesh.subMeshes[submeshIndex];
  42238. var findInVertices = function (positionToSearch) {
  42239. if (optimizeMesh) {
  42240. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42241. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42242. return _this.vertices[ii];
  42243. }
  42244. }
  42245. }
  42246. return null;
  42247. };
  42248. var vertexReferences = [];
  42249. var vertexInit = function (i) {
  42250. var offset = i + submesh.verticesStart;
  42251. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42252. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42253. vertex.originalOffsets.push(offset);
  42254. if (vertex.id === _this.vertices.length) {
  42255. _this.vertices.push(vertex);
  42256. }
  42257. vertexReferences.push(vertex.id);
  42258. };
  42259. //var totalVertices = mesh.getTotalVertices();
  42260. var totalVertices = submesh.verticesCount;
  42261. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42262. var indicesInit = function (i) {
  42263. var offset = (submesh.indexStart / 3) + i;
  42264. var pos = (offset * 3);
  42265. var i0 = indices[pos + 0];
  42266. var i1 = indices[pos + 1];
  42267. var i2 = indices[pos + 2];
  42268. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42269. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42270. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42271. var triangle = new DecimationTriangle([v0, v1, v2]);
  42272. triangle.originalOffset = pos;
  42273. _this.triangles.push(triangle);
  42274. };
  42275. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42276. _this.init(callback);
  42277. });
  42278. });
  42279. };
  42280. QuadraticErrorSimplification.prototype.init = function (callback) {
  42281. var _this = this;
  42282. var triangleInit1 = function (i) {
  42283. var t = _this.triangles[i];
  42284. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42285. for (var j = 0; j < 3; j++) {
  42286. 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))));
  42287. }
  42288. };
  42289. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42290. var triangleInit2 = function (i) {
  42291. var t = _this.triangles[i];
  42292. for (var j = 0; j < 3; ++j) {
  42293. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42294. }
  42295. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42296. };
  42297. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42298. _this.initialized = true;
  42299. callback();
  42300. });
  42301. });
  42302. };
  42303. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42304. var newTriangles = [];
  42305. var i;
  42306. for (i = 0; i < this.vertices.length; ++i) {
  42307. this.vertices[i].triangleCount = 0;
  42308. }
  42309. var t;
  42310. var j;
  42311. for (i = 0; i < this.triangles.length; ++i) {
  42312. if (!this.triangles[i].deleted) {
  42313. t = this.triangles[i];
  42314. for (j = 0; j < 3; ++j) {
  42315. t.vertices[j].triangleCount = 1;
  42316. }
  42317. newTriangles.push(t);
  42318. }
  42319. }
  42320. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42321. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42322. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42323. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42324. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42325. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42326. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42327. var vertexCount = 0;
  42328. for (i = 0; i < this.vertices.length; ++i) {
  42329. var vertex = this.vertices[i];
  42330. vertex.id = vertexCount;
  42331. if (vertex.triangleCount) {
  42332. vertex.originalOffsets.forEach(function (originalOffset) {
  42333. newPositionData.push(vertex.position.x);
  42334. newPositionData.push(vertex.position.y);
  42335. newPositionData.push(vertex.position.z);
  42336. newNormalData.push(normalData[originalOffset * 3]);
  42337. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42338. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42339. if (uvs && uvs.length) {
  42340. newUVsData.push(uvs[(originalOffset * 2)]);
  42341. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42342. }
  42343. else if (colorsData && colorsData.length) {
  42344. newColorsData.push(colorsData[(originalOffset * 4)]);
  42345. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42346. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42347. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42348. }
  42349. ++vertexCount;
  42350. });
  42351. }
  42352. }
  42353. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42354. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42355. var submeshesArray = this._reconstructedMesh.subMeshes;
  42356. this._reconstructedMesh.subMeshes = [];
  42357. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42358. var originalIndices = this._mesh.getIndices();
  42359. for (i = 0; i < newTriangles.length; ++i) {
  42360. t = newTriangles[i]; //now get the new referencing point for each vertex
  42361. [0, 1, 2].forEach(function (idx) {
  42362. var id = originalIndices[t.originalOffset + idx];
  42363. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42364. if (offset < 0)
  42365. offset = 0;
  42366. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42367. });
  42368. }
  42369. //overwriting the old vertex buffers and indices.
  42370. this._reconstructedMesh.setIndices(newIndicesArray);
  42371. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42372. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42373. if (newUVsData.length > 0)
  42374. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42375. if (newColorsData.length > 0)
  42376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42377. //create submesh
  42378. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42379. if (submeshIndex > 0) {
  42380. this._reconstructedMesh.subMeshes = [];
  42381. submeshesArray.forEach(function (submesh) {
  42382. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42383. });
  42384. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42385. }
  42386. };
  42387. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42388. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42389. this._reconstructedMesh.material = this._mesh.material;
  42390. this._reconstructedMesh.parent = this._mesh.parent;
  42391. this._reconstructedMesh.isVisible = false;
  42392. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42393. };
  42394. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42395. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42396. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42397. if (t.deleted)
  42398. continue;
  42399. var s = this.references[vertex1.triangleStart + i].vertexId;
  42400. var v1 = t.vertices[(s + 1) % 3];
  42401. var v2 = t.vertices[(s + 2) % 3];
  42402. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42403. deletedArray[i] = true;
  42404. delTr.push(t);
  42405. continue;
  42406. }
  42407. var d1 = v1.position.subtract(point);
  42408. d1 = d1.normalize();
  42409. var d2 = v2.position.subtract(point);
  42410. d2 = d2.normalize();
  42411. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42412. return true;
  42413. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42414. deletedArray[i] = false;
  42415. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42416. return true;
  42417. }
  42418. return false;
  42419. };
  42420. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42421. var newDeleted = deletedTriangles;
  42422. for (var i = 0; i < vertex.triangleCount; ++i) {
  42423. var ref = this.references[vertex.triangleStart + i];
  42424. var t = this.triangles[ref.triangleId];
  42425. if (t.deleted)
  42426. continue;
  42427. if (deletedArray[i] && t.deletePending) {
  42428. t.deleted = true;
  42429. newDeleted++;
  42430. continue;
  42431. }
  42432. t.vertices[ref.vertexId] = origVertex;
  42433. t.isDirty = true;
  42434. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42435. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42436. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42437. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42438. this.references.push(ref);
  42439. }
  42440. return newDeleted;
  42441. };
  42442. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42443. for (var i = 0; i < this.vertices.length; ++i) {
  42444. var vCount = [];
  42445. var vId = [];
  42446. var v = this.vertices[i];
  42447. var j;
  42448. for (j = 0; j < v.triangleCount; ++j) {
  42449. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42450. for (var ii = 0; ii < 3; ii++) {
  42451. var ofs = 0;
  42452. var vv = triangle.vertices[ii];
  42453. while (ofs < vCount.length) {
  42454. if (vId[ofs] === vv.id)
  42455. break;
  42456. ++ofs;
  42457. }
  42458. if (ofs === vCount.length) {
  42459. vCount.push(1);
  42460. vId.push(vv.id);
  42461. }
  42462. else {
  42463. vCount[ofs]++;
  42464. }
  42465. }
  42466. }
  42467. for (j = 0; j < vCount.length; ++j) {
  42468. if (vCount[j] === 1) {
  42469. this.vertices[vId[j]].isBorder = true;
  42470. }
  42471. else {
  42472. this.vertices[vId[j]].isBorder = false;
  42473. }
  42474. }
  42475. }
  42476. };
  42477. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42478. if (identifyBorders === void 0) { identifyBorders = false; }
  42479. var i;
  42480. if (!identifyBorders) {
  42481. var newTrianglesVector = [];
  42482. for (i = 0; i < this.triangles.length; ++i) {
  42483. if (!this.triangles[i].deleted) {
  42484. newTrianglesVector.push(this.triangles[i]);
  42485. }
  42486. }
  42487. this.triangles = newTrianglesVector;
  42488. }
  42489. for (i = 0; i < this.vertices.length; ++i) {
  42490. this.vertices[i].triangleCount = 0;
  42491. this.vertices[i].triangleStart = 0;
  42492. }
  42493. var t;
  42494. var j;
  42495. var v;
  42496. for (i = 0; i < this.triangles.length; ++i) {
  42497. t = this.triangles[i];
  42498. for (j = 0; j < 3; ++j) {
  42499. v = t.vertices[j];
  42500. v.triangleCount++;
  42501. }
  42502. }
  42503. var tStart = 0;
  42504. for (i = 0; i < this.vertices.length; ++i) {
  42505. this.vertices[i].triangleStart = tStart;
  42506. tStart += this.vertices[i].triangleCount;
  42507. this.vertices[i].triangleCount = 0;
  42508. }
  42509. var newReferences = new Array(this.triangles.length * 3);
  42510. for (i = 0; i < this.triangles.length; ++i) {
  42511. t = this.triangles[i];
  42512. for (j = 0; j < 3; ++j) {
  42513. v = t.vertices[j];
  42514. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42515. v.triangleCount++;
  42516. }
  42517. }
  42518. this.references = newReferences;
  42519. if (identifyBorders) {
  42520. this.identifyBorder();
  42521. }
  42522. };
  42523. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42524. var x = point.x;
  42525. var y = point.y;
  42526. var z = point.z;
  42527. 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
  42528. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42529. };
  42530. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42531. var q = vertex1.q.add(vertex2.q);
  42532. var border = vertex1.isBorder && vertex2.isBorder;
  42533. var error = 0;
  42534. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42535. if (qDet !== 0 && !border) {
  42536. if (!pointResult) {
  42537. pointResult = BABYLON.Vector3.Zero();
  42538. }
  42539. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42540. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42541. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42542. error = this.vertexError(q, pointResult);
  42543. }
  42544. else {
  42545. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42546. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42547. var error1 = this.vertexError(q, vertex1.position);
  42548. var error2 = this.vertexError(q, vertex2.position);
  42549. var error3 = this.vertexError(q, p3);
  42550. error = Math.min(error1, error2, error3);
  42551. if (error === error1) {
  42552. if (pointResult) {
  42553. pointResult.copyFrom(vertex1.position);
  42554. }
  42555. }
  42556. else if (error === error2) {
  42557. if (pointResult) {
  42558. pointResult.copyFrom(vertex2.position);
  42559. }
  42560. }
  42561. else {
  42562. if (pointResult) {
  42563. pointResult.copyFrom(p3);
  42564. }
  42565. }
  42566. }
  42567. return error;
  42568. };
  42569. return QuadraticErrorSimplification;
  42570. }());
  42571. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42572. })(BABYLON || (BABYLON = {}));
  42573. //# sourceMappingURL=babylon.meshSimplification.js.map
  42574. var BABYLON;
  42575. (function (BABYLON) {
  42576. var serializedGeometries = [];
  42577. var serializeGeometry = function (geometry, serializationGeometries) {
  42578. if (serializedGeometries[geometry.id]) {
  42579. return;
  42580. }
  42581. if (geometry.doNotSerialize) {
  42582. return;
  42583. }
  42584. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42585. serializationGeometries.boxes.push(geometry.serialize());
  42586. }
  42587. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42588. serializationGeometries.spheres.push(geometry.serialize());
  42589. }
  42590. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42591. serializationGeometries.cylinders.push(geometry.serialize());
  42592. }
  42593. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42594. serializationGeometries.toruses.push(geometry.serialize());
  42595. }
  42596. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42597. serializationGeometries.grounds.push(geometry.serialize());
  42598. }
  42599. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42600. serializationGeometries.planes.push(geometry.serialize());
  42601. }
  42602. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42603. serializationGeometries.torusKnots.push(geometry.serialize());
  42604. }
  42605. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42606. throw new Error("Unknown primitive type");
  42607. }
  42608. else {
  42609. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42610. }
  42611. serializedGeometries[geometry.id] = true;
  42612. };
  42613. var serializeMesh = function (mesh, serializationScene) {
  42614. var serializationObject = {};
  42615. serializationObject.name = mesh.name;
  42616. serializationObject.id = mesh.id;
  42617. if (BABYLON.Tags.HasTags(mesh)) {
  42618. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42619. }
  42620. serializationObject.position = mesh.position.asArray();
  42621. if (mesh.rotationQuaternion) {
  42622. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42623. }
  42624. else if (mesh.rotation) {
  42625. serializationObject.rotation = mesh.rotation.asArray();
  42626. }
  42627. serializationObject.scaling = mesh.scaling.asArray();
  42628. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42629. serializationObject.isEnabled = mesh.isEnabled();
  42630. serializationObject.isVisible = mesh.isVisible;
  42631. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42632. serializationObject.pickable = mesh.isPickable;
  42633. serializationObject.receiveShadows = mesh.receiveShadows;
  42634. serializationObject.billboardMode = mesh.billboardMode;
  42635. serializationObject.visibility = mesh.visibility;
  42636. serializationObject.checkCollisions = mesh.checkCollisions;
  42637. serializationObject.isBlocker = mesh.isBlocker;
  42638. // Parent
  42639. if (mesh.parent) {
  42640. serializationObject.parentId = mesh.parent.id;
  42641. }
  42642. // Geometry
  42643. var geometry = mesh._geometry;
  42644. if (geometry) {
  42645. var geometryId = geometry.id;
  42646. serializationObject.geometryId = geometryId;
  42647. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42648. // 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
  42649. serializeGeometry(geometry, serializationScene.geometries);
  42650. }
  42651. // SubMeshes
  42652. serializationObject.subMeshes = [];
  42653. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42654. var subMesh = mesh.subMeshes[subIndex];
  42655. serializationObject.subMeshes.push({
  42656. materialIndex: subMesh.materialIndex,
  42657. verticesStart: subMesh.verticesStart,
  42658. verticesCount: subMesh.verticesCount,
  42659. indexStart: subMesh.indexStart,
  42660. indexCount: subMesh.indexCount
  42661. });
  42662. }
  42663. }
  42664. // Material
  42665. if (mesh.material) {
  42666. serializationObject.materialId = mesh.material.id;
  42667. }
  42668. else {
  42669. mesh.material = null;
  42670. }
  42671. // Skeleton
  42672. if (mesh.skeleton) {
  42673. serializationObject.skeletonId = mesh.skeleton.id;
  42674. }
  42675. // Physics
  42676. //TODO implement correct serialization for physics impostors.
  42677. if (mesh.getPhysicsImpostor()) {
  42678. serializationObject.physicsMass = mesh.getPhysicsMass();
  42679. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42680. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42681. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42682. }
  42683. // Metadata
  42684. if (mesh.metadata) {
  42685. serializationObject.metadata = mesh.metadata;
  42686. }
  42687. // Instances
  42688. serializationObject.instances = [];
  42689. for (var index = 0; index < mesh.instances.length; index++) {
  42690. var instance = mesh.instances[index];
  42691. var serializationInstance = {
  42692. name: instance.name,
  42693. position: instance.position.asArray(),
  42694. scaling: instance.scaling.asArray()
  42695. };
  42696. if (instance.rotationQuaternion) {
  42697. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42698. }
  42699. else if (instance.rotation) {
  42700. serializationInstance.rotation = instance.rotation.asArray();
  42701. }
  42702. serializationObject.instances.push(serializationInstance);
  42703. // Animations
  42704. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42705. serializationInstance.ranges = instance.serializeAnimationRanges();
  42706. }
  42707. // Animations
  42708. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42709. serializationObject.ranges = mesh.serializeAnimationRanges();
  42710. // Layer mask
  42711. serializationObject.layerMask = mesh.layerMask;
  42712. // Alpha
  42713. serializationObject.alphaIndex = mesh.alphaIndex;
  42714. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42715. // Overlay
  42716. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42717. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42718. serializationObject.renderOverlay = mesh.renderOverlay;
  42719. // Fog
  42720. serializationObject.applyFog = mesh.applyFog;
  42721. // Action Manager
  42722. if (mesh.actionManager) {
  42723. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42724. }
  42725. return serializationObject;
  42726. };
  42727. var finalizeSingleMesh = function (mesh, serializationObject) {
  42728. //only works if the mesh is already loaded
  42729. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42730. //serialize material
  42731. if (mesh.material) {
  42732. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42733. serializationObject.materials = serializationObject.materials || [];
  42734. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42735. serializationObject.materials.push(mesh.material.serialize());
  42736. }
  42737. }
  42738. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42739. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42740. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42741. serializationObject.multiMaterials.push(mesh.material.serialize());
  42742. }
  42743. }
  42744. }
  42745. //serialize geometry
  42746. var geometry = mesh._geometry;
  42747. if (geometry) {
  42748. if (!serializationObject.geometries) {
  42749. serializationObject.geometries = {};
  42750. serializationObject.geometries.boxes = [];
  42751. serializationObject.geometries.spheres = [];
  42752. serializationObject.geometries.cylinders = [];
  42753. serializationObject.geometries.toruses = [];
  42754. serializationObject.geometries.grounds = [];
  42755. serializationObject.geometries.planes = [];
  42756. serializationObject.geometries.torusKnots = [];
  42757. serializationObject.geometries.vertexData = [];
  42758. }
  42759. serializeGeometry(geometry, serializationObject.geometries);
  42760. }
  42761. // Skeletons
  42762. if (mesh.skeleton) {
  42763. serializationObject.skeletons = serializationObject.skeletons || [];
  42764. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42765. }
  42766. //serialize the actual mesh
  42767. serializationObject.meshes = serializationObject.meshes || [];
  42768. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42769. }
  42770. };
  42771. var SceneSerializer = (function () {
  42772. function SceneSerializer() {
  42773. }
  42774. SceneSerializer.ClearCache = function () {
  42775. serializedGeometries = [];
  42776. };
  42777. SceneSerializer.Serialize = function (scene) {
  42778. var serializationObject = {};
  42779. // Scene
  42780. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42781. serializationObject.autoClear = scene.autoClear;
  42782. serializationObject.clearColor = scene.clearColor.asArray();
  42783. serializationObject.ambientColor = scene.ambientColor.asArray();
  42784. serializationObject.gravity = scene.gravity.asArray();
  42785. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42786. serializationObject.workerCollisions = scene.workerCollisions;
  42787. // Fog
  42788. if (scene.fogMode && scene.fogMode !== 0) {
  42789. serializationObject.fogMode = scene.fogMode;
  42790. serializationObject.fogColor = scene.fogColor.asArray();
  42791. serializationObject.fogStart = scene.fogStart;
  42792. serializationObject.fogEnd = scene.fogEnd;
  42793. serializationObject.fogDensity = scene.fogDensity;
  42794. }
  42795. //Physics
  42796. if (scene.isPhysicsEnabled()) {
  42797. serializationObject.physicsEnabled = true;
  42798. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42799. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42800. }
  42801. // Metadata
  42802. if (scene.metadata) {
  42803. serializationObject.metadata = scene.metadata;
  42804. }
  42805. // Lights
  42806. serializationObject.lights = [];
  42807. var index;
  42808. var light;
  42809. for (index = 0; index < scene.lights.length; index++) {
  42810. light = scene.lights[index];
  42811. if (!light.doNotSerialize) {
  42812. serializationObject.lights.push(light.serialize());
  42813. }
  42814. }
  42815. // Cameras
  42816. serializationObject.cameras = [];
  42817. for (index = 0; index < scene.cameras.length; index++) {
  42818. var camera = scene.cameras[index];
  42819. if (!camera.doNotSerialize) {
  42820. serializationObject.cameras.push(camera.serialize());
  42821. }
  42822. }
  42823. if (scene.activeCamera) {
  42824. serializationObject.activeCameraID = scene.activeCamera.id;
  42825. }
  42826. // Animations
  42827. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42828. // Materials
  42829. serializationObject.materials = [];
  42830. serializationObject.multiMaterials = [];
  42831. var material;
  42832. for (index = 0; index < scene.materials.length; index++) {
  42833. material = scene.materials[index];
  42834. if (!material.doNotSerialize) {
  42835. serializationObject.materials.push(material.serialize());
  42836. }
  42837. }
  42838. // MultiMaterials
  42839. serializationObject.multiMaterials = [];
  42840. for (index = 0; index < scene.multiMaterials.length; index++) {
  42841. var multiMaterial = scene.multiMaterials[index];
  42842. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42843. }
  42844. // Skeletons
  42845. serializationObject.skeletons = [];
  42846. for (index = 0; index < scene.skeletons.length; index++) {
  42847. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42848. }
  42849. // Geometries
  42850. serializationObject.geometries = {};
  42851. serializationObject.geometries.boxes = [];
  42852. serializationObject.geometries.spheres = [];
  42853. serializationObject.geometries.cylinders = [];
  42854. serializationObject.geometries.toruses = [];
  42855. serializationObject.geometries.grounds = [];
  42856. serializationObject.geometries.planes = [];
  42857. serializationObject.geometries.torusKnots = [];
  42858. serializationObject.geometries.vertexData = [];
  42859. serializedGeometries = [];
  42860. var geometries = scene.getGeometries();
  42861. for (index = 0; index < geometries.length; index++) {
  42862. var geometry = geometries[index];
  42863. if (geometry.isReady()) {
  42864. serializeGeometry(geometry, serializationObject.geometries);
  42865. }
  42866. }
  42867. // Meshes
  42868. serializationObject.meshes = [];
  42869. for (index = 0; index < scene.meshes.length; index++) {
  42870. var abstractMesh = scene.meshes[index];
  42871. if (abstractMesh instanceof BABYLON.Mesh) {
  42872. var mesh = abstractMesh;
  42873. if (!mesh.doNotSerialize) {
  42874. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42875. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42876. }
  42877. }
  42878. }
  42879. }
  42880. // Particles Systems
  42881. serializationObject.particleSystems = [];
  42882. for (index = 0; index < scene.particleSystems.length; index++) {
  42883. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42884. }
  42885. // Lens flares
  42886. serializationObject.lensFlareSystems = [];
  42887. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42888. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42889. }
  42890. // Shadows
  42891. serializationObject.shadowGenerators = [];
  42892. for (index = 0; index < scene.lights.length; index++) {
  42893. light = scene.lights[index];
  42894. var shadowGenerator = light.getShadowGenerator();
  42895. // Only support serialization for official generator so far.
  42896. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42897. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42898. }
  42899. }
  42900. // Action Manager
  42901. if (scene.actionManager) {
  42902. serializationObject.actions = scene.actionManager.serialize("scene");
  42903. }
  42904. // Audio
  42905. serializationObject.sounds = [];
  42906. for (index = 0; index < scene.soundTracks.length; index++) {
  42907. var soundtrack = scene.soundTracks[index];
  42908. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42909. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42910. }
  42911. }
  42912. return serializationObject;
  42913. };
  42914. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42915. if (withParents === void 0) { withParents = false; }
  42916. if (withChildren === void 0) { withChildren = false; }
  42917. var serializationObject = {};
  42918. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42919. if (withParents || withChildren) {
  42920. //deliberate for loop! not for each, appended should be processed as well.
  42921. for (var i = 0; i < toSerialize.length; ++i) {
  42922. if (withChildren) {
  42923. toSerialize[i].getDescendants().forEach(function (node) {
  42924. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42925. toSerialize.push(node);
  42926. }
  42927. });
  42928. }
  42929. //make sure the array doesn't contain the object already
  42930. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42931. toSerialize.push(toSerialize[i].parent);
  42932. }
  42933. }
  42934. }
  42935. toSerialize.forEach(function (mesh) {
  42936. finalizeSingleMesh(mesh, serializationObject);
  42937. });
  42938. return serializationObject;
  42939. };
  42940. return SceneSerializer;
  42941. }());
  42942. BABYLON.SceneSerializer = SceneSerializer;
  42943. })(BABYLON || (BABYLON = {}));
  42944. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42945. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42946. // Huge respect for a such great lib.
  42947. // Earcut license:
  42948. // Copyright (c) 2016, Mapbox
  42949. //
  42950. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42951. // with or without fee is hereby granted, provided that the above copyright notice
  42952. // and this permission notice appear in all copies.
  42953. //
  42954. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42955. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42956. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42957. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42958. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42959. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42960. // THIS SOFTWARE.
  42961. var Earcut;
  42962. (function (Earcut) {
  42963. /**
  42964. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42965. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42966. * @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).
  42967. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42968. */
  42969. function earcut(data, holeIndices, dim) {
  42970. dim = dim || 2;
  42971. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42972. if (!outerNode)
  42973. return triangles;
  42974. var minX, minY, maxX, maxY, x, y, size;
  42975. if (hasHoles)
  42976. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42977. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42978. if (data.length > 80 * dim) {
  42979. minX = maxX = data[0];
  42980. minY = maxY = data[1];
  42981. for (var i = dim; i < outerLen; i += dim) {
  42982. x = data[i];
  42983. y = data[i + 1];
  42984. if (x < minX)
  42985. minX = x;
  42986. if (y < minY)
  42987. minY = y;
  42988. if (x > maxX)
  42989. maxX = x;
  42990. if (y > maxY)
  42991. maxY = y;
  42992. }
  42993. // minX, minY and size are later used to transform coords into integers for z-order calculation
  42994. size = Math.max(maxX - minX, maxY - minY);
  42995. }
  42996. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  42997. return triangles;
  42998. }
  42999. Earcut.earcut = earcut;
  43000. // create a circular doubly linked list from polygon points in the specified winding order
  43001. function linkedList(data, start, end, dim, clockwise) {
  43002. var i, last;
  43003. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43004. for (i = start; i < end; i += dim)
  43005. last = insertNode(i, data[i], data[i + 1], last);
  43006. }
  43007. else {
  43008. for (i = end - dim; i >= start; i -= dim)
  43009. last = insertNode(i, data[i], data[i + 1], last);
  43010. }
  43011. if (last && equals(last, last.next)) {
  43012. removeNode(last);
  43013. last = last.next;
  43014. }
  43015. return last;
  43016. }
  43017. // eliminate colinear or duplicate points
  43018. function filterPoints(start, end) {
  43019. if (!start)
  43020. return start;
  43021. if (!end)
  43022. end = start;
  43023. var p = start, again;
  43024. do {
  43025. again = false;
  43026. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43027. removeNode(p);
  43028. p = end = p.prev;
  43029. if (p === p.next)
  43030. return null;
  43031. again = true;
  43032. }
  43033. else {
  43034. p = p.next;
  43035. }
  43036. } while (again || p !== end);
  43037. return end;
  43038. }
  43039. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43040. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43041. if (!ear)
  43042. return;
  43043. // interlink polygon nodes in z-order
  43044. if (!pass && size)
  43045. indexCurve(ear, minX, minY, size);
  43046. var stop = ear, prev, next;
  43047. // iterate through ears, slicing them one by one
  43048. while (ear.prev !== ear.next) {
  43049. prev = ear.prev;
  43050. next = ear.next;
  43051. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43052. // cut off the triangle
  43053. triangles.push(prev.i / dim);
  43054. triangles.push(ear.i / dim);
  43055. triangles.push(next.i / dim);
  43056. removeNode(ear);
  43057. // skipping the next vertice leads to less sliver triangles
  43058. ear = next.next;
  43059. stop = next.next;
  43060. continue;
  43061. }
  43062. ear = next;
  43063. // if we looped through the whole remaining polygon and can't find any more ears
  43064. if (ear === stop) {
  43065. // try filtering points and slicing again
  43066. if (!pass) {
  43067. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43068. }
  43069. else if (pass === 1) {
  43070. ear = cureLocalIntersections(ear, triangles, dim);
  43071. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43072. }
  43073. else if (pass === 2) {
  43074. splitEarcut(ear, triangles, dim, minX, minY, size);
  43075. }
  43076. break;
  43077. }
  43078. }
  43079. }
  43080. // check whether a polygon node forms a valid ear with adjacent nodes
  43081. function isEar(ear) {
  43082. var a = ear.prev, b = ear, c = ear.next;
  43083. if (area(a, b, c) >= 0)
  43084. return false; // reflex, can't be an ear
  43085. // now make sure we don't have other points inside the potential ear
  43086. var p = ear.next.next;
  43087. while (p !== ear.prev) {
  43088. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43089. area(p.prev, p, p.next) >= 0)
  43090. return false;
  43091. p = p.next;
  43092. }
  43093. return true;
  43094. }
  43095. function isEarHashed(ear, minX, minY, size) {
  43096. var a = ear.prev, b = ear, c = ear.next;
  43097. if (area(a, b, c) >= 0)
  43098. return false; // reflex, can't be an ear
  43099. // triangle bbox; min & max are calculated like this for speed
  43100. 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);
  43101. // z-order range for the current triangle bbox;
  43102. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43103. // first look for points inside the triangle in increasing z-order
  43104. var p = ear.nextZ;
  43105. while (p && p.z <= maxZ) {
  43106. if (p !== ear.prev &&
  43107. p !== ear.next &&
  43108. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43109. area(p.prev, p, p.next) >= 0)
  43110. return false;
  43111. p = p.nextZ;
  43112. }
  43113. // then look for points in decreasing z-order
  43114. p = ear.prevZ;
  43115. while (p && p.z >= minZ) {
  43116. if (p !== ear.prev &&
  43117. p !== ear.next &&
  43118. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43119. area(p.prev, p, p.next) >= 0)
  43120. return false;
  43121. p = p.prevZ;
  43122. }
  43123. return true;
  43124. }
  43125. // go through all polygon nodes and cure small local self-intersections
  43126. function cureLocalIntersections(start, triangles, dim) {
  43127. var p = start;
  43128. do {
  43129. var a = p.prev, b = p.next.next;
  43130. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43131. triangles.push(a.i / dim);
  43132. triangles.push(p.i / dim);
  43133. triangles.push(b.i / dim);
  43134. // remove two nodes involved
  43135. removeNode(p);
  43136. removeNode(p.next);
  43137. p = start = b;
  43138. }
  43139. p = p.next;
  43140. } while (p !== start);
  43141. return p;
  43142. }
  43143. // try splitting polygon into two and triangulate them independently
  43144. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43145. // look for a valid diagonal that divides the polygon into two
  43146. var a = start;
  43147. do {
  43148. var b = a.next.next;
  43149. while (b !== a.prev) {
  43150. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43151. // split the polygon in two by the diagonal
  43152. var c = splitPolygon(a, b);
  43153. // filter colinear points around the cuts
  43154. a = filterPoints(a, a.next);
  43155. c = filterPoints(c, c.next);
  43156. // run earcut on each half
  43157. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43158. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43159. return;
  43160. }
  43161. b = b.next;
  43162. }
  43163. a = a.next;
  43164. } while (a !== start);
  43165. }
  43166. // link every hole into the outer loop, producing a single-ring polygon without holes
  43167. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43168. var queue = [], i, len, start, end, list;
  43169. for (i = 0, len = holeIndices.length; i < len; i++) {
  43170. start = holeIndices[i] * dim;
  43171. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43172. list = linkedList(data, start, end, dim, false);
  43173. if (list === list.next)
  43174. list.steiner = true;
  43175. queue.push(getLeftmost(list));
  43176. }
  43177. queue.sort(compareX);
  43178. // process holes from left to right
  43179. for (i = 0; i < queue.length; i++) {
  43180. eliminateHole(queue[i], outerNode);
  43181. outerNode = filterPoints(outerNode, outerNode.next);
  43182. }
  43183. return outerNode;
  43184. }
  43185. function compareX(a, b) {
  43186. return a.x - b.x;
  43187. }
  43188. // find a bridge between vertices that connects hole with an outer ring and and link it
  43189. function eliminateHole(hole, outerNode) {
  43190. outerNode = findHoleBridge(hole, outerNode);
  43191. if (outerNode) {
  43192. var b = splitPolygon(outerNode, hole);
  43193. filterPoints(b, b.next);
  43194. }
  43195. }
  43196. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43197. function findHoleBridge(hole, outerNode) {
  43198. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43199. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43200. // segment's endpoint with lesser x will be potential connection point
  43201. do {
  43202. if (hy <= p.y && hy >= p.next.y) {
  43203. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43204. if (x <= hx && x > qx) {
  43205. qx = x;
  43206. if (x === hx) {
  43207. if (hy === p.y)
  43208. return p;
  43209. if (hy === p.next.y)
  43210. return p.next;
  43211. }
  43212. m = p.x < p.next.x ? p : p.next;
  43213. }
  43214. }
  43215. p = p.next;
  43216. } while (p !== outerNode);
  43217. if (!m)
  43218. return null;
  43219. if (hx === qx)
  43220. return m.prev; // hole touches outer segment; pick lower endpoint
  43221. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43222. // if there are no points found, we have a valid connection;
  43223. // otherwise choose the point of the minimum angle with the ray as connection point
  43224. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43225. p = m.next;
  43226. while (p !== stop) {
  43227. if (hx >= p.x &&
  43228. p.x >= mx &&
  43229. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43230. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43231. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43232. m = p;
  43233. tanMin = tan;
  43234. }
  43235. }
  43236. p = p.next;
  43237. }
  43238. return m;
  43239. }
  43240. // interlink polygon nodes in z-order
  43241. function indexCurve(start, minX, minY, size) {
  43242. var p = start;
  43243. do {
  43244. if (p.z === null)
  43245. p.z = zOrder(p.x, p.y, minX, minY, size);
  43246. p.prevZ = p.prev;
  43247. p.nextZ = p.next;
  43248. p = p.next;
  43249. } while (p !== start);
  43250. p.prevZ.nextZ = null;
  43251. p.prevZ = null;
  43252. sortLinked(p);
  43253. }
  43254. // Simon Tatham's linked list merge sort algorithm
  43255. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43256. function sortLinked(list) {
  43257. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43258. do {
  43259. p = list;
  43260. list = null;
  43261. tail = null;
  43262. numMerges = 0;
  43263. while (p) {
  43264. numMerges++;
  43265. q = p;
  43266. pSize = 0;
  43267. for (i = 0; i < inSize; i++) {
  43268. pSize++;
  43269. q = q.nextZ;
  43270. if (!q)
  43271. break;
  43272. }
  43273. qSize = inSize;
  43274. while (pSize > 0 || (qSize > 0 && q)) {
  43275. if (pSize === 0) {
  43276. e = q;
  43277. q = q.nextZ;
  43278. qSize--;
  43279. }
  43280. else if (qSize === 0 || !q) {
  43281. e = p;
  43282. p = p.nextZ;
  43283. pSize--;
  43284. }
  43285. else if (p.z <= q.z) {
  43286. e = p;
  43287. p = p.nextZ;
  43288. pSize--;
  43289. }
  43290. else {
  43291. e = q;
  43292. q = q.nextZ;
  43293. qSize--;
  43294. }
  43295. if (tail)
  43296. tail.nextZ = e;
  43297. else
  43298. list = e;
  43299. e.prevZ = tail;
  43300. tail = e;
  43301. }
  43302. p = q;
  43303. }
  43304. tail.nextZ = null;
  43305. inSize *= 2;
  43306. } while (numMerges > 1);
  43307. return list;
  43308. }
  43309. // z-order of a point given coords and size of the data bounding box
  43310. function zOrder(x, y, minX, minY, size) {
  43311. // coords are transformed into non-negative 15-bit integer range
  43312. x = 32767 * (x - minX) / size;
  43313. y = 32767 * (y - minY) / size;
  43314. x = (x | (x << 8)) & 0x00FF00FF;
  43315. x = (x | (x << 4)) & 0x0F0F0F0F;
  43316. x = (x | (x << 2)) & 0x33333333;
  43317. x = (x | (x << 1)) & 0x55555555;
  43318. y = (y | (y << 8)) & 0x00FF00FF;
  43319. y = (y | (y << 4)) & 0x0F0F0F0F;
  43320. y = (y | (y << 2)) & 0x33333333;
  43321. y = (y | (y << 1)) & 0x55555555;
  43322. return x | (y << 1);
  43323. }
  43324. // find the leftmost node of a polygon ring
  43325. function getLeftmost(start) {
  43326. var p = start, leftmost = start;
  43327. do {
  43328. if (p.x < leftmost.x)
  43329. leftmost = p;
  43330. p = p.next;
  43331. } while (p !== start);
  43332. return leftmost;
  43333. }
  43334. // check if a point lies within a convex triangle
  43335. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43336. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43337. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43338. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43339. }
  43340. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43341. function isValidDiagonal(a, b) {
  43342. return a.next.i !== b.i &&
  43343. a.prev.i !== b.i &&
  43344. !intersectsPolygon(a, b) &&
  43345. locallyInside(a, b) &&
  43346. locallyInside(b, a) &&
  43347. middleInside(a, b);
  43348. }
  43349. // signed area of a triangle
  43350. function area(p, q, r) {
  43351. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43352. }
  43353. // check if two points are equal
  43354. function equals(p1, p2) {
  43355. return p1.x === p2.x && p1.y === p2.y;
  43356. }
  43357. // check if two segments intersect
  43358. function intersects(p1, q1, p2, q2) {
  43359. if ((equals(p1, q1) && equals(p2, q2)) ||
  43360. (equals(p1, q2) && equals(p2, q1)))
  43361. return true;
  43362. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43363. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43364. }
  43365. // check if a polygon diagonal intersects any polygon segments
  43366. function intersectsPolygon(a, b) {
  43367. var p = a;
  43368. do {
  43369. if (p.i !== a.i &&
  43370. p.next.i !== a.i &&
  43371. p.i !== b.i &&
  43372. p.next.i !== b.i &&
  43373. intersects(p, p.next, a, b))
  43374. return true;
  43375. p = p.next;
  43376. } while (p !== a);
  43377. return false;
  43378. }
  43379. // check if a polygon diagonal is locally inside the polygon
  43380. function locallyInside(a, b) {
  43381. return area(a.prev, a, a.next) < 0
  43382. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43383. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43384. }
  43385. // check if the middle point of a polygon diagonal is inside the polygon
  43386. function middleInside(a, b) {
  43387. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43388. do {
  43389. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43390. inside = !inside;
  43391. p = p.next;
  43392. } while (p !== a);
  43393. return inside;
  43394. }
  43395. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43396. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43397. function splitPolygon(a, b) {
  43398. 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;
  43399. a.next = b;
  43400. b.prev = a;
  43401. a2.next = an;
  43402. an.prev = a2;
  43403. b2.next = a2;
  43404. a2.prev = b2;
  43405. bp.next = b2;
  43406. b2.prev = bp;
  43407. return b2;
  43408. }
  43409. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43410. function insertNode(i, x, y, last) {
  43411. var p = new Node(i, x, y);
  43412. if (!last) {
  43413. p.prev = p;
  43414. p.next = p;
  43415. }
  43416. else {
  43417. p.next = last.next;
  43418. p.prev = last;
  43419. last.next.prev = p;
  43420. last.next = p;
  43421. }
  43422. return p;
  43423. }
  43424. function removeNode(p) {
  43425. p.next.prev = p.prev;
  43426. p.prev.next = p.next;
  43427. if (p.prevZ)
  43428. p.prevZ.nextZ = p.nextZ;
  43429. if (p.nextZ)
  43430. p.nextZ.prevZ = p.prevZ;
  43431. }
  43432. function Node(i, x, y) {
  43433. // vertice index in coordinates array
  43434. this.i = i;
  43435. // vertex coordinates
  43436. this.x = x;
  43437. this.y = y;
  43438. // previous and next vertice nodes in a polygon ring
  43439. this.prev = null;
  43440. this.next = null;
  43441. // z-order curve value
  43442. this.z = null;
  43443. // previous and next nodes in z-order
  43444. this.prevZ = null;
  43445. this.nextZ = null;
  43446. // indicates whether this is a steiner point
  43447. this.steiner = false;
  43448. }
  43449. /**
  43450. * return a percentage difference between the polygon area and its triangulation area;
  43451. * used to verify correctness of triangulation
  43452. */
  43453. function deviation(data, holeIndices, dim, triangles) {
  43454. var hasHoles = holeIndices && holeIndices.length;
  43455. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43456. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43457. if (hasHoles) {
  43458. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43459. var start = holeIndices[i] * dim;
  43460. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43461. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43462. }
  43463. }
  43464. var trianglesArea = 0;
  43465. for (i = 0; i < triangles.length; i += 3) {
  43466. var a = triangles[i] * dim;
  43467. var b = triangles[i + 1] * dim;
  43468. var c = triangles[i + 2] * dim;
  43469. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43470. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43471. }
  43472. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43473. }
  43474. Earcut.deviation = deviation;
  43475. ;
  43476. function signedArea(data, start, end, dim) {
  43477. var sum = 0;
  43478. for (var i = start, j = end - dim; i < end; i += dim) {
  43479. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43480. j = i;
  43481. }
  43482. return sum;
  43483. }
  43484. /**
  43485. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43486. */
  43487. function flatten(data) {
  43488. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43489. for (var i = 0; i < data.length; i++) {
  43490. for (var j = 0; j < data[i].length; j++) {
  43491. for (var d = 0; d < dim; d++)
  43492. result.vertices.push(data[i][j][d]);
  43493. }
  43494. if (i > 0) {
  43495. holeIndex += data[i - 1].length;
  43496. result.holes.push(holeIndex);
  43497. }
  43498. }
  43499. return result;
  43500. }
  43501. Earcut.flatten = flatten;
  43502. ;
  43503. })(Earcut || (Earcut = {}));
  43504. //# sourceMappingURL=babylon.earcut.js.map
  43505. var BABYLON;
  43506. (function (BABYLON) {
  43507. // Unique ID when we import meshes from Babylon to CSG
  43508. var currentCSGMeshId = 0;
  43509. // # class Vertex
  43510. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43511. // one to provide additional features like texture coordinates and vertex
  43512. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43513. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43514. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43515. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43516. // is not used anywhere else.
  43517. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43518. var Vertex = (function () {
  43519. function Vertex(pos, normal, uv) {
  43520. this.pos = pos;
  43521. this.normal = normal;
  43522. this.uv = uv;
  43523. }
  43524. Vertex.prototype.clone = function () {
  43525. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43526. };
  43527. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43528. // orientation of a polygon is flipped.
  43529. Vertex.prototype.flip = function () {
  43530. this.normal = this.normal.scale(-1);
  43531. };
  43532. // Create a new vertex between this vertex and `other` by linearly
  43533. // interpolating all properties using a parameter of `t`. Subclasses should
  43534. // override this to interpolate additional properties.
  43535. Vertex.prototype.interpolate = function (other, t) {
  43536. 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));
  43537. };
  43538. return Vertex;
  43539. }());
  43540. // # class Plane
  43541. // Represents a plane in 3D space.
  43542. var Plane = (function () {
  43543. function Plane(normal, w) {
  43544. this.normal = normal;
  43545. this.w = w;
  43546. }
  43547. Plane.FromPoints = function (a, b, c) {
  43548. var v0 = c.subtract(a);
  43549. var v1 = b.subtract(a);
  43550. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43551. return null;
  43552. }
  43553. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43554. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43555. };
  43556. Plane.prototype.clone = function () {
  43557. return new Plane(this.normal.clone(), this.w);
  43558. };
  43559. Plane.prototype.flip = function () {
  43560. this.normal.scaleInPlace(-1);
  43561. this.w = -this.w;
  43562. };
  43563. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43564. // fragments in the appropriate lists. Coplanar polygons go into either
  43565. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43566. // respect to this plane. Polygons in front or in back of this plane go into
  43567. // either `front` or `back`.
  43568. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43569. var COPLANAR = 0;
  43570. var FRONT = 1;
  43571. var BACK = 2;
  43572. var SPANNING = 3;
  43573. // Classify each point as well as the entire polygon into one of the above
  43574. // four classes.
  43575. var polygonType = 0;
  43576. var types = [];
  43577. var i;
  43578. var t;
  43579. for (i = 0; i < polygon.vertices.length; i++) {
  43580. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43581. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43582. polygonType |= type;
  43583. types.push(type);
  43584. }
  43585. // Put the polygon in the correct list, splitting it when necessary.
  43586. switch (polygonType) {
  43587. case COPLANAR:
  43588. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43589. break;
  43590. case FRONT:
  43591. front.push(polygon);
  43592. break;
  43593. case BACK:
  43594. back.push(polygon);
  43595. break;
  43596. case SPANNING:
  43597. var f = [], b = [];
  43598. for (i = 0; i < polygon.vertices.length; i++) {
  43599. var j = (i + 1) % polygon.vertices.length;
  43600. var ti = types[i], tj = types[j];
  43601. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43602. if (ti !== BACK)
  43603. f.push(vi);
  43604. if (ti !== FRONT)
  43605. b.push(ti !== BACK ? vi.clone() : vi);
  43606. if ((ti | tj) === SPANNING) {
  43607. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43608. var v = vi.interpolate(vj, t);
  43609. f.push(v);
  43610. b.push(v.clone());
  43611. }
  43612. }
  43613. var poly;
  43614. if (f.length >= 3) {
  43615. poly = new Polygon(f, polygon.shared);
  43616. if (poly.plane)
  43617. front.push(poly);
  43618. }
  43619. if (b.length >= 3) {
  43620. poly = new Polygon(b, polygon.shared);
  43621. if (poly.plane)
  43622. back.push(poly);
  43623. }
  43624. break;
  43625. }
  43626. };
  43627. return Plane;
  43628. }());
  43629. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43630. // point is on the plane.
  43631. Plane.EPSILON = 1e-5;
  43632. // # class Polygon
  43633. // Represents a convex polygon. The vertices used to initialize a polygon must
  43634. // be coplanar and form a convex loop.
  43635. //
  43636. // Each convex polygon has a `shared` property, which is shared between all
  43637. // polygons that are clones of each other or were split from the same polygon.
  43638. // This can be used to define per-polygon properties (such as surface color).
  43639. var Polygon = (function () {
  43640. function Polygon(vertices, shared) {
  43641. this.vertices = vertices;
  43642. this.shared = shared;
  43643. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43644. }
  43645. Polygon.prototype.clone = function () {
  43646. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43647. return new Polygon(vertices, this.shared);
  43648. };
  43649. Polygon.prototype.flip = function () {
  43650. this.vertices.reverse().map(function (v) { v.flip(); });
  43651. this.plane.flip();
  43652. };
  43653. return Polygon;
  43654. }());
  43655. // # class Node
  43656. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43657. // by picking a polygon to split along. That polygon (and all other coplanar
  43658. // polygons) are added directly to that node and the other polygons are added to
  43659. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43660. // no distinction between internal and leaf nodes.
  43661. var Node = (function () {
  43662. function Node(polygons) {
  43663. this.plane = null;
  43664. this.front = null;
  43665. this.back = null;
  43666. this.polygons = [];
  43667. if (polygons) {
  43668. this.build(polygons);
  43669. }
  43670. }
  43671. Node.prototype.clone = function () {
  43672. var node = new Node();
  43673. node.plane = this.plane && this.plane.clone();
  43674. node.front = this.front && this.front.clone();
  43675. node.back = this.back && this.back.clone();
  43676. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43677. return node;
  43678. };
  43679. // Convert solid space to empty space and empty space to solid space.
  43680. Node.prototype.invert = function () {
  43681. for (var i = 0; i < this.polygons.length; i++) {
  43682. this.polygons[i].flip();
  43683. }
  43684. if (this.plane) {
  43685. this.plane.flip();
  43686. }
  43687. if (this.front) {
  43688. this.front.invert();
  43689. }
  43690. if (this.back) {
  43691. this.back.invert();
  43692. }
  43693. var temp = this.front;
  43694. this.front = this.back;
  43695. this.back = temp;
  43696. };
  43697. // Recursively remove all polygons in `polygons` that are inside this BSP
  43698. // tree.
  43699. Node.prototype.clipPolygons = function (polygons) {
  43700. if (!this.plane)
  43701. return polygons.slice();
  43702. var front = [], back = [];
  43703. for (var i = 0; i < polygons.length; i++) {
  43704. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43705. }
  43706. if (this.front) {
  43707. front = this.front.clipPolygons(front);
  43708. }
  43709. if (this.back) {
  43710. back = this.back.clipPolygons(back);
  43711. }
  43712. else {
  43713. back = [];
  43714. }
  43715. return front.concat(back);
  43716. };
  43717. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43718. // `bsp`.
  43719. Node.prototype.clipTo = function (bsp) {
  43720. this.polygons = bsp.clipPolygons(this.polygons);
  43721. if (this.front)
  43722. this.front.clipTo(bsp);
  43723. if (this.back)
  43724. this.back.clipTo(bsp);
  43725. };
  43726. // Return a list of all polygons in this BSP tree.
  43727. Node.prototype.allPolygons = function () {
  43728. var polygons = this.polygons.slice();
  43729. if (this.front)
  43730. polygons = polygons.concat(this.front.allPolygons());
  43731. if (this.back)
  43732. polygons = polygons.concat(this.back.allPolygons());
  43733. return polygons;
  43734. };
  43735. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43736. // new polygons are filtered down to the bottom of the tree and become new
  43737. // nodes there. Each set of polygons is partitioned using the first polygon
  43738. // (no heuristic is used to pick a good split).
  43739. Node.prototype.build = function (polygons) {
  43740. if (!polygons.length)
  43741. return;
  43742. if (!this.plane)
  43743. this.plane = polygons[0].plane.clone();
  43744. var front = [], back = [];
  43745. for (var i = 0; i < polygons.length; i++) {
  43746. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43747. }
  43748. if (front.length) {
  43749. if (!this.front)
  43750. this.front = new Node();
  43751. this.front.build(front);
  43752. }
  43753. if (back.length) {
  43754. if (!this.back)
  43755. this.back = new Node();
  43756. this.back.build(back);
  43757. }
  43758. };
  43759. return Node;
  43760. }());
  43761. var CSG = (function () {
  43762. function CSG() {
  43763. this.polygons = new Array();
  43764. }
  43765. // Convert BABYLON.Mesh to BABYLON.CSG
  43766. CSG.FromMesh = function (mesh) {
  43767. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43768. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43769. if (mesh instanceof BABYLON.Mesh) {
  43770. mesh.computeWorldMatrix(true);
  43771. matrix = mesh.getWorldMatrix();
  43772. meshPosition = mesh.position.clone();
  43773. meshRotation = mesh.rotation.clone();
  43774. if (mesh.rotationQuaternion) {
  43775. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43776. }
  43777. meshScaling = mesh.scaling.clone();
  43778. }
  43779. else {
  43780. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43781. }
  43782. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43783. var subMeshes = mesh.subMeshes;
  43784. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43785. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43786. vertices = [];
  43787. for (var j = 0; j < 3; j++) {
  43788. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43789. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43790. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43791. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43792. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43793. vertex = new Vertex(position, normal, uv);
  43794. vertices.push(vertex);
  43795. }
  43796. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43797. // To handle the case of degenerated triangle
  43798. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43799. if (polygon.plane)
  43800. polygons.push(polygon);
  43801. }
  43802. }
  43803. var csg = CSG.FromPolygons(polygons);
  43804. csg.matrix = matrix;
  43805. csg.position = meshPosition;
  43806. csg.rotation = meshRotation;
  43807. csg.scaling = meshScaling;
  43808. csg.rotationQuaternion = meshRotationQuaternion;
  43809. currentCSGMeshId++;
  43810. return csg;
  43811. };
  43812. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43813. CSG.FromPolygons = function (polygons) {
  43814. var csg = new CSG();
  43815. csg.polygons = polygons;
  43816. return csg;
  43817. };
  43818. CSG.prototype.clone = function () {
  43819. var csg = new CSG();
  43820. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43821. csg.copyTransformAttributes(this);
  43822. return csg;
  43823. };
  43824. CSG.prototype.toPolygons = function () {
  43825. return this.polygons;
  43826. };
  43827. CSG.prototype.union = function (csg) {
  43828. var a = new Node(this.clone().polygons);
  43829. var b = new Node(csg.clone().polygons);
  43830. a.clipTo(b);
  43831. b.clipTo(a);
  43832. b.invert();
  43833. b.clipTo(a);
  43834. b.invert();
  43835. a.build(b.allPolygons());
  43836. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43837. };
  43838. CSG.prototype.unionInPlace = function (csg) {
  43839. var a = new Node(this.polygons);
  43840. var b = new Node(csg.polygons);
  43841. a.clipTo(b);
  43842. b.clipTo(a);
  43843. b.invert();
  43844. b.clipTo(a);
  43845. b.invert();
  43846. a.build(b.allPolygons());
  43847. this.polygons = a.allPolygons();
  43848. };
  43849. CSG.prototype.subtract = function (csg) {
  43850. var a = new Node(this.clone().polygons);
  43851. var b = new Node(csg.clone().polygons);
  43852. a.invert();
  43853. a.clipTo(b);
  43854. b.clipTo(a);
  43855. b.invert();
  43856. b.clipTo(a);
  43857. b.invert();
  43858. a.build(b.allPolygons());
  43859. a.invert();
  43860. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43861. };
  43862. CSG.prototype.subtractInPlace = function (csg) {
  43863. var a = new Node(this.polygons);
  43864. var b = new Node(csg.polygons);
  43865. a.invert();
  43866. a.clipTo(b);
  43867. b.clipTo(a);
  43868. b.invert();
  43869. b.clipTo(a);
  43870. b.invert();
  43871. a.build(b.allPolygons());
  43872. a.invert();
  43873. this.polygons = a.allPolygons();
  43874. };
  43875. CSG.prototype.intersect = function (csg) {
  43876. var a = new Node(this.clone().polygons);
  43877. var b = new Node(csg.clone().polygons);
  43878. a.invert();
  43879. b.clipTo(a);
  43880. b.invert();
  43881. a.clipTo(b);
  43882. b.clipTo(a);
  43883. a.build(b.allPolygons());
  43884. a.invert();
  43885. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43886. };
  43887. CSG.prototype.intersectInPlace = function (csg) {
  43888. var a = new Node(this.polygons);
  43889. var b = new Node(csg.polygons);
  43890. a.invert();
  43891. b.clipTo(a);
  43892. b.invert();
  43893. a.clipTo(b);
  43894. b.clipTo(a);
  43895. a.build(b.allPolygons());
  43896. a.invert();
  43897. this.polygons = a.allPolygons();
  43898. };
  43899. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43900. // not modified.
  43901. CSG.prototype.inverse = function () {
  43902. var csg = this.clone();
  43903. csg.inverseInPlace();
  43904. return csg;
  43905. };
  43906. CSG.prototype.inverseInPlace = function () {
  43907. this.polygons.map(function (p) { p.flip(); });
  43908. };
  43909. // This is used to keep meshes transformations so they can be restored
  43910. // when we build back a Babylon Mesh
  43911. // NB : All CSG operations are performed in world coordinates
  43912. CSG.prototype.copyTransformAttributes = function (csg) {
  43913. this.matrix = csg.matrix;
  43914. this.position = csg.position;
  43915. this.rotation = csg.rotation;
  43916. this.scaling = csg.scaling;
  43917. this.rotationQuaternion = csg.rotationQuaternion;
  43918. return this;
  43919. };
  43920. // Build Raw mesh from CSG
  43921. // Coordinates here are in world space
  43922. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43923. var matrix = this.matrix.clone();
  43924. matrix.invert();
  43925. 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;
  43926. if (keepSubMeshes) {
  43927. // Sort Polygons, since subMeshes are indices range
  43928. polygons.sort(function (a, b) {
  43929. if (a.shared.meshId === b.shared.meshId) {
  43930. return a.shared.subMeshId - b.shared.subMeshId;
  43931. }
  43932. else {
  43933. return a.shared.meshId - b.shared.meshId;
  43934. }
  43935. });
  43936. }
  43937. for (var i = 0, il = polygons.length; i < il; i++) {
  43938. polygon = polygons[i];
  43939. // Building SubMeshes
  43940. if (!subMesh_dict[polygon.shared.meshId]) {
  43941. subMesh_dict[polygon.shared.meshId] = {};
  43942. }
  43943. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43944. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43945. indexStart: +Infinity,
  43946. indexEnd: -Infinity,
  43947. materialIndex: polygon.shared.materialIndex
  43948. };
  43949. }
  43950. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43951. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43952. polygonIndices[0] = 0;
  43953. polygonIndices[1] = j - 1;
  43954. polygonIndices[2] = j;
  43955. for (var k = 0; k < 3; k++) {
  43956. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43957. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43958. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43959. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43960. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43961. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43962. // Check if 2 points can be merged
  43963. if (!(typeof vertex_idx !== 'undefined' &&
  43964. normals[vertex_idx * 3] === localNormal.x &&
  43965. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43966. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43967. uvs[vertex_idx * 2] === uv.x &&
  43968. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43969. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43970. uvs.push(uv.x, uv.y);
  43971. normals.push(normal.x, normal.y, normal.z);
  43972. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43973. }
  43974. indices.push(vertex_idx);
  43975. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43976. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43977. currentIndex++;
  43978. }
  43979. }
  43980. }
  43981. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43982. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43983. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43984. mesh.setIndices(indices);
  43985. if (keepSubMeshes) {
  43986. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43987. var materialIndexOffset = 0, materialMaxIndex;
  43988. mesh.subMeshes = new Array();
  43989. for (var m in subMesh_dict) {
  43990. materialMaxIndex = -1;
  43991. for (var sm in subMesh_dict[m]) {
  43992. subMesh_obj = subMesh_dict[m][sm];
  43993. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  43994. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  43995. }
  43996. materialIndexOffset += ++materialMaxIndex;
  43997. }
  43998. }
  43999. return mesh;
  44000. };
  44001. // Build Mesh from CSG taking material and transforms into account
  44002. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44003. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44004. mesh.material = material;
  44005. mesh.position.copyFrom(this.position);
  44006. mesh.rotation.copyFrom(this.rotation);
  44007. if (this.rotationQuaternion) {
  44008. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44009. }
  44010. mesh.scaling.copyFrom(this.scaling);
  44011. mesh.computeWorldMatrix(true);
  44012. return mesh;
  44013. };
  44014. return CSG;
  44015. }());
  44016. BABYLON.CSG = CSG;
  44017. })(BABYLON || (BABYLON = {}));
  44018. //# sourceMappingURL=babylon.csg.js.map
  44019. var BABYLON;
  44020. (function (BABYLON) {
  44021. var VRDistortionCorrectionPostProcess = (function (_super) {
  44022. __extends(VRDistortionCorrectionPostProcess, _super);
  44023. //ANY
  44024. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44025. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44026. 'LensCenter',
  44027. 'Scale',
  44028. 'ScaleIn',
  44029. 'HmdWarpParam'
  44030. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44031. _this._isRightEye = isRightEye;
  44032. _this._distortionFactors = vrMetrics.distortionK;
  44033. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44034. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44035. _this.onSizeChangedObservable.add(function () {
  44036. _this.aspectRatio = _this.width * .5 / _this.height;
  44037. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44038. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44039. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44040. });
  44041. _this.onApplyObservable.add(function (effect) {
  44042. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44043. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44044. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44045. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44046. });
  44047. return _this;
  44048. }
  44049. return VRDistortionCorrectionPostProcess;
  44050. }(BABYLON.PostProcess));
  44051. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44052. })(BABYLON || (BABYLON = {}));
  44053. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44054. // Mainly based on these 2 articles :
  44055. // 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
  44056. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44057. var BABYLON;
  44058. (function (BABYLON) {
  44059. var JoystickAxis;
  44060. (function (JoystickAxis) {
  44061. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44062. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44063. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44064. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44065. var VirtualJoystick = (function () {
  44066. function VirtualJoystick(leftJoystick) {
  44067. var _this = this;
  44068. if (leftJoystick) {
  44069. this._leftJoystick = true;
  44070. }
  44071. else {
  44072. this._leftJoystick = false;
  44073. }
  44074. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44075. VirtualJoystick._globalJoystickIndex++;
  44076. // By default left & right arrow keys are moving the X
  44077. // and up & down keys are moving the Y
  44078. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44079. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44080. this.reverseLeftRight = false;
  44081. this.reverseUpDown = false;
  44082. // collections of pointers
  44083. this._touches = new BABYLON.StringDictionary();
  44084. this.deltaPosition = BABYLON.Vector3.Zero();
  44085. this._joystickSensibility = 25;
  44086. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44087. this._rotationSpeed = 25;
  44088. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44089. this._rotateOnAxisRelativeToMesh = false;
  44090. this._onResize = function (evt) {
  44091. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44092. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44093. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44094. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44095. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44096. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44097. };
  44098. // injecting a canvas element on top of the canvas 3D game
  44099. if (!VirtualJoystick.vjCanvas) {
  44100. window.addEventListener("resize", this._onResize, false);
  44101. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44102. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44103. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44104. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44105. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44106. VirtualJoystick.vjCanvas.style.width = "100%";
  44107. VirtualJoystick.vjCanvas.style.height = "100%";
  44108. VirtualJoystick.vjCanvas.style.position = "absolute";
  44109. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44110. VirtualJoystick.vjCanvas.style.top = "0px";
  44111. VirtualJoystick.vjCanvas.style.left = "0px";
  44112. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44113. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44114. // Support for jQuery PEP polyfill
  44115. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44116. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44117. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44118. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44119. document.body.appendChild(VirtualJoystick.vjCanvas);
  44120. }
  44121. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44122. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44123. this.pressed = false;
  44124. // default joystick color
  44125. this._joystickColor = "cyan";
  44126. this._joystickPointerID = -1;
  44127. // current joystick position
  44128. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44129. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44130. // origin joystick position
  44131. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44132. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44133. this._onPointerDownHandlerRef = function (evt) {
  44134. _this._onPointerDown(evt);
  44135. };
  44136. this._onPointerMoveHandlerRef = function (evt) {
  44137. _this._onPointerMove(evt);
  44138. };
  44139. this._onPointerOutHandlerRef = function (evt) {
  44140. _this._onPointerUp(evt);
  44141. };
  44142. this._onPointerUpHandlerRef = function (evt) {
  44143. _this._onPointerUp(evt);
  44144. };
  44145. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44146. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44147. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44148. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44149. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44150. evt.preventDefault(); // Disables system menu
  44151. }, false);
  44152. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44153. }
  44154. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44155. this._joystickSensibility = newJoystickSensibility;
  44156. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44157. };
  44158. VirtualJoystick.prototype._onPointerDown = function (e) {
  44159. var positionOnScreenCondition;
  44160. e.preventDefault();
  44161. if (this._leftJoystick === true) {
  44162. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44163. }
  44164. else {
  44165. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44166. }
  44167. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44168. // First contact will be dedicated to the virtual joystick
  44169. this._joystickPointerID = e.pointerId;
  44170. this._joystickPointerStartPos.x = e.clientX;
  44171. this._joystickPointerStartPos.y = e.clientY;
  44172. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44173. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44174. this._deltaJoystickVector.x = 0;
  44175. this._deltaJoystickVector.y = 0;
  44176. this.pressed = true;
  44177. this._touches.add(e.pointerId.toString(), e);
  44178. }
  44179. else {
  44180. // You can only trigger the action buttons with a joystick declared
  44181. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44182. this._action();
  44183. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44184. }
  44185. }
  44186. };
  44187. VirtualJoystick.prototype._onPointerMove = function (e) {
  44188. // If the current pointer is the one associated to the joystick (first touch contact)
  44189. if (this._joystickPointerID == e.pointerId) {
  44190. this._joystickPointerPos.x = e.clientX;
  44191. this._joystickPointerPos.y = e.clientY;
  44192. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44193. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44194. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44195. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44196. switch (this._axisTargetedByLeftAndRight) {
  44197. case JoystickAxis.X:
  44198. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44199. break;
  44200. case JoystickAxis.Y:
  44201. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44202. break;
  44203. case JoystickAxis.Z:
  44204. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44205. break;
  44206. }
  44207. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44208. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44209. switch (this._axisTargetedByUpAndDown) {
  44210. case JoystickAxis.X:
  44211. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44212. break;
  44213. case JoystickAxis.Y:
  44214. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44215. break;
  44216. case JoystickAxis.Z:
  44217. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44218. break;
  44219. }
  44220. }
  44221. else {
  44222. var data = this._touches.get(e.pointerId.toString());
  44223. if (data) {
  44224. data.x = e.clientX;
  44225. data.y = e.clientY;
  44226. }
  44227. }
  44228. };
  44229. VirtualJoystick.prototype._onPointerUp = function (e) {
  44230. if (this._joystickPointerID == e.pointerId) {
  44231. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44232. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44233. this._joystickPointerID = -1;
  44234. this.pressed = false;
  44235. }
  44236. else {
  44237. var touch = this._touches.get(e.pointerId.toString());
  44238. if (touch) {
  44239. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44240. }
  44241. }
  44242. this._deltaJoystickVector.x = 0;
  44243. this._deltaJoystickVector.y = 0;
  44244. this._touches.remove(e.pointerId.toString());
  44245. };
  44246. /**
  44247. * Change the color of the virtual joystick
  44248. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44249. */
  44250. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44251. this._joystickColor = newColor;
  44252. };
  44253. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44254. this._action = action;
  44255. };
  44256. // Define which axis you'd like to control for left & right
  44257. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44258. switch (axis) {
  44259. case JoystickAxis.X:
  44260. case JoystickAxis.Y:
  44261. case JoystickAxis.Z:
  44262. this._axisTargetedByLeftAndRight = axis;
  44263. break;
  44264. default:
  44265. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44266. break;
  44267. }
  44268. };
  44269. // Define which axis you'd like to control for up & down
  44270. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44271. switch (axis) {
  44272. case JoystickAxis.X:
  44273. case JoystickAxis.Y:
  44274. case JoystickAxis.Z:
  44275. this._axisTargetedByUpAndDown = axis;
  44276. break;
  44277. default:
  44278. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44279. break;
  44280. }
  44281. };
  44282. VirtualJoystick.prototype._clearCanvas = function () {
  44283. if (this._leftJoystick) {
  44284. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44285. }
  44286. else {
  44287. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44288. }
  44289. };
  44290. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44291. var _this = this;
  44292. if (this.pressed) {
  44293. this._touches.forEach(function (touch) {
  44294. if (touch.pointerId === _this._joystickPointerID) {
  44295. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44296. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44297. VirtualJoystick.vjCanvasContext.beginPath();
  44298. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44299. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44300. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44301. VirtualJoystick.vjCanvasContext.stroke();
  44302. VirtualJoystick.vjCanvasContext.closePath();
  44303. VirtualJoystick.vjCanvasContext.beginPath();
  44304. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44305. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44306. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44307. VirtualJoystick.vjCanvasContext.stroke();
  44308. VirtualJoystick.vjCanvasContext.closePath();
  44309. VirtualJoystick.vjCanvasContext.beginPath();
  44310. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44311. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44312. VirtualJoystick.vjCanvasContext.stroke();
  44313. VirtualJoystick.vjCanvasContext.closePath();
  44314. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44315. }
  44316. else {
  44317. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44318. VirtualJoystick.vjCanvasContext.beginPath();
  44319. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44320. VirtualJoystick.vjCanvasContext.beginPath();
  44321. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44322. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44323. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44324. VirtualJoystick.vjCanvasContext.stroke();
  44325. VirtualJoystick.vjCanvasContext.closePath();
  44326. touch.prevX = touch.x;
  44327. touch.prevY = touch.y;
  44328. }
  44329. ;
  44330. });
  44331. }
  44332. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44333. };
  44334. VirtualJoystick.prototype.releaseCanvas = function () {
  44335. if (VirtualJoystick.vjCanvas) {
  44336. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44337. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44338. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44339. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44340. window.removeEventListener("resize", this._onResize);
  44341. document.body.removeChild(VirtualJoystick.vjCanvas);
  44342. VirtualJoystick.vjCanvas = null;
  44343. }
  44344. };
  44345. return VirtualJoystick;
  44346. }());
  44347. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44348. VirtualJoystick._globalJoystickIndex = 0;
  44349. BABYLON.VirtualJoystick = VirtualJoystick;
  44350. })(BABYLON || (BABYLON = {}));
  44351. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44352. var BABYLON;
  44353. (function (BABYLON) {
  44354. // We're mainly based on the logic defined into the FreeCamera code
  44355. var VirtualJoysticksCamera = (function (_super) {
  44356. __extends(VirtualJoysticksCamera, _super);
  44357. function VirtualJoysticksCamera(name, position, scene) {
  44358. var _this = _super.call(this, name, position, scene) || this;
  44359. _this.inputs.addVirtualJoystick();
  44360. return _this;
  44361. }
  44362. VirtualJoysticksCamera.prototype.getClassName = function () {
  44363. return "VirtualJoysticksCamera";
  44364. };
  44365. return VirtualJoysticksCamera;
  44366. }(BABYLON.FreeCamera));
  44367. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44368. })(BABYLON || (BABYLON = {}));
  44369. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44370. var BABYLON;
  44371. (function (BABYLON) {
  44372. var FreeCameraVirtualJoystickInput = (function () {
  44373. function FreeCameraVirtualJoystickInput() {
  44374. }
  44375. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44376. return this._leftjoystick;
  44377. };
  44378. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44379. return this._rightjoystick;
  44380. };
  44381. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44382. if (this._leftjoystick) {
  44383. var camera = this.camera;
  44384. var speed = camera._computeLocalCameraSpeed() * 50;
  44385. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44386. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44387. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44388. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44389. if (!this._leftjoystick.pressed) {
  44390. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44391. }
  44392. if (!this._rightjoystick.pressed) {
  44393. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44394. }
  44395. }
  44396. };
  44397. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44398. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44399. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44400. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44401. this._leftjoystick.setJoystickSensibility(0.15);
  44402. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44403. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44404. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44405. this._rightjoystick.reverseUpDown = true;
  44406. this._rightjoystick.setJoystickSensibility(0.05);
  44407. this._rightjoystick.setJoystickColor("yellow");
  44408. };
  44409. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44410. this._leftjoystick.releaseCanvas();
  44411. this._rightjoystick.releaseCanvas();
  44412. };
  44413. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44414. return "FreeCameraVirtualJoystickInput";
  44415. };
  44416. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44417. return "virtualJoystick";
  44418. };
  44419. return FreeCameraVirtualJoystickInput;
  44420. }());
  44421. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44422. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44423. })(BABYLON || (BABYLON = {}));
  44424. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44425. var BABYLON;
  44426. (function (BABYLON) {
  44427. var AnaglyphPostProcess = (function (_super) {
  44428. __extends(AnaglyphPostProcess, _super);
  44429. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44430. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44431. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44432. _this.onApplyObservable.add(function (effect) {
  44433. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44434. });
  44435. return _this;
  44436. }
  44437. return AnaglyphPostProcess;
  44438. }(BABYLON.PostProcess));
  44439. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44440. })(BABYLON || (BABYLON = {}));
  44441. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44442. var BABYLON;
  44443. (function (BABYLON) {
  44444. var OutlineRenderer = (function () {
  44445. function OutlineRenderer(scene) {
  44446. this._scene = scene;
  44447. }
  44448. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44449. var _this = this;
  44450. if (useOverlay === void 0) { useOverlay = false; }
  44451. var scene = this._scene;
  44452. var engine = this._scene.getEngine();
  44453. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44454. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44455. return;
  44456. }
  44457. var mesh = subMesh.getRenderingMesh();
  44458. var material = subMesh.getMaterial();
  44459. engine.enableEffect(this._effect);
  44460. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44461. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44462. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44463. // Bones
  44464. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44465. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44466. }
  44467. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44468. // Alpha test
  44469. if (material && material.needAlphaTesting()) {
  44470. var alphaTexture = material.getAlphaTestTexture();
  44471. this._effect.setTexture("diffuseSampler", alphaTexture);
  44472. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44473. }
  44474. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44475. };
  44476. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44477. var defines = [];
  44478. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44479. var mesh = subMesh.getMesh();
  44480. var material = subMesh.getMaterial();
  44481. // Alpha test
  44482. if (material && material.needAlphaTesting()) {
  44483. defines.push("#define ALPHATEST");
  44484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44485. attribs.push(BABYLON.VertexBuffer.UVKind);
  44486. defines.push("#define UV1");
  44487. }
  44488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44489. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44490. defines.push("#define UV2");
  44491. }
  44492. }
  44493. // Bones
  44494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44497. if (mesh.numBoneInfluencers > 4) {
  44498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44500. }
  44501. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44502. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44503. }
  44504. else {
  44505. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44506. }
  44507. // Instances
  44508. if (useInstances) {
  44509. defines.push("#define INSTANCES");
  44510. attribs.push("world0");
  44511. attribs.push("world1");
  44512. attribs.push("world2");
  44513. attribs.push("world3");
  44514. }
  44515. // Get correct effect
  44516. var join = defines.join("\n");
  44517. if (this._cachedDefines !== join) {
  44518. this._cachedDefines = join;
  44519. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44520. }
  44521. return this._effect.isReady();
  44522. };
  44523. return OutlineRenderer;
  44524. }());
  44525. BABYLON.OutlineRenderer = OutlineRenderer;
  44526. })(BABYLON || (BABYLON = {}));
  44527. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44528. var BABYLON;
  44529. (function (BABYLON) {
  44530. var MeshAssetTask = (function () {
  44531. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44532. this.name = name;
  44533. this.meshesNames = meshesNames;
  44534. this.rootUrl = rootUrl;
  44535. this.sceneFilename = sceneFilename;
  44536. this.isCompleted = false;
  44537. }
  44538. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44539. var _this = this;
  44540. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44541. _this.loadedMeshes = meshes;
  44542. _this.loadedParticleSystems = particleSystems;
  44543. _this.loadedSkeletons = skeletons;
  44544. _this.isCompleted = true;
  44545. if (_this.onSuccess) {
  44546. _this.onSuccess(_this);
  44547. }
  44548. onSuccess();
  44549. }, null, function () {
  44550. if (_this.onError) {
  44551. _this.onError(_this);
  44552. }
  44553. onError();
  44554. });
  44555. };
  44556. return MeshAssetTask;
  44557. }());
  44558. BABYLON.MeshAssetTask = MeshAssetTask;
  44559. var TextFileAssetTask = (function () {
  44560. function TextFileAssetTask(name, url) {
  44561. this.name = name;
  44562. this.url = url;
  44563. this.isCompleted = false;
  44564. }
  44565. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44566. var _this = this;
  44567. BABYLON.Tools.LoadFile(this.url, function (data) {
  44568. _this.text = data;
  44569. _this.isCompleted = true;
  44570. if (_this.onSuccess) {
  44571. _this.onSuccess(_this);
  44572. }
  44573. onSuccess();
  44574. }, null, scene.database, false, function () {
  44575. if (_this.onError) {
  44576. _this.onError(_this);
  44577. }
  44578. onError();
  44579. });
  44580. };
  44581. return TextFileAssetTask;
  44582. }());
  44583. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44584. var BinaryFileAssetTask = (function () {
  44585. function BinaryFileAssetTask(name, url) {
  44586. this.name = name;
  44587. this.url = url;
  44588. this.isCompleted = false;
  44589. }
  44590. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44591. var _this = this;
  44592. BABYLON.Tools.LoadFile(this.url, function (data) {
  44593. _this.data = data;
  44594. _this.isCompleted = true;
  44595. if (_this.onSuccess) {
  44596. _this.onSuccess(_this);
  44597. }
  44598. onSuccess();
  44599. }, null, scene.database, true, function () {
  44600. if (_this.onError) {
  44601. _this.onError(_this);
  44602. }
  44603. onError();
  44604. });
  44605. };
  44606. return BinaryFileAssetTask;
  44607. }());
  44608. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44609. var ImageAssetTask = (function () {
  44610. function ImageAssetTask(name, url) {
  44611. this.name = name;
  44612. this.url = url;
  44613. this.isCompleted = false;
  44614. }
  44615. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44616. var _this = this;
  44617. var img = new Image();
  44618. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44619. img.onload = function () {
  44620. _this.image = img;
  44621. _this.isCompleted = true;
  44622. if (_this.onSuccess) {
  44623. _this.onSuccess(_this);
  44624. }
  44625. onSuccess();
  44626. };
  44627. img.onerror = function () {
  44628. if (_this.onError) {
  44629. _this.onError(_this);
  44630. }
  44631. onError();
  44632. };
  44633. img.src = this.url;
  44634. };
  44635. return ImageAssetTask;
  44636. }());
  44637. BABYLON.ImageAssetTask = ImageAssetTask;
  44638. var TextureAssetTask = (function () {
  44639. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44641. this.name = name;
  44642. this.url = url;
  44643. this.noMipmap = noMipmap;
  44644. this.invertY = invertY;
  44645. this.samplingMode = samplingMode;
  44646. this.isCompleted = false;
  44647. }
  44648. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44649. var _this = this;
  44650. var onload = function () {
  44651. _this.isCompleted = true;
  44652. if (_this.onSuccess) {
  44653. _this.onSuccess(_this);
  44654. }
  44655. onSuccess();
  44656. };
  44657. var onerror = function () {
  44658. if (_this.onError) {
  44659. _this.onError(_this);
  44660. }
  44661. onError();
  44662. };
  44663. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44664. };
  44665. return TextureAssetTask;
  44666. }());
  44667. BABYLON.TextureAssetTask = TextureAssetTask;
  44668. var CubeTextureAssetTask = (function () {
  44669. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44670. this.name = name;
  44671. this.url = url;
  44672. this.extensions = extensions;
  44673. this.noMipmap = noMipmap;
  44674. this.files = files;
  44675. this.isCompleted = false;
  44676. }
  44677. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44678. var _this = this;
  44679. var onload = function () {
  44680. _this.isCompleted = true;
  44681. if (_this.onSuccess) {
  44682. _this.onSuccess(_this);
  44683. }
  44684. onSuccess();
  44685. };
  44686. var onerror = function () {
  44687. if (_this.onError) {
  44688. _this.onError(_this);
  44689. }
  44690. onError();
  44691. };
  44692. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44693. };
  44694. return CubeTextureAssetTask;
  44695. }());
  44696. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44697. var AssetsManager = (function () {
  44698. function AssetsManager(scene) {
  44699. this.tasks = new Array();
  44700. this.waitingTasksCount = 0;
  44701. this.useDefaultLoadingScreen = true;
  44702. this._scene = scene;
  44703. }
  44704. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44705. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44706. this.tasks.push(task);
  44707. return task;
  44708. };
  44709. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44710. var task = new TextFileAssetTask(taskName, url);
  44711. this.tasks.push(task);
  44712. return task;
  44713. };
  44714. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44715. var task = new BinaryFileAssetTask(taskName, url);
  44716. this.tasks.push(task);
  44717. return task;
  44718. };
  44719. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44720. var task = new ImageAssetTask(taskName, url);
  44721. this.tasks.push(task);
  44722. return task;
  44723. };
  44724. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44726. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44727. this.tasks.push(task);
  44728. return task;
  44729. };
  44730. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44731. this.waitingTasksCount--;
  44732. if (this.waitingTasksCount === 0) {
  44733. if (this.onFinish) {
  44734. this.onFinish(this.tasks);
  44735. }
  44736. this._scene.getEngine().hideLoadingUI();
  44737. }
  44738. };
  44739. AssetsManager.prototype._runTask = function (task) {
  44740. var _this = this;
  44741. task.run(this._scene, function () {
  44742. if (_this.onTaskSuccess) {
  44743. _this.onTaskSuccess(task);
  44744. }
  44745. _this._decreaseWaitingTasksCount();
  44746. }, function () {
  44747. if (_this.onTaskError) {
  44748. _this.onTaskError(task);
  44749. }
  44750. _this._decreaseWaitingTasksCount();
  44751. });
  44752. };
  44753. AssetsManager.prototype.reset = function () {
  44754. this.tasks = new Array();
  44755. return this;
  44756. };
  44757. AssetsManager.prototype.load = function () {
  44758. this.waitingTasksCount = this.tasks.length;
  44759. if (this.waitingTasksCount === 0) {
  44760. if (this.onFinish) {
  44761. this.onFinish(this.tasks);
  44762. }
  44763. return this;
  44764. }
  44765. if (this.useDefaultLoadingScreen) {
  44766. this._scene.getEngine().displayLoadingUI();
  44767. }
  44768. for (var index = 0; index < this.tasks.length; index++) {
  44769. var task = this.tasks[index];
  44770. this._runTask(task);
  44771. }
  44772. return this;
  44773. };
  44774. return AssetsManager;
  44775. }());
  44776. BABYLON.AssetsManager = AssetsManager;
  44777. })(BABYLON || (BABYLON = {}));
  44778. //# sourceMappingURL=babylon.assetsManager.js.map
  44779. var BABYLON;
  44780. (function (BABYLON) {
  44781. var VRCameraMetrics = (function () {
  44782. function VRCameraMetrics() {
  44783. this.compensateDistortion = true;
  44784. }
  44785. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44786. get: function () {
  44787. return this.hResolution / (2 * this.vResolution);
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44793. get: function () {
  44794. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44795. },
  44796. enumerable: true,
  44797. configurable: true
  44798. });
  44799. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44800. get: function () {
  44801. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44802. var h = (4 * meters) / this.hScreenSize;
  44803. return BABYLON.Matrix.Translation(h, 0, 0);
  44804. },
  44805. enumerable: true,
  44806. configurable: true
  44807. });
  44808. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44809. get: function () {
  44810. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44811. var h = (4 * meters) / this.hScreenSize;
  44812. return BABYLON.Matrix.Translation(-h, 0, 0);
  44813. },
  44814. enumerable: true,
  44815. configurable: true
  44816. });
  44817. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44818. get: function () {
  44819. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44820. },
  44821. enumerable: true,
  44822. configurable: true
  44823. });
  44824. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44825. get: function () {
  44826. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44827. },
  44828. enumerable: true,
  44829. configurable: true
  44830. });
  44831. VRCameraMetrics.GetDefault = function () {
  44832. var result = new VRCameraMetrics();
  44833. result.hResolution = 1280;
  44834. result.vResolution = 800;
  44835. result.hScreenSize = 0.149759993;
  44836. result.vScreenSize = 0.0935999975;
  44837. result.vScreenCenter = 0.0467999987,
  44838. result.eyeToScreenDistance = 0.0410000011;
  44839. result.lensSeparationDistance = 0.0635000020;
  44840. result.interpupillaryDistance = 0.0640000030;
  44841. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44842. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44843. result.postProcessScaleFactor = 1.714605507808412;
  44844. result.lensCenterOffset = 0.151976421;
  44845. return result;
  44846. };
  44847. return VRCameraMetrics;
  44848. }());
  44849. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44850. })(BABYLON || (BABYLON = {}));
  44851. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44852. var BABYLON;
  44853. (function (BABYLON) {
  44854. var WebVRFreeCamera = (function (_super) {
  44855. __extends(WebVRFreeCamera, _super);
  44856. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44857. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44858. if (webVROptions === void 0) { webVROptions = {}; }
  44859. var _this = _super.call(this, name, position, scene) || this;
  44860. _this.webVROptions = webVROptions;
  44861. _this._vrDevice = null;
  44862. _this._cacheState = null;
  44863. _this._vrEnabled = false;
  44864. _this._attached = false;
  44865. //using the position provided as the current position offset
  44866. _this._positionOffset = position;
  44867. //enable VR
  44868. _this.getEngine().initWebVR();
  44869. if (!_this.getEngine().vrDisplaysPromise) {
  44870. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44871. }
  44872. else {
  44873. //TODO get the metrics updated using the device's eye parameters!
  44874. //TODO also check that the device has the right capabilities!
  44875. _this._frameData = new VRFrameData();
  44876. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  44877. if (devices.length > 0) {
  44878. _this._vrEnabled = true;
  44879. if (_this.webVROptions.displayName) {
  44880. var found = devices.some(function (device) {
  44881. if (device.displayName === _this.webVROptions.displayName) {
  44882. _this._vrDevice = device;
  44883. return true;
  44884. }
  44885. else {
  44886. return false;
  44887. }
  44888. });
  44889. if (!found) {
  44890. _this._vrDevice = devices[0];
  44891. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44892. }
  44893. }
  44894. else {
  44895. //choose the first one
  44896. _this._vrDevice = devices[0];
  44897. }
  44898. //reset the rig parameters.
  44899. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44900. if (_this._attached) {
  44901. _this.getEngine().enableVR(_this._vrDevice);
  44902. }
  44903. }
  44904. else {
  44905. BABYLON.Tools.Error("No WebVR devices found!");
  44906. }
  44907. });
  44908. }
  44909. _this.rotationQuaternion = new BABYLON.Quaternion();
  44910. _this._quaternionCache = new BABYLON.Quaternion();
  44911. return _this;
  44912. }
  44913. WebVRFreeCamera.prototype._checkInputs = function () {
  44914. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44915. var currentPost = this._frameData.pose;
  44916. //make sure we have data
  44917. if (currentPost && currentPost.orientation) {
  44918. this._cacheState = currentPost;
  44919. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44920. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44921. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44922. //scale the position accordingly
  44923. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44924. //add the position offset
  44925. this.position.addInPlace(this._positionOffset);
  44926. }
  44927. }
  44928. }
  44929. _super.prototype._checkInputs.call(this);
  44930. };
  44931. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44932. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44933. this._attached = true;
  44934. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44935. if (this._vrEnabled) {
  44936. this.getEngine().enableVR(this._vrDevice);
  44937. }
  44938. };
  44939. WebVRFreeCamera.prototype.detachControl = function (element) {
  44940. _super.prototype.detachControl.call(this, element);
  44941. this._vrEnabled = false;
  44942. this._attached = false;
  44943. this.getEngine().disableVR();
  44944. };
  44945. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44946. //Backwards comp.
  44947. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44948. //this.getEngine().switchFullscreen(requestPointerlock);
  44949. };
  44950. WebVRFreeCamera.prototype.getClassName = function () {
  44951. return "WebVRFreeCamera";
  44952. };
  44953. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44954. //uses the vrDisplay's "resetPose()".
  44955. //pitch and roll won't be affected.
  44956. this._vrDevice.resetPose();
  44957. };
  44958. /**
  44959. *
  44960. * Set the position offset of the VR camera
  44961. * The offset will be added to the WebVR pose, after scaling it (if set).
  44962. *
  44963. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44964. *
  44965. * @memberOf WebVRFreeCamera
  44966. */
  44967. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44968. if (newPosition) {
  44969. this._positionOffset = newPosition;
  44970. }
  44971. else {
  44972. this._positionOffset.copyFrom(this.position);
  44973. }
  44974. };
  44975. return WebVRFreeCamera;
  44976. }(BABYLON.FreeCamera));
  44977. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44978. })(BABYLON || (BABYLON = {}));
  44979. //# sourceMappingURL=babylon.webVRCamera.js.map
  44980. var BABYLON;
  44981. (function (BABYLON) {
  44982. // Standard optimizations
  44983. var SceneOptimization = (function () {
  44984. function SceneOptimization(priority) {
  44985. if (priority === void 0) { priority = 0; }
  44986. this.priority = priority;
  44987. this.apply = function (scene) {
  44988. return true; // Return true if everything that can be done was applied
  44989. };
  44990. }
  44991. return SceneOptimization;
  44992. }());
  44993. BABYLON.SceneOptimization = SceneOptimization;
  44994. var TextureOptimization = (function (_super) {
  44995. __extends(TextureOptimization, _super);
  44996. function TextureOptimization(priority, maximumSize) {
  44997. if (priority === void 0) { priority = 0; }
  44998. if (maximumSize === void 0) { maximumSize = 1024; }
  44999. var _this = _super.call(this, priority) || this;
  45000. _this.priority = priority;
  45001. _this.maximumSize = maximumSize;
  45002. _this.apply = function (scene) {
  45003. var allDone = true;
  45004. for (var index = 0; index < scene.textures.length; index++) {
  45005. var texture = scene.textures[index];
  45006. if (!texture.canRescale) {
  45007. continue;
  45008. }
  45009. var currentSize = texture.getSize();
  45010. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45011. if (maxDimension > _this.maximumSize) {
  45012. texture.scale(0.5);
  45013. allDone = false;
  45014. }
  45015. }
  45016. return allDone;
  45017. };
  45018. return _this;
  45019. }
  45020. return TextureOptimization;
  45021. }(SceneOptimization));
  45022. BABYLON.TextureOptimization = TextureOptimization;
  45023. var HardwareScalingOptimization = (function (_super) {
  45024. __extends(HardwareScalingOptimization, _super);
  45025. function HardwareScalingOptimization(priority, maximumScale) {
  45026. if (priority === void 0) { priority = 0; }
  45027. if (maximumScale === void 0) { maximumScale = 2; }
  45028. var _this = _super.call(this, priority) || this;
  45029. _this.priority = priority;
  45030. _this.maximumScale = maximumScale;
  45031. _this._currentScale = 1;
  45032. _this.apply = function (scene) {
  45033. _this._currentScale++;
  45034. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45035. return _this._currentScale >= _this.maximumScale;
  45036. };
  45037. return _this;
  45038. }
  45039. return HardwareScalingOptimization;
  45040. }(SceneOptimization));
  45041. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45042. var ShadowsOptimization = (function (_super) {
  45043. __extends(ShadowsOptimization, _super);
  45044. function ShadowsOptimization() {
  45045. var _this = _super.apply(this, arguments) || this;
  45046. _this.apply = function (scene) {
  45047. scene.shadowsEnabled = false;
  45048. return true;
  45049. };
  45050. return _this;
  45051. }
  45052. return ShadowsOptimization;
  45053. }(SceneOptimization));
  45054. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45055. var PostProcessesOptimization = (function (_super) {
  45056. __extends(PostProcessesOptimization, _super);
  45057. function PostProcessesOptimization() {
  45058. var _this = _super.apply(this, arguments) || this;
  45059. _this.apply = function (scene) {
  45060. scene.postProcessesEnabled = false;
  45061. return true;
  45062. };
  45063. return _this;
  45064. }
  45065. return PostProcessesOptimization;
  45066. }(SceneOptimization));
  45067. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45068. var LensFlaresOptimization = (function (_super) {
  45069. __extends(LensFlaresOptimization, _super);
  45070. function LensFlaresOptimization() {
  45071. var _this = _super.apply(this, arguments) || this;
  45072. _this.apply = function (scene) {
  45073. scene.lensFlaresEnabled = false;
  45074. return true;
  45075. };
  45076. return _this;
  45077. }
  45078. return LensFlaresOptimization;
  45079. }(SceneOptimization));
  45080. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45081. var ParticlesOptimization = (function (_super) {
  45082. __extends(ParticlesOptimization, _super);
  45083. function ParticlesOptimization() {
  45084. var _this = _super.apply(this, arguments) || this;
  45085. _this.apply = function (scene) {
  45086. scene.particlesEnabled = false;
  45087. return true;
  45088. };
  45089. return _this;
  45090. }
  45091. return ParticlesOptimization;
  45092. }(SceneOptimization));
  45093. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45094. var RenderTargetsOptimization = (function (_super) {
  45095. __extends(RenderTargetsOptimization, _super);
  45096. function RenderTargetsOptimization() {
  45097. var _this = _super.apply(this, arguments) || this;
  45098. _this.apply = function (scene) {
  45099. scene.renderTargetsEnabled = false;
  45100. return true;
  45101. };
  45102. return _this;
  45103. }
  45104. return RenderTargetsOptimization;
  45105. }(SceneOptimization));
  45106. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45107. var MergeMeshesOptimization = (function (_super) {
  45108. __extends(MergeMeshesOptimization, _super);
  45109. function MergeMeshesOptimization() {
  45110. var _this = _super.apply(this, arguments) || this;
  45111. _this._canBeMerged = function (abstractMesh) {
  45112. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45113. return false;
  45114. }
  45115. var mesh = abstractMesh;
  45116. if (!mesh.isVisible || !mesh.isEnabled()) {
  45117. return false;
  45118. }
  45119. if (mesh.instances.length > 0) {
  45120. return false;
  45121. }
  45122. if (mesh.skeleton || mesh.hasLODLevels) {
  45123. return false;
  45124. }
  45125. if (mesh.parent) {
  45126. return false;
  45127. }
  45128. return true;
  45129. };
  45130. _this.apply = function (scene, updateSelectionTree) {
  45131. var globalPool = scene.meshes.slice(0);
  45132. var globalLength = globalPool.length;
  45133. for (var index = 0; index < globalLength; index++) {
  45134. var currentPool = new Array();
  45135. var current = globalPool[index];
  45136. // Checks
  45137. if (!_this._canBeMerged(current)) {
  45138. continue;
  45139. }
  45140. currentPool.push(current);
  45141. // Find compatible meshes
  45142. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45143. var otherMesh = globalPool[subIndex];
  45144. if (!_this._canBeMerged(otherMesh)) {
  45145. continue;
  45146. }
  45147. if (otherMesh.material !== current.material) {
  45148. continue;
  45149. }
  45150. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45151. continue;
  45152. }
  45153. currentPool.push(otherMesh);
  45154. globalLength--;
  45155. globalPool.splice(subIndex, 1);
  45156. subIndex--;
  45157. }
  45158. if (currentPool.length < 2) {
  45159. continue;
  45160. }
  45161. // Merge meshes
  45162. BABYLON.Mesh.MergeMeshes(currentPool);
  45163. }
  45164. if (updateSelectionTree != undefined) {
  45165. if (updateSelectionTree) {
  45166. scene.createOrUpdateSelectionOctree();
  45167. }
  45168. }
  45169. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45170. scene.createOrUpdateSelectionOctree();
  45171. }
  45172. return true;
  45173. };
  45174. return _this;
  45175. }
  45176. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45177. get: function () {
  45178. return MergeMeshesOptimization._UpdateSelectionTree;
  45179. },
  45180. set: function (value) {
  45181. MergeMeshesOptimization._UpdateSelectionTree = value;
  45182. },
  45183. enumerable: true,
  45184. configurable: true
  45185. });
  45186. return MergeMeshesOptimization;
  45187. }(SceneOptimization));
  45188. MergeMeshesOptimization._UpdateSelectionTree = false;
  45189. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45190. // Options
  45191. var SceneOptimizerOptions = (function () {
  45192. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45193. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45194. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45195. this.targetFrameRate = targetFrameRate;
  45196. this.trackerDuration = trackerDuration;
  45197. this.optimizations = new Array();
  45198. }
  45199. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45200. var result = new SceneOptimizerOptions(targetFrameRate);
  45201. var priority = 0;
  45202. result.optimizations.push(new MergeMeshesOptimization(priority));
  45203. result.optimizations.push(new ShadowsOptimization(priority));
  45204. result.optimizations.push(new LensFlaresOptimization(priority));
  45205. // Next priority
  45206. priority++;
  45207. result.optimizations.push(new PostProcessesOptimization(priority));
  45208. result.optimizations.push(new ParticlesOptimization(priority));
  45209. // Next priority
  45210. priority++;
  45211. result.optimizations.push(new TextureOptimization(priority, 1024));
  45212. return result;
  45213. };
  45214. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45215. var result = new SceneOptimizerOptions(targetFrameRate);
  45216. var priority = 0;
  45217. result.optimizations.push(new MergeMeshesOptimization(priority));
  45218. result.optimizations.push(new ShadowsOptimization(priority));
  45219. result.optimizations.push(new LensFlaresOptimization(priority));
  45220. // Next priority
  45221. priority++;
  45222. result.optimizations.push(new PostProcessesOptimization(priority));
  45223. result.optimizations.push(new ParticlesOptimization(priority));
  45224. // Next priority
  45225. priority++;
  45226. result.optimizations.push(new TextureOptimization(priority, 512));
  45227. // Next priority
  45228. priority++;
  45229. result.optimizations.push(new RenderTargetsOptimization(priority));
  45230. // Next priority
  45231. priority++;
  45232. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45233. return result;
  45234. };
  45235. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45236. var result = new SceneOptimizerOptions(targetFrameRate);
  45237. var priority = 0;
  45238. result.optimizations.push(new MergeMeshesOptimization(priority));
  45239. result.optimizations.push(new ShadowsOptimization(priority));
  45240. result.optimizations.push(new LensFlaresOptimization(priority));
  45241. // Next priority
  45242. priority++;
  45243. result.optimizations.push(new PostProcessesOptimization(priority));
  45244. result.optimizations.push(new ParticlesOptimization(priority));
  45245. // Next priority
  45246. priority++;
  45247. result.optimizations.push(new TextureOptimization(priority, 256));
  45248. // Next priority
  45249. priority++;
  45250. result.optimizations.push(new RenderTargetsOptimization(priority));
  45251. // Next priority
  45252. priority++;
  45253. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45254. return result;
  45255. };
  45256. return SceneOptimizerOptions;
  45257. }());
  45258. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45259. // Scene optimizer tool
  45260. var SceneOptimizer = (function () {
  45261. function SceneOptimizer() {
  45262. }
  45263. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45264. // TODO: add an epsilon
  45265. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45266. if (onSuccess) {
  45267. onSuccess();
  45268. }
  45269. return;
  45270. }
  45271. // Apply current level of optimizations
  45272. var allDone = true;
  45273. var noOptimizationApplied = true;
  45274. for (var index = 0; index < options.optimizations.length; index++) {
  45275. var optimization = options.optimizations[index];
  45276. if (optimization.priority === currentPriorityLevel) {
  45277. noOptimizationApplied = false;
  45278. allDone = allDone && optimization.apply(scene);
  45279. }
  45280. }
  45281. // If no optimization was applied, this is a failure :(
  45282. if (noOptimizationApplied) {
  45283. if (onFailure) {
  45284. onFailure();
  45285. }
  45286. return;
  45287. }
  45288. // If all optimizations were done, move to next level
  45289. if (allDone) {
  45290. currentPriorityLevel++;
  45291. }
  45292. // Let's the system running for a specific amount of time before checking FPS
  45293. scene.executeWhenReady(function () {
  45294. setTimeout(function () {
  45295. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45296. }, options.trackerDuration);
  45297. });
  45298. };
  45299. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45300. if (!options) {
  45301. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45302. }
  45303. // Let's the system running for a specific amount of time before checking FPS
  45304. scene.executeWhenReady(function () {
  45305. setTimeout(function () {
  45306. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45307. }, options.trackerDuration);
  45308. });
  45309. };
  45310. return SceneOptimizer;
  45311. }());
  45312. BABYLON.SceneOptimizer = SceneOptimizer;
  45313. })(BABYLON || (BABYLON = {}));
  45314. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45315. var BABYLON;
  45316. (function (BABYLON) {
  45317. var Internals;
  45318. (function (Internals) {
  45319. var MeshLODLevel = (function () {
  45320. function MeshLODLevel(distance, mesh) {
  45321. this.distance = distance;
  45322. this.mesh = mesh;
  45323. }
  45324. return MeshLODLevel;
  45325. }());
  45326. Internals.MeshLODLevel = MeshLODLevel;
  45327. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45328. })(BABYLON || (BABYLON = {}));
  45329. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45330. var BABYLON;
  45331. (function (BABYLON) {
  45332. var RawTexture = (function (_super) {
  45333. __extends(RawTexture, _super);
  45334. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45335. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45336. if (invertY === void 0) { invertY = false; }
  45337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45338. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45339. _this.format = format;
  45340. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45341. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45342. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45343. return _this;
  45344. }
  45345. RawTexture.prototype.update = function (data) {
  45346. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45347. };
  45348. // Statics
  45349. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45350. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45351. if (invertY === void 0) { invertY = false; }
  45352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45353. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45354. };
  45355. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45356. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45357. if (invertY === void 0) { invertY = false; }
  45358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45359. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45360. };
  45361. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45362. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45363. if (invertY === void 0) { invertY = false; }
  45364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45365. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45366. };
  45367. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45368. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45369. if (invertY === void 0) { invertY = false; }
  45370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45371. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45372. };
  45373. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45374. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45375. if (invertY === void 0) { invertY = false; }
  45376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45377. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45378. };
  45379. return RawTexture;
  45380. }(BABYLON.Texture));
  45381. BABYLON.RawTexture = RawTexture;
  45382. })(BABYLON || (BABYLON = {}));
  45383. //# sourceMappingURL=babylon.rawTexture.js.map
  45384. var BABYLON;
  45385. (function (BABYLON) {
  45386. var IndexedVector2 = (function (_super) {
  45387. __extends(IndexedVector2, _super);
  45388. function IndexedVector2(original, index) {
  45389. var _this = _super.call(this, original.x, original.y) || this;
  45390. _this.index = index;
  45391. return _this;
  45392. }
  45393. return IndexedVector2;
  45394. }(BABYLON.Vector2));
  45395. var PolygonPoints = (function () {
  45396. function PolygonPoints() {
  45397. this.elements = new Array();
  45398. }
  45399. PolygonPoints.prototype.add = function (originalPoints) {
  45400. var _this = this;
  45401. var result = new Array();
  45402. originalPoints.forEach(function (point) {
  45403. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45404. var newPoint = new IndexedVector2(point, _this.elements.length);
  45405. result.push(newPoint);
  45406. _this.elements.push(newPoint);
  45407. }
  45408. });
  45409. return result;
  45410. };
  45411. PolygonPoints.prototype.computeBounds = function () {
  45412. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45413. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45414. this.elements.forEach(function (point) {
  45415. // x
  45416. if (point.x < lmin.x) {
  45417. lmin.x = point.x;
  45418. }
  45419. else if (point.x > lmax.x) {
  45420. lmax.x = point.x;
  45421. }
  45422. // y
  45423. if (point.y < lmin.y) {
  45424. lmin.y = point.y;
  45425. }
  45426. else if (point.y > lmax.y) {
  45427. lmax.y = point.y;
  45428. }
  45429. });
  45430. return {
  45431. min: lmin,
  45432. max: lmax,
  45433. width: lmax.x - lmin.x,
  45434. height: lmax.y - lmin.y
  45435. };
  45436. };
  45437. return PolygonPoints;
  45438. }());
  45439. var Polygon = (function () {
  45440. function Polygon() {
  45441. }
  45442. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45443. return [
  45444. new BABYLON.Vector2(xmin, ymin),
  45445. new BABYLON.Vector2(xmax, ymin),
  45446. new BABYLON.Vector2(xmax, ymax),
  45447. new BABYLON.Vector2(xmin, ymax)
  45448. ];
  45449. };
  45450. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45451. if (cx === void 0) { cx = 0; }
  45452. if (cy === void 0) { cy = 0; }
  45453. if (numberOfSides === void 0) { numberOfSides = 32; }
  45454. var result = new Array();
  45455. var angle = 0;
  45456. var increment = (Math.PI * 2) / numberOfSides;
  45457. for (var i = 0; i < numberOfSides; i++) {
  45458. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45459. angle -= increment;
  45460. }
  45461. return result;
  45462. };
  45463. Polygon.Parse = function (input) {
  45464. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45465. var i, result = [];
  45466. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45467. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45468. }
  45469. return result;
  45470. };
  45471. Polygon.StartingAt = function (x, y) {
  45472. return BABYLON.Path2.StartingAt(x, y);
  45473. };
  45474. return Polygon;
  45475. }());
  45476. BABYLON.Polygon = Polygon;
  45477. var PolygonMeshBuilder = (function () {
  45478. function PolygonMeshBuilder(name, contours, scene) {
  45479. this._points = new PolygonPoints();
  45480. this._outlinepoints = new PolygonPoints();
  45481. this._holes = [];
  45482. this._epoints = new Array();
  45483. this._eholes = new Array();
  45484. this._name = name;
  45485. this._scene = scene;
  45486. var points;
  45487. if (contours instanceof BABYLON.Path2) {
  45488. points = contours.getPoints();
  45489. }
  45490. else {
  45491. points = contours;
  45492. }
  45493. this._addToepoint(points);
  45494. this._points.add(points);
  45495. this._outlinepoints.add(points);
  45496. }
  45497. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45498. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45499. var p = points_1[_i];
  45500. this._epoints.push(p.x, p.y);
  45501. }
  45502. };
  45503. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45504. this._points.add(hole);
  45505. var holepoints = new PolygonPoints();
  45506. holepoints.add(hole);
  45507. this._holes.push(holepoints);
  45508. this._eholes.push(this._epoints.length / 2);
  45509. this._addToepoint(hole);
  45510. return this;
  45511. };
  45512. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45513. var _this = this;
  45514. if (updatable === void 0) { updatable = false; }
  45515. var result = new BABYLON.Mesh(this._name, this._scene);
  45516. var normals = [];
  45517. var positions = [];
  45518. var uvs = [];
  45519. var bounds = this._points.computeBounds();
  45520. this._points.elements.forEach(function (p) {
  45521. normals.push(0, 1.0, 0);
  45522. positions.push(p.x, 0, p.y);
  45523. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45524. });
  45525. var indices = [];
  45526. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45527. for (var i = 0; i < res.length; i++) {
  45528. indices.push(res[i]);
  45529. }
  45530. if (depth > 0) {
  45531. var positionscount = (positions.length / 3); //get the current pointcount
  45532. this._points.elements.forEach(function (p) {
  45533. normals.push(0, -1.0, 0);
  45534. positions.push(p.x, -depth, p.y);
  45535. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45536. });
  45537. var totalCount = indices.length;
  45538. for (var i = 0; i < totalCount; i += 3) {
  45539. var i0 = indices[i + 0];
  45540. var i1 = indices[i + 1];
  45541. var i2 = indices[i + 2];
  45542. indices.push(i2 + positionscount);
  45543. indices.push(i1 + positionscount);
  45544. indices.push(i0 + positionscount);
  45545. }
  45546. //Add the sides
  45547. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45548. this._holes.forEach(function (hole) {
  45549. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45550. });
  45551. }
  45552. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45553. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45554. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45555. result.setIndices(indices);
  45556. return result;
  45557. };
  45558. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45559. var StartIndex = positions.length / 3;
  45560. var ulength = 0;
  45561. for (var i = 0; i < points.elements.length; i++) {
  45562. var p = points.elements[i];
  45563. var p1;
  45564. if ((i + 1) > points.elements.length - 1) {
  45565. p1 = points.elements[0];
  45566. }
  45567. else {
  45568. p1 = points.elements[i + 1];
  45569. }
  45570. positions.push(p.x, 0, p.y);
  45571. positions.push(p.x, -depth, p.y);
  45572. positions.push(p1.x, 0, p1.y);
  45573. positions.push(p1.x, -depth, p1.y);
  45574. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45575. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45576. var v3 = v2.subtract(v1);
  45577. var v4 = new BABYLON.Vector3(0, 1, 0);
  45578. var vn = BABYLON.Vector3.Cross(v3, v4);
  45579. vn = vn.normalize();
  45580. uvs.push(ulength / bounds.width, 0);
  45581. uvs.push(ulength / bounds.width, 1);
  45582. ulength += v3.length();
  45583. uvs.push((ulength / bounds.width), 0);
  45584. uvs.push((ulength / bounds.width), 1);
  45585. if (!flip) {
  45586. normals.push(-vn.x, -vn.y, -vn.z);
  45587. normals.push(-vn.x, -vn.y, -vn.z);
  45588. normals.push(-vn.x, -vn.y, -vn.z);
  45589. normals.push(-vn.x, -vn.y, -vn.z);
  45590. indices.push(StartIndex);
  45591. indices.push(StartIndex + 1);
  45592. indices.push(StartIndex + 2);
  45593. indices.push(StartIndex + 1);
  45594. indices.push(StartIndex + 3);
  45595. indices.push(StartIndex + 2);
  45596. }
  45597. else {
  45598. normals.push(vn.x, vn.y, vn.z);
  45599. normals.push(vn.x, vn.y, vn.z);
  45600. normals.push(vn.x, vn.y, vn.z);
  45601. normals.push(vn.x, vn.y, vn.z);
  45602. indices.push(StartIndex);
  45603. indices.push(StartIndex + 2);
  45604. indices.push(StartIndex + 1);
  45605. indices.push(StartIndex + 1);
  45606. indices.push(StartIndex + 2);
  45607. indices.push(StartIndex + 3);
  45608. }
  45609. StartIndex += 4;
  45610. }
  45611. ;
  45612. };
  45613. return PolygonMeshBuilder;
  45614. }());
  45615. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45616. })(BABYLON || (BABYLON = {}));
  45617. //# sourceMappingURL=babylon.polygonMesh.js.map
  45618. var BABYLON;
  45619. (function (BABYLON) {
  45620. var Octree = (function () {
  45621. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45622. if (maxDepth === void 0) { maxDepth = 2; }
  45623. this.maxDepth = maxDepth;
  45624. this.dynamicContent = new Array();
  45625. this._maxBlockCapacity = maxBlockCapacity || 64;
  45626. this._selectionContent = new BABYLON.SmartArray(1024);
  45627. this._creationFunc = creationFunc;
  45628. }
  45629. // Methods
  45630. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45631. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45632. };
  45633. Octree.prototype.addMesh = function (entry) {
  45634. for (var index = 0; index < this.blocks.length; index++) {
  45635. var block = this.blocks[index];
  45636. block.addEntry(entry);
  45637. }
  45638. };
  45639. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45640. this._selectionContent.reset();
  45641. for (var index = 0; index < this.blocks.length; index++) {
  45642. var block = this.blocks[index];
  45643. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45644. }
  45645. if (allowDuplicate) {
  45646. this._selectionContent.concat(this.dynamicContent);
  45647. }
  45648. else {
  45649. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45650. }
  45651. return this._selectionContent;
  45652. };
  45653. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45654. this._selectionContent.reset();
  45655. for (var index = 0; index < this.blocks.length; index++) {
  45656. var block = this.blocks[index];
  45657. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45658. }
  45659. if (allowDuplicate) {
  45660. this._selectionContent.concat(this.dynamicContent);
  45661. }
  45662. else {
  45663. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45664. }
  45665. return this._selectionContent;
  45666. };
  45667. Octree.prototype.intersectsRay = function (ray) {
  45668. this._selectionContent.reset();
  45669. for (var index = 0; index < this.blocks.length; index++) {
  45670. var block = this.blocks[index];
  45671. block.intersectsRay(ray, this._selectionContent);
  45672. }
  45673. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45674. return this._selectionContent;
  45675. };
  45676. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45677. target.blocks = new Array();
  45678. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45679. // Segmenting space
  45680. for (var x = 0; x < 2; x++) {
  45681. for (var y = 0; y < 2; y++) {
  45682. for (var z = 0; z < 2; z++) {
  45683. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45684. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45685. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45686. block.addEntries(entries);
  45687. target.blocks.push(block);
  45688. }
  45689. }
  45690. }
  45691. };
  45692. return Octree;
  45693. }());
  45694. Octree.CreationFuncForMeshes = function (entry, block) {
  45695. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45696. block.entries.push(entry);
  45697. }
  45698. };
  45699. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45700. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45701. block.entries.push(entry);
  45702. }
  45703. };
  45704. BABYLON.Octree = Octree;
  45705. })(BABYLON || (BABYLON = {}));
  45706. //# sourceMappingURL=babylon.octree.js.map
  45707. var BABYLON;
  45708. (function (BABYLON) {
  45709. var OctreeBlock = (function () {
  45710. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45711. this.entries = new Array();
  45712. this._boundingVectors = new Array();
  45713. this._capacity = capacity;
  45714. this._depth = depth;
  45715. this._maxDepth = maxDepth;
  45716. this._creationFunc = creationFunc;
  45717. this._minPoint = minPoint;
  45718. this._maxPoint = maxPoint;
  45719. this._boundingVectors.push(minPoint.clone());
  45720. this._boundingVectors.push(maxPoint.clone());
  45721. this._boundingVectors.push(minPoint.clone());
  45722. this._boundingVectors[2].x = maxPoint.x;
  45723. this._boundingVectors.push(minPoint.clone());
  45724. this._boundingVectors[3].y = maxPoint.y;
  45725. this._boundingVectors.push(minPoint.clone());
  45726. this._boundingVectors[4].z = maxPoint.z;
  45727. this._boundingVectors.push(maxPoint.clone());
  45728. this._boundingVectors[5].z = minPoint.z;
  45729. this._boundingVectors.push(maxPoint.clone());
  45730. this._boundingVectors[6].x = minPoint.x;
  45731. this._boundingVectors.push(maxPoint.clone());
  45732. this._boundingVectors[7].y = minPoint.y;
  45733. }
  45734. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45735. // Property
  45736. get: function () {
  45737. return this._capacity;
  45738. },
  45739. enumerable: true,
  45740. configurable: true
  45741. });
  45742. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45743. get: function () {
  45744. return this._minPoint;
  45745. },
  45746. enumerable: true,
  45747. configurable: true
  45748. });
  45749. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45750. get: function () {
  45751. return this._maxPoint;
  45752. },
  45753. enumerable: true,
  45754. configurable: true
  45755. });
  45756. // Methods
  45757. OctreeBlock.prototype.addEntry = function (entry) {
  45758. if (this.blocks) {
  45759. for (var index = 0; index < this.blocks.length; index++) {
  45760. var block = this.blocks[index];
  45761. block.addEntry(entry);
  45762. }
  45763. return;
  45764. }
  45765. this._creationFunc(entry, this);
  45766. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45767. this.createInnerBlocks();
  45768. }
  45769. };
  45770. OctreeBlock.prototype.addEntries = function (entries) {
  45771. for (var index = 0; index < entries.length; index++) {
  45772. var mesh = entries[index];
  45773. this.addEntry(mesh);
  45774. }
  45775. };
  45776. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45777. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45778. if (this.blocks) {
  45779. for (var index = 0; index < this.blocks.length; index++) {
  45780. var block = this.blocks[index];
  45781. block.select(frustumPlanes, selection, allowDuplicate);
  45782. }
  45783. return;
  45784. }
  45785. if (allowDuplicate) {
  45786. selection.concat(this.entries);
  45787. }
  45788. else {
  45789. selection.concatWithNoDuplicate(this.entries);
  45790. }
  45791. }
  45792. };
  45793. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45794. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45795. if (this.blocks) {
  45796. for (var index = 0; index < this.blocks.length; index++) {
  45797. var block = this.blocks[index];
  45798. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45799. }
  45800. return;
  45801. }
  45802. if (allowDuplicate) {
  45803. selection.concat(this.entries);
  45804. }
  45805. else {
  45806. selection.concatWithNoDuplicate(this.entries);
  45807. }
  45808. }
  45809. };
  45810. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45811. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45812. if (this.blocks) {
  45813. for (var index = 0; index < this.blocks.length; index++) {
  45814. var block = this.blocks[index];
  45815. block.intersectsRay(ray, selection);
  45816. }
  45817. return;
  45818. }
  45819. selection.concatWithNoDuplicate(this.entries);
  45820. }
  45821. };
  45822. OctreeBlock.prototype.createInnerBlocks = function () {
  45823. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45824. };
  45825. return OctreeBlock;
  45826. }());
  45827. BABYLON.OctreeBlock = OctreeBlock;
  45828. })(BABYLON || (BABYLON = {}));
  45829. //# sourceMappingURL=babylon.octreeBlock.js.map
  45830. var BABYLON;
  45831. (function (BABYLON) {
  45832. var BlurPostProcess = (function (_super) {
  45833. __extends(BlurPostProcess, _super);
  45834. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45836. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  45837. _this.direction = direction;
  45838. _this.blurWidth = blurWidth;
  45839. _this.onApplyObservable.add(function (effect) {
  45840. effect.setFloat2("screenSize", _this.width, _this.height);
  45841. effect.setVector2("direction", _this.direction);
  45842. effect.setFloat("blurWidth", _this.blurWidth);
  45843. });
  45844. return _this;
  45845. }
  45846. return BlurPostProcess;
  45847. }(BABYLON.PostProcess));
  45848. BABYLON.BlurPostProcess = BlurPostProcess;
  45849. })(BABYLON || (BABYLON = {}));
  45850. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45851. var BABYLON;
  45852. (function (BABYLON) {
  45853. var RefractionPostProcess = (function (_super) {
  45854. __extends(RefractionPostProcess, _super);
  45855. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45856. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  45857. _this.color = color;
  45858. _this.depth = depth;
  45859. _this.colorLevel = colorLevel;
  45860. _this.onActivateObservable.add(function (cam) {
  45861. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45862. });
  45863. _this.onApplyObservable.add(function (effect) {
  45864. effect.setColor3("baseColor", _this.color);
  45865. effect.setFloat("depth", _this.depth);
  45866. effect.setFloat("colorLevel", _this.colorLevel);
  45867. effect.setTexture("refractionSampler", _this._refRexture);
  45868. });
  45869. return _this;
  45870. }
  45871. // Methods
  45872. RefractionPostProcess.prototype.dispose = function (camera) {
  45873. if (this._refRexture) {
  45874. this._refRexture.dispose();
  45875. }
  45876. _super.prototype.dispose.call(this, camera);
  45877. };
  45878. return RefractionPostProcess;
  45879. }(BABYLON.PostProcess));
  45880. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45881. })(BABYLON || (BABYLON = {}));
  45882. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45883. var BABYLON;
  45884. (function (BABYLON) {
  45885. var BlackAndWhitePostProcess = (function (_super) {
  45886. __extends(BlackAndWhitePostProcess, _super);
  45887. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45888. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  45889. }
  45890. return BlackAndWhitePostProcess;
  45891. }(BABYLON.PostProcess));
  45892. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45893. })(BABYLON || (BABYLON = {}));
  45894. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45895. var BABYLON;
  45896. (function (BABYLON) {
  45897. var ConvolutionPostProcess = (function (_super) {
  45898. __extends(ConvolutionPostProcess, _super);
  45899. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45900. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  45901. _this.kernel = kernel;
  45902. _this.onApply = function (effect) {
  45903. effect.setFloat2("screenSize", _this.width, _this.height);
  45904. effect.setArray("kernel", _this.kernel);
  45905. };
  45906. return _this;
  45907. }
  45908. return ConvolutionPostProcess;
  45909. }(BABYLON.PostProcess));
  45910. // Statics
  45911. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45912. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45913. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45914. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45915. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45916. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45917. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45918. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45919. })(BABYLON || (BABYLON = {}));
  45920. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45921. var BABYLON;
  45922. (function (BABYLON) {
  45923. var FilterPostProcess = (function (_super) {
  45924. __extends(FilterPostProcess, _super);
  45925. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45926. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  45927. _this.kernelMatrix = kernelMatrix;
  45928. _this.onApply = function (effect) {
  45929. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45930. };
  45931. return _this;
  45932. }
  45933. return FilterPostProcess;
  45934. }(BABYLON.PostProcess));
  45935. BABYLON.FilterPostProcess = FilterPostProcess;
  45936. })(BABYLON || (BABYLON = {}));
  45937. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45938. var BABYLON;
  45939. (function (BABYLON) {
  45940. var FxaaPostProcess = (function (_super) {
  45941. __extends(FxaaPostProcess, _super);
  45942. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45943. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  45944. _this.onSizeChangedObservable.add(function () {
  45945. _this.texelWidth = 1.0 / _this.width;
  45946. _this.texelHeight = 1.0 / _this.height;
  45947. });
  45948. _this.onApplyObservable.add(function (effect) {
  45949. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45950. });
  45951. return _this;
  45952. }
  45953. return FxaaPostProcess;
  45954. }(BABYLON.PostProcess));
  45955. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45956. })(BABYLON || (BABYLON = {}));
  45957. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45958. var BABYLON;
  45959. (function (BABYLON) {
  45960. var StereoscopicInterlacePostProcess = (function (_super) {
  45961. __extends(StereoscopicInterlacePostProcess, _super);
  45962. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45963. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  45964. _this._passedProcess = rigCameras[0]._rigPostProcess;
  45965. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45966. _this.onSizeChangedObservable.add(function () {
  45967. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45968. });
  45969. _this.onApplyObservable.add(function (effect) {
  45970. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45971. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45972. });
  45973. return _this;
  45974. }
  45975. return StereoscopicInterlacePostProcess;
  45976. }(BABYLON.PostProcess));
  45977. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45978. })(BABYLON || (BABYLON = {}));
  45979. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  45980. var BABYLON;
  45981. (function (BABYLON) {
  45982. var LensFlare = (function () {
  45983. function LensFlare(size, position, color, imgUrl, system) {
  45984. this.size = size;
  45985. this.position = position;
  45986. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45987. this.dispose = function () {
  45988. if (this.texture) {
  45989. this.texture.dispose();
  45990. }
  45991. // Remove from scene
  45992. var index = this._system.lensFlares.indexOf(this);
  45993. this._system.lensFlares.splice(index, 1);
  45994. };
  45995. this.color = color || new BABYLON.Color3(1, 1, 1);
  45996. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  45997. this._system = system;
  45998. system.lensFlares.push(this);
  45999. }
  46000. return LensFlare;
  46001. }());
  46002. BABYLON.LensFlare = LensFlare;
  46003. })(BABYLON || (BABYLON = {}));
  46004. //# sourceMappingURL=babylon.lensFlare.js.map
  46005. var BABYLON;
  46006. (function (BABYLON) {
  46007. var LensFlareSystem = (function () {
  46008. function LensFlareSystem(name, emitter, scene) {
  46009. this.name = name;
  46010. this.lensFlares = new Array();
  46011. this.borderLimit = 300;
  46012. this.viewportBorder = 0;
  46013. this.layerMask = 0x0FFFFFFF;
  46014. this._vertexBuffers = {};
  46015. this._isEnabled = true;
  46016. this._scene = scene;
  46017. this._emitter = emitter;
  46018. this.id = name;
  46019. scene.lensFlareSystems.push(this);
  46020. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46021. var engine = scene.getEngine();
  46022. // VBO
  46023. var vertices = [];
  46024. vertices.push(1, 1);
  46025. vertices.push(-1, 1);
  46026. vertices.push(-1, -1);
  46027. vertices.push(1, -1);
  46028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46029. // Indices
  46030. var indices = [];
  46031. indices.push(0);
  46032. indices.push(1);
  46033. indices.push(2);
  46034. indices.push(0);
  46035. indices.push(2);
  46036. indices.push(3);
  46037. this._indexBuffer = engine.createIndexBuffer(indices);
  46038. // Effects
  46039. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46040. }
  46041. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46042. get: function () {
  46043. return this._isEnabled;
  46044. },
  46045. set: function (value) {
  46046. this._isEnabled = value;
  46047. },
  46048. enumerable: true,
  46049. configurable: true
  46050. });
  46051. LensFlareSystem.prototype.getScene = function () {
  46052. return this._scene;
  46053. };
  46054. LensFlareSystem.prototype.getEmitter = function () {
  46055. return this._emitter;
  46056. };
  46057. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46058. this._emitter = newEmitter;
  46059. };
  46060. LensFlareSystem.prototype.getEmitterPosition = function () {
  46061. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46062. };
  46063. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46064. var position = this.getEmitterPosition();
  46065. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46066. this._positionX = position.x;
  46067. this._positionY = position.y;
  46068. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46069. if (this.viewportBorder > 0) {
  46070. globalViewport.x -= this.viewportBorder;
  46071. globalViewport.y -= this.viewportBorder;
  46072. globalViewport.width += this.viewportBorder * 2;
  46073. globalViewport.height += this.viewportBorder * 2;
  46074. position.x += this.viewportBorder;
  46075. position.y += this.viewportBorder;
  46076. this._positionX += this.viewportBorder;
  46077. this._positionY += this.viewportBorder;
  46078. }
  46079. if (position.z > 0) {
  46080. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46081. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46082. return true;
  46083. }
  46084. return true;
  46085. }
  46086. return false;
  46087. };
  46088. LensFlareSystem.prototype._isVisible = function () {
  46089. if (!this._isEnabled) {
  46090. return false;
  46091. }
  46092. var emitterPosition = this.getEmitterPosition();
  46093. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46094. var distance = direction.length();
  46095. direction.normalize();
  46096. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46097. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46098. return !pickInfo.hit || pickInfo.distance > distance;
  46099. };
  46100. LensFlareSystem.prototype.render = function () {
  46101. if (!this._effect.isReady())
  46102. return false;
  46103. var engine = this._scene.getEngine();
  46104. var viewport = this._scene.activeCamera.viewport;
  46105. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46106. // Position
  46107. if (!this.computeEffectivePosition(globalViewport)) {
  46108. return false;
  46109. }
  46110. // Visibility
  46111. if (!this._isVisible()) {
  46112. return false;
  46113. }
  46114. // Intensity
  46115. var awayX;
  46116. var awayY;
  46117. if (this._positionX < this.borderLimit + globalViewport.x) {
  46118. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46119. }
  46120. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46121. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46122. }
  46123. else {
  46124. awayX = 0;
  46125. }
  46126. if (this._positionY < this.borderLimit + globalViewport.y) {
  46127. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46128. }
  46129. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46130. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46131. }
  46132. else {
  46133. awayY = 0;
  46134. }
  46135. var away = (awayX > awayY) ? awayX : awayY;
  46136. away -= this.viewportBorder;
  46137. if (away > this.borderLimit) {
  46138. away = this.borderLimit;
  46139. }
  46140. var intensity = 1.0 - (away / this.borderLimit);
  46141. if (intensity < 0) {
  46142. return false;
  46143. }
  46144. if (intensity > 1.0) {
  46145. intensity = 1.0;
  46146. }
  46147. if (this.viewportBorder > 0) {
  46148. globalViewport.x += this.viewportBorder;
  46149. globalViewport.y += this.viewportBorder;
  46150. globalViewport.width -= this.viewportBorder * 2;
  46151. globalViewport.height -= this.viewportBorder * 2;
  46152. this._positionX -= this.viewportBorder;
  46153. this._positionY -= this.viewportBorder;
  46154. }
  46155. // Position
  46156. var centerX = globalViewport.x + globalViewport.width / 2;
  46157. var centerY = globalViewport.y + globalViewport.height / 2;
  46158. var distX = centerX - this._positionX;
  46159. var distY = centerY - this._positionY;
  46160. // Effects
  46161. engine.enableEffect(this._effect);
  46162. engine.setState(false);
  46163. engine.setDepthBuffer(false);
  46164. // VBOs
  46165. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46166. // Flares
  46167. for (var index = 0; index < this.lensFlares.length; index++) {
  46168. var flare = this.lensFlares[index];
  46169. engine.setAlphaMode(flare.alphaMode);
  46170. var x = centerX - (distX * flare.position);
  46171. var y = centerY - (distY * flare.position);
  46172. var cw = flare.size;
  46173. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46174. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46175. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46176. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46177. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46178. // Texture
  46179. this._effect.setTexture("textureSampler", flare.texture);
  46180. // Color
  46181. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46182. // Draw order
  46183. engine.draw(true, 0, 6);
  46184. }
  46185. engine.setDepthBuffer(true);
  46186. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46187. return true;
  46188. };
  46189. LensFlareSystem.prototype.dispose = function () {
  46190. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46191. if (vertexBuffer) {
  46192. vertexBuffer.dispose();
  46193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46194. }
  46195. if (this._indexBuffer) {
  46196. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46197. this._indexBuffer = null;
  46198. }
  46199. while (this.lensFlares.length) {
  46200. this.lensFlares[0].dispose();
  46201. }
  46202. // Remove from scene
  46203. var index = this._scene.lensFlareSystems.indexOf(this);
  46204. this._scene.lensFlareSystems.splice(index, 1);
  46205. };
  46206. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46207. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46208. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46209. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46210. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46211. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46212. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46213. var parsedFlare = parsedLensFlareSystem.flares[index];
  46214. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46215. }
  46216. return lensFlareSystem;
  46217. };
  46218. LensFlareSystem.prototype.serialize = function () {
  46219. var serializationObject = {};
  46220. serializationObject.id = this.id;
  46221. serializationObject.name = this.name;
  46222. serializationObject.emitterId = this.getEmitter().id;
  46223. serializationObject.borderLimit = this.borderLimit;
  46224. serializationObject.flares = [];
  46225. for (var index = 0; index < this.lensFlares.length; index++) {
  46226. var flare = this.lensFlares[index];
  46227. serializationObject.flares.push({
  46228. size: flare.size,
  46229. position: flare.position,
  46230. color: flare.color.asArray(),
  46231. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46232. });
  46233. }
  46234. return serializationObject;
  46235. };
  46236. return LensFlareSystem;
  46237. }());
  46238. BABYLON.LensFlareSystem = LensFlareSystem;
  46239. })(BABYLON || (BABYLON = {}));
  46240. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46241. var BABYLON;
  46242. (function (BABYLON) {
  46243. // We're mainly based on the logic defined into the FreeCamera code
  46244. var DeviceOrientationCamera = (function (_super) {
  46245. __extends(DeviceOrientationCamera, _super);
  46246. function DeviceOrientationCamera(name, position, scene) {
  46247. var _this = _super.call(this, name, position, scene) || this;
  46248. _this._quaternionCache = new BABYLON.Quaternion();
  46249. _this.inputs.addDeviceOrientation();
  46250. return _this;
  46251. }
  46252. DeviceOrientationCamera.prototype.getClassName = function () {
  46253. return "DeviceOrientationCamera";
  46254. };
  46255. DeviceOrientationCamera.prototype._checkInputs = function () {
  46256. _super.prototype._checkInputs.call(this);
  46257. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46258. if (this._initialQuaternion) {
  46259. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46260. }
  46261. };
  46262. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46263. var _this = this;
  46264. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46265. //can only work if this camera has a rotation quaternion already.
  46266. if (!this.rotationQuaternion)
  46267. return;
  46268. if (!this._initialQuaternion) {
  46269. this._initialQuaternion = new BABYLON.Quaternion();
  46270. }
  46271. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46272. ['x', 'y', 'z'].forEach(function (axisName) {
  46273. if (!axis[axisName]) {
  46274. _this._initialQuaternion[axisName] = 0;
  46275. }
  46276. else {
  46277. _this._initialQuaternion[axisName] *= -1;
  46278. }
  46279. });
  46280. this._initialQuaternion.normalize();
  46281. //force rotation update
  46282. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46283. };
  46284. return DeviceOrientationCamera;
  46285. }(BABYLON.FreeCamera));
  46286. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46287. })(BABYLON || (BABYLON = {}));
  46288. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46289. var BABYLON;
  46290. (function (BABYLON) {
  46291. var VRDeviceOrientationFreeCamera = (function (_super) {
  46292. __extends(VRDeviceOrientationFreeCamera, _super);
  46293. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46294. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46295. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46296. var _this = _super.call(this, name, position, scene) || this;
  46297. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46298. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46299. return _this;
  46300. }
  46301. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46302. return "VRDeviceOrientationFreeCamera";
  46303. };
  46304. return VRDeviceOrientationFreeCamera;
  46305. }(BABYLON.DeviceOrientationCamera));
  46306. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46307. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46308. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46309. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46310. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46311. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46312. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46313. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46314. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46315. _this.inputs.addVRDeviceOrientation();
  46316. return _this;
  46317. }
  46318. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46319. return "VRDeviceOrientationArcRotateCamera";
  46320. };
  46321. return VRDeviceOrientationArcRotateCamera;
  46322. }(BABYLON.ArcRotateCamera));
  46323. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46324. })(BABYLON || (BABYLON = {}));
  46325. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46326. var BABYLON;
  46327. (function (BABYLON) {
  46328. // We're mainly based on the logic defined into the FreeCamera code
  46329. var UniversalCamera = (function (_super) {
  46330. __extends(UniversalCamera, _super);
  46331. //-- end properties for backward compatibility for inputs
  46332. function UniversalCamera(name, position, scene) {
  46333. var _this = _super.call(this, name, position, scene) || this;
  46334. _this.inputs.addGamepad();
  46335. return _this;
  46336. }
  46337. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46338. //-- Begin properties for backward compatibility for inputs
  46339. get: function () {
  46340. var gamepad = this.inputs.attached["gamepad"];
  46341. if (gamepad)
  46342. return gamepad.gamepadAngularSensibility;
  46343. },
  46344. set: function (value) {
  46345. var gamepad = this.inputs.attached["gamepad"];
  46346. if (gamepad)
  46347. gamepad.gamepadAngularSensibility = value;
  46348. },
  46349. enumerable: true,
  46350. configurable: true
  46351. });
  46352. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46353. get: function () {
  46354. var gamepad = this.inputs.attached["gamepad"];
  46355. if (gamepad)
  46356. return gamepad.gamepadMoveSensibility;
  46357. },
  46358. set: function (value) {
  46359. var gamepad = this.inputs.attached["gamepad"];
  46360. if (gamepad)
  46361. gamepad.gamepadMoveSensibility = value;
  46362. },
  46363. enumerable: true,
  46364. configurable: true
  46365. });
  46366. UniversalCamera.prototype.getClassName = function () {
  46367. return "UniversalCamera";
  46368. };
  46369. return UniversalCamera;
  46370. }(BABYLON.TouchCamera));
  46371. BABYLON.UniversalCamera = UniversalCamera;
  46372. })(BABYLON || (BABYLON = {}));
  46373. //# sourceMappingURL=babylon.universalCamera.js.map
  46374. var BABYLON;
  46375. (function (BABYLON) {
  46376. var Gamepads = (function () {
  46377. function Gamepads(ongamedpadconnected) {
  46378. var _this = this;
  46379. this.babylonGamepads = [];
  46380. this.oneGamepadConnected = false;
  46381. this.isMonitoring = false;
  46382. this.gamepadEventSupported = 'GamepadEvent' in window;
  46383. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46384. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46385. this._callbackGamepadConnected = ongamedpadconnected;
  46386. if (this.gamepadSupportAvailable) {
  46387. // Checking if the gamepad connected event is supported (like in Firefox)
  46388. if (this.gamepadEventSupported) {
  46389. this._onGamepadConnectedEvent = function (evt) {
  46390. _this._onGamepadConnected(evt);
  46391. };
  46392. this._onGamepadDisonnectedEvent = function (evt) {
  46393. _this._onGamepadDisconnected(evt);
  46394. };
  46395. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46396. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46397. }
  46398. else {
  46399. this._startMonitoringGamepads();
  46400. }
  46401. }
  46402. }
  46403. Gamepads.prototype.dispose = function () {
  46404. if (Gamepads.gamepadDOMInfo) {
  46405. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46406. }
  46407. if (this._onGamepadConnectedEvent) {
  46408. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46409. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46410. this._onGamepadConnectedEvent = null;
  46411. this._onGamepadDisonnectedEvent = null;
  46412. }
  46413. };
  46414. Gamepads.prototype._onGamepadConnected = function (evt) {
  46415. var newGamepad = this._addNewGamepad(evt.gamepad);
  46416. if (this._callbackGamepadConnected)
  46417. this._callbackGamepadConnected(newGamepad);
  46418. this._startMonitoringGamepads();
  46419. };
  46420. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46421. if (!this.oneGamepadConnected) {
  46422. this.oneGamepadConnected = true;
  46423. if (Gamepads.gamepadDOMInfo) {
  46424. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46425. Gamepads.gamepadDOMInfo = null;
  46426. }
  46427. }
  46428. var newGamepad;
  46429. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46430. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46431. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46432. }
  46433. else {
  46434. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46435. }
  46436. this.babylonGamepads.push(newGamepad);
  46437. return newGamepad;
  46438. };
  46439. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46440. // Remove the gamepad from the list of gamepads to monitor.
  46441. for (var i in this.babylonGamepads) {
  46442. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46443. this.babylonGamepads.splice(+i, 1);
  46444. break;
  46445. }
  46446. }
  46447. // If no gamepads are left, stop the polling loop.
  46448. if (this.babylonGamepads.length == 0) {
  46449. this._stopMonitoringGamepads();
  46450. }
  46451. };
  46452. Gamepads.prototype._startMonitoringGamepads = function () {
  46453. if (!this.isMonitoring) {
  46454. this.isMonitoring = true;
  46455. this._checkGamepadsStatus();
  46456. }
  46457. };
  46458. Gamepads.prototype._stopMonitoringGamepads = function () {
  46459. this.isMonitoring = false;
  46460. };
  46461. Gamepads.prototype._checkGamepadsStatus = function () {
  46462. var _this = this;
  46463. // updating gamepad objects
  46464. this._updateGamepadObjects();
  46465. for (var i in this.babylonGamepads) {
  46466. this.babylonGamepads[i].update();
  46467. }
  46468. if (this.isMonitoring) {
  46469. if (window.requestAnimationFrame) {
  46470. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46471. }
  46472. else if (window.mozRequestAnimationFrame) {
  46473. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46474. }
  46475. else if (window.webkitRequestAnimationFrame) {
  46476. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46477. }
  46478. }
  46479. };
  46480. // This function is called only on Chrome, which does not yet support
  46481. // connection/disconnection events, but requires you to monitor
  46482. // an array for changes.
  46483. Gamepads.prototype._updateGamepadObjects = function () {
  46484. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46485. for (var i = 0; i < gamepads.length; i++) {
  46486. if (gamepads[i]) {
  46487. if (!(gamepads[i].index in this.babylonGamepads)) {
  46488. var newGamepad = this._addNewGamepad(gamepads[i]);
  46489. if (this._callbackGamepadConnected) {
  46490. this._callbackGamepadConnected(newGamepad);
  46491. }
  46492. }
  46493. else {
  46494. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46495. }
  46496. }
  46497. }
  46498. };
  46499. return Gamepads;
  46500. }());
  46501. BABYLON.Gamepads = Gamepads;
  46502. var StickValues = (function () {
  46503. function StickValues(x, y) {
  46504. this.x = x;
  46505. this.y = y;
  46506. }
  46507. return StickValues;
  46508. }());
  46509. BABYLON.StickValues = StickValues;
  46510. var Gamepad = (function () {
  46511. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46512. if (leftStickX === void 0) { leftStickX = 0; }
  46513. if (leftStickY === void 0) { leftStickY = 1; }
  46514. if (rightStickX === void 0) { rightStickX = 2; }
  46515. if (rightStickY === void 0) { rightStickY = 3; }
  46516. this.id = id;
  46517. this.index = index;
  46518. this.browserGamepad = browserGamepad;
  46519. this._leftStickAxisX = leftStickX;
  46520. this._leftStickAxisY = leftStickY;
  46521. this._rightStickAxisX = rightStickX;
  46522. this._rightStickAxisY = rightStickY;
  46523. if (this.browserGamepad.axes.length >= 2) {
  46524. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46525. }
  46526. if (this.browserGamepad.axes.length >= 4) {
  46527. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46528. }
  46529. }
  46530. Gamepad.prototype.onleftstickchanged = function (callback) {
  46531. this._onleftstickchanged = callback;
  46532. };
  46533. Gamepad.prototype.onrightstickchanged = function (callback) {
  46534. this._onrightstickchanged = callback;
  46535. };
  46536. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46537. get: function () {
  46538. return this._leftStick;
  46539. },
  46540. set: function (newValues) {
  46541. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46542. this._onleftstickchanged(newValues);
  46543. }
  46544. this._leftStick = newValues;
  46545. },
  46546. enumerable: true,
  46547. configurable: true
  46548. });
  46549. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46550. get: function () {
  46551. return this._rightStick;
  46552. },
  46553. set: function (newValues) {
  46554. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46555. this._onrightstickchanged(newValues);
  46556. }
  46557. this._rightStick = newValues;
  46558. },
  46559. enumerable: true,
  46560. configurable: true
  46561. });
  46562. Gamepad.prototype.update = function () {
  46563. if (this._leftStick) {
  46564. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46565. }
  46566. if (this._rightStick) {
  46567. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46568. }
  46569. };
  46570. return Gamepad;
  46571. }());
  46572. BABYLON.Gamepad = Gamepad;
  46573. var GenericPad = (function (_super) {
  46574. __extends(GenericPad, _super);
  46575. function GenericPad(id, index, gamepad) {
  46576. var _this = _super.call(this, id, index, gamepad) || this;
  46577. _this.id = id;
  46578. _this.index = index;
  46579. _this.gamepad = gamepad;
  46580. _this._buttons = new Array(gamepad.buttons.length);
  46581. return _this;
  46582. }
  46583. GenericPad.prototype.onbuttondown = function (callback) {
  46584. this._onbuttondown = callback;
  46585. };
  46586. GenericPad.prototype.onbuttonup = function (callback) {
  46587. this._onbuttonup = callback;
  46588. };
  46589. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46590. if (newValue !== currentValue) {
  46591. if (this._onbuttondown && newValue === 1) {
  46592. this._onbuttondown(buttonIndex);
  46593. }
  46594. if (this._onbuttonup && newValue === 0) {
  46595. this._onbuttonup(buttonIndex);
  46596. }
  46597. }
  46598. return newValue;
  46599. };
  46600. GenericPad.prototype.update = function () {
  46601. _super.prototype.update.call(this);
  46602. for (var index = 0; index < this._buttons.length; index++) {
  46603. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46604. }
  46605. };
  46606. return GenericPad;
  46607. }(Gamepad));
  46608. BABYLON.GenericPad = GenericPad;
  46609. var Xbox360Button;
  46610. (function (Xbox360Button) {
  46611. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46612. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46613. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46614. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46615. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46616. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46617. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46618. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46619. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46620. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46621. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46622. var Xbox360Dpad;
  46623. (function (Xbox360Dpad) {
  46624. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46625. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46626. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46627. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46628. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46629. var Xbox360Pad = (function (_super) {
  46630. __extends(Xbox360Pad, _super);
  46631. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46632. if (xboxOne === void 0) { xboxOne = false; }
  46633. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  46634. _this._leftTrigger = 0;
  46635. _this._rightTrigger = 0;
  46636. _this._buttonA = 0;
  46637. _this._buttonB = 0;
  46638. _this._buttonX = 0;
  46639. _this._buttonY = 0;
  46640. _this._buttonBack = 0;
  46641. _this._buttonStart = 0;
  46642. _this._buttonLB = 0;
  46643. _this._buttonRB = 0;
  46644. _this._buttonLeftStick = 0;
  46645. _this._buttonRightStick = 0;
  46646. _this._dPadUp = 0;
  46647. _this._dPadDown = 0;
  46648. _this._dPadLeft = 0;
  46649. _this._dPadRight = 0;
  46650. _this._isXboxOnePad = false;
  46651. _this._isXboxOnePad = xboxOne;
  46652. return _this;
  46653. }
  46654. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46655. this._onlefttriggerchanged = callback;
  46656. };
  46657. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46658. this._onrighttriggerchanged = callback;
  46659. };
  46660. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46661. get: function () {
  46662. return this._leftTrigger;
  46663. },
  46664. set: function (newValue) {
  46665. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46666. this._onlefttriggerchanged(newValue);
  46667. }
  46668. this._leftTrigger = newValue;
  46669. },
  46670. enumerable: true,
  46671. configurable: true
  46672. });
  46673. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46674. get: function () {
  46675. return this._rightTrigger;
  46676. },
  46677. set: function (newValue) {
  46678. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46679. this._onrighttriggerchanged(newValue);
  46680. }
  46681. this._rightTrigger = newValue;
  46682. },
  46683. enumerable: true,
  46684. configurable: true
  46685. });
  46686. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46687. this._onbuttondown = callback;
  46688. };
  46689. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46690. this._onbuttonup = callback;
  46691. };
  46692. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46693. this._ondpaddown = callback;
  46694. };
  46695. Xbox360Pad.prototype.ondpadup = function (callback) {
  46696. this._ondpadup = callback;
  46697. };
  46698. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46699. if (newValue !== currentValue) {
  46700. if (this._onbuttondown && newValue === 1) {
  46701. this._onbuttondown(buttonType);
  46702. }
  46703. if (this._onbuttonup && newValue === 0) {
  46704. this._onbuttonup(buttonType);
  46705. }
  46706. }
  46707. return newValue;
  46708. };
  46709. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46710. if (newValue !== currentValue) {
  46711. if (this._ondpaddown && newValue === 1) {
  46712. this._ondpaddown(buttonType);
  46713. }
  46714. if (this._ondpadup && newValue === 0) {
  46715. this._ondpadup(buttonType);
  46716. }
  46717. }
  46718. return newValue;
  46719. };
  46720. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46721. get: function () {
  46722. return this._buttonA;
  46723. },
  46724. set: function (value) {
  46725. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46726. },
  46727. enumerable: true,
  46728. configurable: true
  46729. });
  46730. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46731. get: function () {
  46732. return this._buttonB;
  46733. },
  46734. set: function (value) {
  46735. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46736. },
  46737. enumerable: true,
  46738. configurable: true
  46739. });
  46740. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46741. get: function () {
  46742. return this._buttonX;
  46743. },
  46744. set: function (value) {
  46745. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46746. },
  46747. enumerable: true,
  46748. configurable: true
  46749. });
  46750. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46751. get: function () {
  46752. return this._buttonY;
  46753. },
  46754. set: function (value) {
  46755. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46756. },
  46757. enumerable: true,
  46758. configurable: true
  46759. });
  46760. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46761. get: function () {
  46762. return this._buttonStart;
  46763. },
  46764. set: function (value) {
  46765. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46771. get: function () {
  46772. return this._buttonBack;
  46773. },
  46774. set: function (value) {
  46775. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46781. get: function () {
  46782. return this._buttonLB;
  46783. },
  46784. set: function (value) {
  46785. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46786. },
  46787. enumerable: true,
  46788. configurable: true
  46789. });
  46790. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46791. get: function () {
  46792. return this._buttonRB;
  46793. },
  46794. set: function (value) {
  46795. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46796. },
  46797. enumerable: true,
  46798. configurable: true
  46799. });
  46800. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46801. get: function () {
  46802. return this._buttonLeftStick;
  46803. },
  46804. set: function (value) {
  46805. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46811. get: function () {
  46812. return this._buttonRightStick;
  46813. },
  46814. set: function (value) {
  46815. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46816. },
  46817. enumerable: true,
  46818. configurable: true
  46819. });
  46820. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46821. get: function () {
  46822. return this._dPadUp;
  46823. },
  46824. set: function (value) {
  46825. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46826. },
  46827. enumerable: true,
  46828. configurable: true
  46829. });
  46830. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46831. get: function () {
  46832. return this._dPadDown;
  46833. },
  46834. set: function (value) {
  46835. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46836. },
  46837. enumerable: true,
  46838. configurable: true
  46839. });
  46840. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46841. get: function () {
  46842. return this._dPadLeft;
  46843. },
  46844. set: function (value) {
  46845. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46846. },
  46847. enumerable: true,
  46848. configurable: true
  46849. });
  46850. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46851. get: function () {
  46852. return this._dPadRight;
  46853. },
  46854. set: function (value) {
  46855. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. Xbox360Pad.prototype.update = function () {
  46861. _super.prototype.update.call(this);
  46862. if (this._isXboxOnePad) {
  46863. this.buttonA = this.browserGamepad.buttons[0].value;
  46864. this.buttonB = this.browserGamepad.buttons[1].value;
  46865. this.buttonX = this.browserGamepad.buttons[2].value;
  46866. this.buttonY = this.browserGamepad.buttons[3].value;
  46867. this.buttonLB = this.browserGamepad.buttons[4].value;
  46868. this.buttonRB = this.browserGamepad.buttons[5].value;
  46869. this.leftTrigger = this.browserGamepad.axes[2];
  46870. this.rightTrigger = this.browserGamepad.axes[5];
  46871. this.buttonBack = this.browserGamepad.buttons[9].value;
  46872. this.buttonStart = this.browserGamepad.buttons[8].value;
  46873. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46874. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46875. this.dPadUp = this.browserGamepad.buttons[11].value;
  46876. this.dPadDown = this.browserGamepad.buttons[12].value;
  46877. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46878. this.dPadRight = this.browserGamepad.buttons[14].value;
  46879. }
  46880. else {
  46881. this.buttonA = this.browserGamepad.buttons[0].value;
  46882. this.buttonB = this.browserGamepad.buttons[1].value;
  46883. this.buttonX = this.browserGamepad.buttons[2].value;
  46884. this.buttonY = this.browserGamepad.buttons[3].value;
  46885. this.buttonLB = this.browserGamepad.buttons[4].value;
  46886. this.buttonRB = this.browserGamepad.buttons[5].value;
  46887. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46888. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46889. this.buttonBack = this.browserGamepad.buttons[8].value;
  46890. this.buttonStart = this.browserGamepad.buttons[9].value;
  46891. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46892. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46893. this.dPadUp = this.browserGamepad.buttons[12].value;
  46894. this.dPadDown = this.browserGamepad.buttons[13].value;
  46895. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46896. this.dPadRight = this.browserGamepad.buttons[15].value;
  46897. }
  46898. };
  46899. return Xbox360Pad;
  46900. }(Gamepad));
  46901. BABYLON.Xbox360Pad = Xbox360Pad;
  46902. })(BABYLON || (BABYLON = {}));
  46903. //# sourceMappingURL=babylon.gamepads.js.map
  46904. var BABYLON;
  46905. (function (BABYLON) {
  46906. // We're mainly based on the logic defined into the FreeCamera code
  46907. var GamepadCamera = (function (_super) {
  46908. __extends(GamepadCamera, _super);
  46909. //-- end properties for backward compatibility for inputs
  46910. function GamepadCamera(name, position, scene) {
  46911. var _this;
  46912. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46913. _this = _super.call(this, name, position, scene) || this;
  46914. return _this;
  46915. }
  46916. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46917. //-- Begin properties for backward compatibility for inputs
  46918. get: function () {
  46919. var gamepad = this.inputs.attached["gamepad"];
  46920. if (gamepad)
  46921. return gamepad.gamepadAngularSensibility;
  46922. },
  46923. set: function (value) {
  46924. var gamepad = this.inputs.attached["gamepad"];
  46925. if (gamepad)
  46926. gamepad.gamepadAngularSensibility = value;
  46927. },
  46928. enumerable: true,
  46929. configurable: true
  46930. });
  46931. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46932. get: function () {
  46933. var gamepad = this.inputs.attached["gamepad"];
  46934. if (gamepad)
  46935. return gamepad.gamepadMoveSensibility;
  46936. },
  46937. set: function (value) {
  46938. var gamepad = this.inputs.attached["gamepad"];
  46939. if (gamepad)
  46940. gamepad.gamepadMoveSensibility = value;
  46941. },
  46942. enumerable: true,
  46943. configurable: true
  46944. });
  46945. GamepadCamera.prototype.getClassName = function () {
  46946. return "GamepadCamera";
  46947. };
  46948. return GamepadCamera;
  46949. }(BABYLON.UniversalCamera));
  46950. BABYLON.GamepadCamera = GamepadCamera;
  46951. })(BABYLON || (BABYLON = {}));
  46952. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46953. var BABYLON;
  46954. (function (BABYLON) {
  46955. var Analyser = (function () {
  46956. function Analyser(scene) {
  46957. this.SMOOTHING = 0.75;
  46958. this.FFT_SIZE = 512;
  46959. this.BARGRAPHAMPLITUDE = 256;
  46960. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46961. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46962. this._scene = scene;
  46963. this._audioEngine = BABYLON.Engine.audioEngine;
  46964. if (this._audioEngine.canUseWebAudio) {
  46965. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46966. this._webAudioAnalyser.minDecibels = -140;
  46967. this._webAudioAnalyser.maxDecibels = 0;
  46968. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46969. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46970. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46971. }
  46972. }
  46973. Analyser.prototype.getFrequencyBinCount = function () {
  46974. if (this._audioEngine.canUseWebAudio) {
  46975. return this._webAudioAnalyser.frequencyBinCount;
  46976. }
  46977. else {
  46978. return 0;
  46979. }
  46980. };
  46981. Analyser.prototype.getByteFrequencyData = function () {
  46982. if (this._audioEngine.canUseWebAudio) {
  46983. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46984. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46985. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46986. }
  46987. return this._byteFreqs;
  46988. };
  46989. Analyser.prototype.getByteTimeDomainData = function () {
  46990. if (this._audioEngine.canUseWebAudio) {
  46991. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46992. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46993. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46994. }
  46995. return this._byteTime;
  46996. };
  46997. Analyser.prototype.getFloatFrequencyData = function () {
  46998. if (this._audioEngine.canUseWebAudio) {
  46999. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47000. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47001. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47002. }
  47003. return this._floatFreqs;
  47004. };
  47005. Analyser.prototype.drawDebugCanvas = function () {
  47006. var _this = this;
  47007. if (this._audioEngine.canUseWebAudio) {
  47008. if (!this._debugCanvas) {
  47009. this._debugCanvas = document.createElement("canvas");
  47010. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47011. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47012. this._debugCanvas.style.position = "absolute";
  47013. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47014. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47015. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47016. document.body.appendChild(this._debugCanvas);
  47017. this._registerFunc = function () {
  47018. _this.drawDebugCanvas();
  47019. };
  47020. this._scene.registerBeforeRender(this._registerFunc);
  47021. }
  47022. if (this._registerFunc) {
  47023. var workingArray = this.getByteFrequencyData();
  47024. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47025. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47026. // Draw the frequency domain chart.
  47027. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47028. var value = workingArray[i];
  47029. var percent = value / this.BARGRAPHAMPLITUDE;
  47030. var height = this.DEBUGCANVASSIZE.height * percent;
  47031. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47032. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47033. var hue = i / this.getFrequencyBinCount() * 360;
  47034. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47035. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47036. }
  47037. }
  47038. }
  47039. };
  47040. Analyser.prototype.stopDebugCanvas = function () {
  47041. if (this._debugCanvas) {
  47042. this._scene.unregisterBeforeRender(this._registerFunc);
  47043. this._registerFunc = null;
  47044. document.body.removeChild(this._debugCanvas);
  47045. this._debugCanvas = null;
  47046. this._debugCanvasContext = null;
  47047. }
  47048. };
  47049. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47050. if (this._audioEngine.canUseWebAudio) {
  47051. inputAudioNode.connect(this._webAudioAnalyser);
  47052. this._webAudioAnalyser.connect(outputAudioNode);
  47053. }
  47054. };
  47055. Analyser.prototype.dispose = function () {
  47056. if (this._audioEngine.canUseWebAudio) {
  47057. this._webAudioAnalyser.disconnect();
  47058. }
  47059. };
  47060. return Analyser;
  47061. }());
  47062. BABYLON.Analyser = Analyser;
  47063. })(BABYLON || (BABYLON = {}));
  47064. //# sourceMappingURL=babylon.analyser.js.map
  47065. var BABYLON;
  47066. (function (BABYLON) {
  47067. var DepthRenderer = (function () {
  47068. function DepthRenderer(scene, type) {
  47069. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47070. var _this = this;
  47071. this._viewMatrix = BABYLON.Matrix.Zero();
  47072. this._projectionMatrix = BABYLON.Matrix.Zero();
  47073. this._transformMatrix = BABYLON.Matrix.Zero();
  47074. this._worldViewProjection = BABYLON.Matrix.Zero();
  47075. this._scene = scene;
  47076. var engine = scene.getEngine();
  47077. // Render target
  47078. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47079. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47080. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47081. this._depthMap.refreshRate = 1;
  47082. this._depthMap.renderParticles = false;
  47083. this._depthMap.renderList = null;
  47084. // set default depth value to 1.0 (far away)
  47085. this._depthMap.onClearObservable.add(function (engine) {
  47086. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47087. });
  47088. // Custom render function
  47089. var renderSubMesh = function (subMesh) {
  47090. var mesh = subMesh.getRenderingMesh();
  47091. var scene = _this._scene;
  47092. var engine = scene.getEngine();
  47093. // Culling
  47094. engine.setState(subMesh.getMaterial().backFaceCulling);
  47095. // Managing instances
  47096. var batch = mesh._getInstancesRenderList(subMesh._id);
  47097. if (batch.mustReturn) {
  47098. return;
  47099. }
  47100. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47101. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47102. engine.enableEffect(_this._effect);
  47103. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47104. var material = subMesh.getMaterial();
  47105. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47106. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47107. // Alpha test
  47108. if (material && material.needAlphaTesting()) {
  47109. var alphaTexture = material.getAlphaTestTexture();
  47110. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47111. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47112. }
  47113. // Bones
  47114. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47115. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47116. }
  47117. // Draw
  47118. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47119. }
  47120. };
  47121. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47122. var index;
  47123. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47124. renderSubMesh(opaqueSubMeshes.data[index]);
  47125. }
  47126. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47127. renderSubMesh(alphaTestSubMeshes.data[index]);
  47128. }
  47129. };
  47130. }
  47131. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47132. var material = subMesh.getMaterial();
  47133. if (material.disableDepthWrite) {
  47134. return false;
  47135. }
  47136. var defines = [];
  47137. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47138. var mesh = subMesh.getMesh();
  47139. var scene = mesh.getScene();
  47140. // Alpha test
  47141. if (material && material.needAlphaTesting()) {
  47142. defines.push("#define ALPHATEST");
  47143. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47144. attribs.push(BABYLON.VertexBuffer.UVKind);
  47145. defines.push("#define UV1");
  47146. }
  47147. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47148. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47149. defines.push("#define UV2");
  47150. }
  47151. }
  47152. // Bones
  47153. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47154. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47155. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47156. if (mesh.numBoneInfluencers > 4) {
  47157. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47158. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47159. }
  47160. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47161. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47162. }
  47163. else {
  47164. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47165. }
  47166. // Instances
  47167. if (useInstances) {
  47168. defines.push("#define INSTANCES");
  47169. attribs.push("world0");
  47170. attribs.push("world1");
  47171. attribs.push("world2");
  47172. attribs.push("world3");
  47173. }
  47174. // Get correct effect
  47175. var join = defines.join("\n");
  47176. if (this._cachedDefines !== join) {
  47177. this._cachedDefines = join;
  47178. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47179. }
  47180. return this._effect.isReady();
  47181. };
  47182. DepthRenderer.prototype.getDepthMap = function () {
  47183. return this._depthMap;
  47184. };
  47185. // Methods
  47186. DepthRenderer.prototype.dispose = function () {
  47187. this._depthMap.dispose();
  47188. };
  47189. return DepthRenderer;
  47190. }());
  47191. BABYLON.DepthRenderer = DepthRenderer;
  47192. })(BABYLON || (BABYLON = {}));
  47193. //# sourceMappingURL=babylon.depthRenderer.js.map
  47194. var BABYLON;
  47195. (function (BABYLON) {
  47196. var SSAORenderingPipeline = (function (_super) {
  47197. __extends(SSAORenderingPipeline, _super);
  47198. /**
  47199. * @constructor
  47200. * @param {string} name - The rendering pipeline name
  47201. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47202. * @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 }
  47203. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47204. */
  47205. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47206. var _this = _super.call(this, scene.getEngine(), name) || this;
  47207. // Members
  47208. /**
  47209. * The PassPostProcess id in the pipeline that contains the original scene color
  47210. * @type {string}
  47211. */
  47212. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47213. /**
  47214. * The SSAO PostProcess id in the pipeline
  47215. * @type {string}
  47216. */
  47217. _this.SSAORenderEffect = "SSAORenderEffect";
  47218. /**
  47219. * The horizontal blur PostProcess id in the pipeline
  47220. * @type {string}
  47221. */
  47222. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47223. /**
  47224. * The vertical blur PostProcess id in the pipeline
  47225. * @type {string}
  47226. */
  47227. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47228. /**
  47229. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47230. * @type {string}
  47231. */
  47232. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47233. /**
  47234. * The output strength of the SSAO post-process. Default value is 1.0.
  47235. * @type {number}
  47236. */
  47237. _this.totalStrength = 1.0;
  47238. /**
  47239. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47240. * @type {number}
  47241. */
  47242. _this.radius = 0.0001;
  47243. /**
  47244. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47245. * Must not be equal to fallOff and superior to fallOff.
  47246. * Default value is 0.975
  47247. * @type {number}
  47248. */
  47249. _this.area = 0.0075;
  47250. /**
  47251. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47252. * Must not be equal to area and inferior to area.
  47253. * Default value is 0.0
  47254. * @type {number}
  47255. */
  47256. _this.fallOff = 0.000001;
  47257. /**
  47258. * The base color of the SSAO post-process
  47259. * The final result is "base + ssao" between [0, 1]
  47260. * @type {number}
  47261. */
  47262. _this.base = 0.5;
  47263. _this._firstUpdate = true;
  47264. _this._scene = scene;
  47265. // Set up assets
  47266. _this._createRandomTexture();
  47267. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47268. var ssaoRatio = ratio.ssaoRatio || ratio;
  47269. var combineRatio = ratio.combineRatio || ratio;
  47270. _this._ratio = {
  47271. ssaoRatio: ssaoRatio,
  47272. combineRatio: combineRatio
  47273. };
  47274. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47275. _this._createSSAOPostProcess(ssaoRatio);
  47276. _this._createBlurPostProcess(ssaoRatio);
  47277. _this._createSSAOCombinePostProcess(combineRatio);
  47278. // Set up pipeline
  47279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47281. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47282. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47283. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47284. // Finish
  47285. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47286. if (cameras)
  47287. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47288. return _this;
  47289. }
  47290. // Public Methods
  47291. /**
  47292. * Returns the horizontal blur PostProcess
  47293. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47294. */
  47295. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47296. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47297. return null;
  47298. };
  47299. /**
  47300. * Returns the vertical blur PostProcess
  47301. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47302. */
  47303. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47304. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47305. return null;
  47306. };
  47307. /**
  47308. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47309. */
  47310. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47311. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47312. for (var i = 0; i < this._scene.cameras.length; i++) {
  47313. var camera = this._scene.cameras[i];
  47314. this._originalColorPostProcess.dispose(camera);
  47315. this._ssaoPostProcess.dispose(camera);
  47316. this._blurHPostProcess.dispose(camera);
  47317. this._blurVPostProcess.dispose(camera);
  47318. this._ssaoCombinePostProcess.dispose(camera);
  47319. }
  47320. this._randomTexture.dispose();
  47321. if (disableDepthRender)
  47322. this._scene.disableDepthRenderer();
  47323. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47324. };
  47325. // Private Methods
  47326. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47327. var _this = this;
  47328. /*
  47329. var samplerOffsets = [
  47330. -8.0, -6.0, -4.0, -2.0,
  47331. 0.0,
  47332. 2.0, 4.0, 6.0, 8.0
  47333. ];
  47334. */
  47335. var samples = 16;
  47336. var samplerOffsets = [];
  47337. for (var i = -8; i < 8; i++) {
  47338. samplerOffsets.push(i * 2);
  47339. }
  47340. 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");
  47341. this._blurHPostProcess.onApply = function (effect) {
  47342. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47343. effect.setTexture("depthSampler", _this._depthTexture);
  47344. if (_this._firstUpdate) {
  47345. effect.setArray("samplerOffsets", samplerOffsets);
  47346. }
  47347. };
  47348. 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");
  47349. this._blurVPostProcess.onApply = function (effect) {
  47350. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47351. effect.setTexture("depthSampler", _this._depthTexture);
  47352. if (_this._firstUpdate) {
  47353. effect.setArray("samplerOffsets", samplerOffsets);
  47354. _this._firstUpdate = false;
  47355. }
  47356. };
  47357. };
  47358. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47359. var _this = this;
  47360. var numSamples = 16;
  47361. var sampleSphere = [
  47362. 0.5381, 0.1856, -0.4319,
  47363. 0.1379, 0.2486, 0.4430,
  47364. 0.3371, 0.5679, -0.0057,
  47365. -0.6999, -0.0451, -0.0019,
  47366. 0.0689, -0.1598, -0.8547,
  47367. 0.0560, 0.0069, -0.1843,
  47368. -0.0146, 0.1402, 0.0762,
  47369. 0.0100, -0.1924, -0.0344,
  47370. -0.3577, -0.5301, -0.4358,
  47371. -0.3169, 0.1063, 0.0158,
  47372. 0.0103, -0.5869, 0.0046,
  47373. -0.0897, -0.4940, 0.3287,
  47374. 0.7119, -0.0154, -0.0918,
  47375. -0.0533, 0.0596, -0.5411,
  47376. 0.0352, -0.0631, 0.5460,
  47377. -0.4776, 0.2847, -0.0271
  47378. ];
  47379. var samplesFactor = 1.0 / numSamples;
  47380. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47381. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47382. "area", "fallOff", "base", "range", "viewport"
  47383. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47384. var viewport = new BABYLON.Vector2(0, 0);
  47385. this._ssaoPostProcess.onApply = function (effect) {
  47386. if (_this._firstUpdate) {
  47387. effect.setArray3("sampleSphere", sampleSphere);
  47388. effect.setFloat("samplesFactor", samplesFactor);
  47389. effect.setFloat("randTextureTiles", 4.0);
  47390. }
  47391. effect.setFloat("totalStrength", _this.totalStrength);
  47392. effect.setFloat("radius", _this.radius);
  47393. effect.setFloat("area", _this.area);
  47394. effect.setFloat("fallOff", _this.fallOff);
  47395. effect.setFloat("base", _this.base);
  47396. effect.setTexture("textureSampler", _this._depthTexture);
  47397. effect.setTexture("randomSampler", _this._randomTexture);
  47398. };
  47399. };
  47400. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47401. var _this = this;
  47402. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47403. this._ssaoCombinePostProcess.onApply = function (effect) {
  47404. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47405. };
  47406. };
  47407. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47408. var size = 512;
  47409. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47410. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47411. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47412. var context = this._randomTexture.getContext();
  47413. var rand = function (min, max) {
  47414. return Math.random() * (max - min) + min;
  47415. };
  47416. var randVector = BABYLON.Vector3.Zero();
  47417. for (var x = 0; x < size; x++) {
  47418. for (var y = 0; y < size; y++) {
  47419. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47420. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47421. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47422. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47423. context.fillRect(x, y, 1, 1);
  47424. }
  47425. }
  47426. this._randomTexture.update(false);
  47427. };
  47428. return SSAORenderingPipeline;
  47429. }(BABYLON.PostProcessRenderPipeline));
  47430. __decorate([
  47431. BABYLON.serialize()
  47432. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47433. __decorate([
  47434. BABYLON.serialize()
  47435. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47436. __decorate([
  47437. BABYLON.serialize()
  47438. ], SSAORenderingPipeline.prototype, "area", void 0);
  47439. __decorate([
  47440. BABYLON.serialize()
  47441. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47442. __decorate([
  47443. BABYLON.serialize()
  47444. ], SSAORenderingPipeline.prototype, "base", void 0);
  47445. __decorate([
  47446. BABYLON.serialize()
  47447. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47448. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47449. })(BABYLON || (BABYLON = {}));
  47450. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47451. var BABYLON;
  47452. (function (BABYLON) {
  47453. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47454. var VolumetricLightScatteringPostProcess = (function (_super) {
  47455. __extends(VolumetricLightScatteringPostProcess, _super);
  47456. /**
  47457. * @constructor
  47458. * @param {string} name - The post-process name
  47459. * @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)
  47460. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47461. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47462. * @param {number} samples - The post-process quality, default 100
  47463. * @param {number} samplingMode - The post-process filtering mode
  47464. * @param {BABYLON.Engine} engine - The babylon engine
  47465. * @param {boolean} reusable - If the post-process is reusable
  47466. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47467. */
  47468. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47469. if (samples === void 0) { samples = 100; }
  47470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47471. 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;
  47472. _this._screenCoordinates = BABYLON.Vector2.Zero();
  47473. /**
  47474. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47475. * @type {Vector3}
  47476. */
  47477. _this.customMeshPosition = BABYLON.Vector3.Zero();
  47478. /**
  47479. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47480. * @type {boolean}
  47481. */
  47482. _this.useCustomMeshPosition = false;
  47483. /**
  47484. * If the post-process should inverse the light scattering direction
  47485. * @type {boolean}
  47486. */
  47487. _this.invert = true;
  47488. /**
  47489. * Array containing the excluded meshes not rendered in the internal pass
  47490. */
  47491. _this.excludedMeshes = new Array();
  47492. /**
  47493. * Controls the overall intensity of the post-process
  47494. * @type {number}
  47495. */
  47496. _this.exposure = 0.3;
  47497. /**
  47498. * Dissipates each sample's contribution in range [0, 1]
  47499. * @type {number}
  47500. */
  47501. _this.decay = 0.96815;
  47502. /**
  47503. * Controls the overall intensity of each sample
  47504. * @type {number}
  47505. */
  47506. _this.weight = 0.58767;
  47507. /**
  47508. * Controls the density of each sample
  47509. * @type {number}
  47510. */
  47511. _this.density = 0.926;
  47512. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47513. var engine = scene.getEngine();
  47514. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47515. // Configure mesh
  47516. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47517. // Configure
  47518. _this._createPass(scene, ratio.passRatio || ratio);
  47519. _this.onActivate = function (camera) {
  47520. if (!_this.isSupported) {
  47521. _this.dispose(camera);
  47522. }
  47523. _this.onActivate = null;
  47524. };
  47525. _this.onApplyObservable.add(function (effect) {
  47526. _this._updateMeshScreenCoordinates(scene);
  47527. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47528. effect.setFloat("exposure", _this.exposure);
  47529. effect.setFloat("decay", _this.decay);
  47530. effect.setFloat("weight", _this.weight);
  47531. effect.setFloat("density", _this.density);
  47532. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47533. });
  47534. return _this;
  47535. }
  47536. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47537. get: function () {
  47538. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47539. return false;
  47540. },
  47541. set: function (useDiffuseColor) {
  47542. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47543. },
  47544. enumerable: true,
  47545. configurable: true
  47546. });
  47547. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47548. var mesh = subMesh.getMesh();
  47549. // Render this.mesh as default
  47550. if (mesh === this.mesh) {
  47551. return mesh.material.isReady(mesh);
  47552. }
  47553. var defines = [];
  47554. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47555. var material = subMesh.getMaterial();
  47556. var needUV = false;
  47557. // Alpha test
  47558. if (material) {
  47559. if (material.needAlphaTesting()) {
  47560. defines.push("#define ALPHATEST");
  47561. }
  47562. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47563. attribs.push(BABYLON.VertexBuffer.UVKind);
  47564. defines.push("#define UV1");
  47565. }
  47566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47567. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47568. defines.push("#define UV2");
  47569. }
  47570. }
  47571. // Bones
  47572. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47573. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47574. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47575. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47576. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47577. }
  47578. else {
  47579. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47580. }
  47581. // Instances
  47582. if (useInstances) {
  47583. defines.push("#define INSTANCES");
  47584. attribs.push("world0");
  47585. attribs.push("world1");
  47586. attribs.push("world2");
  47587. attribs.push("world3");
  47588. }
  47589. // Get correct effect
  47590. var join = defines.join("\n");
  47591. if (this._cachedDefines !== join) {
  47592. this._cachedDefines = join;
  47593. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47594. }
  47595. return this._volumetricLightScatteringPass.isReady();
  47596. };
  47597. /**
  47598. * Sets the new light position for light scattering effect
  47599. * @param {BABYLON.Vector3} The new custom light position
  47600. */
  47601. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47602. this.customMeshPosition = position;
  47603. };
  47604. /**
  47605. * Returns the light position for light scattering effect
  47606. * @return {BABYLON.Vector3} The custom light position
  47607. */
  47608. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47609. return this.customMeshPosition;
  47610. };
  47611. /**
  47612. * Disposes the internal assets and detaches the post-process from the camera
  47613. */
  47614. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47615. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47616. if (rttIndex !== -1) {
  47617. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47618. }
  47619. this._volumetricLightScatteringRTT.dispose();
  47620. _super.prototype.dispose.call(this, camera);
  47621. };
  47622. /**
  47623. * Returns the render target texture used by the post-process
  47624. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47625. */
  47626. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47627. return this._volumetricLightScatteringRTT;
  47628. };
  47629. // Private methods
  47630. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47631. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47632. return true;
  47633. }
  47634. return false;
  47635. };
  47636. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47637. var _this = this;
  47638. var engine = scene.getEngine();
  47639. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47640. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47641. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47642. this._volumetricLightScatteringRTT.renderList = null;
  47643. this._volumetricLightScatteringRTT.renderParticles = false;
  47644. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47645. // Custom render function for submeshes
  47646. var renderSubMesh = function (subMesh) {
  47647. var mesh = subMesh.getRenderingMesh();
  47648. if (_this._meshExcluded(mesh)) {
  47649. return;
  47650. }
  47651. var scene = mesh.getScene();
  47652. var engine = scene.getEngine();
  47653. // Culling
  47654. engine.setState(subMesh.getMaterial().backFaceCulling);
  47655. // Managing instances
  47656. var batch = mesh._getInstancesRenderList(subMesh._id);
  47657. if (batch.mustReturn) {
  47658. return;
  47659. }
  47660. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47661. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47662. var effect = _this._volumetricLightScatteringPass;
  47663. if (mesh === _this.mesh) {
  47664. effect = subMesh.getMaterial().getEffect();
  47665. }
  47666. engine.enableEffect(effect);
  47667. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47668. if (mesh === _this.mesh) {
  47669. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47670. }
  47671. else {
  47672. var material = subMesh.getMaterial();
  47673. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47674. // Alpha test
  47675. if (material && material.needAlphaTesting()) {
  47676. var alphaTexture = material.getAlphaTestTexture();
  47677. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47678. if (alphaTexture) {
  47679. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47680. }
  47681. }
  47682. // Bones
  47683. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47684. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47685. }
  47686. }
  47687. // Draw
  47688. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47689. }
  47690. };
  47691. // Render target texture callbacks
  47692. var savedSceneClearColor;
  47693. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47694. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47695. savedSceneClearColor = scene.clearColor;
  47696. scene.clearColor = sceneClearColor;
  47697. });
  47698. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47699. scene.clearColor = savedSceneClearColor;
  47700. });
  47701. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47702. var engine = scene.getEngine();
  47703. var index;
  47704. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47705. renderSubMesh(opaqueSubMeshes.data[index]);
  47706. }
  47707. engine.setAlphaTesting(true);
  47708. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47709. renderSubMesh(alphaTestSubMeshes.data[index]);
  47710. }
  47711. engine.setAlphaTesting(false);
  47712. if (transparentSubMeshes.length) {
  47713. // Sort sub meshes
  47714. for (index = 0; index < transparentSubMeshes.length; index++) {
  47715. var submesh = transparentSubMeshes.data[index];
  47716. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47717. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47718. }
  47719. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47720. sortedArray.sort(function (a, b) {
  47721. // Alpha index first
  47722. if (a._alphaIndex > b._alphaIndex) {
  47723. return 1;
  47724. }
  47725. if (a._alphaIndex < b._alphaIndex) {
  47726. return -1;
  47727. }
  47728. // Then distance to camera
  47729. if (a._distanceToCamera < b._distanceToCamera) {
  47730. return 1;
  47731. }
  47732. if (a._distanceToCamera > b._distanceToCamera) {
  47733. return -1;
  47734. }
  47735. return 0;
  47736. });
  47737. // Render sub meshes
  47738. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47739. for (index = 0; index < sortedArray.length; index++) {
  47740. renderSubMesh(sortedArray[index]);
  47741. }
  47742. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47743. }
  47744. };
  47745. };
  47746. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47747. var transform = scene.getTransformMatrix();
  47748. var meshPosition;
  47749. if (this.useCustomMeshPosition) {
  47750. meshPosition = this.customMeshPosition;
  47751. }
  47752. else if (this.attachedNode) {
  47753. meshPosition = this.attachedNode.position;
  47754. }
  47755. else {
  47756. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47757. }
  47758. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47759. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47760. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47761. if (this.invert)
  47762. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47763. };
  47764. // Static methods
  47765. /**
  47766. * Creates a default mesh for the Volumeric Light Scattering post-process
  47767. * @param {string} The mesh name
  47768. * @param {BABYLON.Scene} The scene where to create the mesh
  47769. * @return {BABYLON.Mesh} the default mesh
  47770. */
  47771. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47772. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47773. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47774. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47775. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47776. mesh.material = material;
  47777. return mesh;
  47778. };
  47779. return VolumetricLightScatteringPostProcess;
  47780. }(BABYLON.PostProcess));
  47781. __decorate([
  47782. BABYLON.serializeAsVector3()
  47783. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47784. __decorate([
  47785. BABYLON.serialize()
  47786. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47787. __decorate([
  47788. BABYLON.serialize()
  47789. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47790. __decorate([
  47791. BABYLON.serializeAsMeshReference()
  47792. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47793. __decorate([
  47794. BABYLON.serialize()
  47795. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47796. __decorate([
  47797. BABYLON.serialize()
  47798. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47799. __decorate([
  47800. BABYLON.serialize()
  47801. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47802. __decorate([
  47803. BABYLON.serialize()
  47804. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47805. __decorate([
  47806. BABYLON.serialize()
  47807. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47808. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47809. })(BABYLON || (BABYLON = {}));
  47810. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47811. // BABYLON.JS Chromatic Aberration GLSL Shader
  47812. // Author: Olivier Guyot
  47813. // Separates very slightly R, G and B colors on the edges of the screen
  47814. // Inspired by Francois Tarlier & Martins Upitis
  47815. var BABYLON;
  47816. (function (BABYLON) {
  47817. var LensRenderingPipeline = (function (_super) {
  47818. __extends(LensRenderingPipeline, _super);
  47819. /**
  47820. * @constructor
  47821. *
  47822. * Effect parameters are as follow:
  47823. * {
  47824. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47825. * edge_blur: number; // from 0 to x (1 for realism)
  47826. * distortion: number; // from 0 to x (1 for realism)
  47827. * grain_amount: number; // from 0 to 1
  47828. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47829. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47830. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47831. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47832. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47833. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47834. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47835. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47836. * }
  47837. * Note: if an effect parameter is unset, effect is disabled
  47838. *
  47839. * @param {string} name - The rendering pipeline name
  47840. * @param {object} parameters - An object containing all parameters (see above)
  47841. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47842. * @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)
  47843. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47844. */
  47845. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47846. if (ratio === void 0) { ratio = 1.0; }
  47847. var _this = _super.call(this, scene.getEngine(), name) || this;
  47848. // Lens effects can be of the following:
  47849. // - chromatic aberration (slight shift of RGB colors)
  47850. // - blur on the edge of the lens
  47851. // - lens distortion
  47852. // - depth-of-field blur & highlights enhancing
  47853. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47854. // - grain effect (noise or custom texture)
  47855. // Two additional texture samplers are needed:
  47856. // - depth map (for depth-of-field)
  47857. // - grain texture
  47858. /**
  47859. * The chromatic aberration PostProcess id in the pipeline
  47860. * @type {string}
  47861. */
  47862. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47863. /**
  47864. * The highlights enhancing PostProcess id in the pipeline
  47865. * @type {string}
  47866. */
  47867. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47868. /**
  47869. * The depth-of-field PostProcess id in the pipeline
  47870. * @type {string}
  47871. */
  47872. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47873. _this._scene = scene;
  47874. // Fetch texture samplers
  47875. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47876. if (parameters.grain_texture) {
  47877. _this._grainTexture = parameters.grain_texture;
  47878. }
  47879. else {
  47880. _this._createGrainTexture();
  47881. }
  47882. // save parameters
  47883. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47884. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47885. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47886. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47887. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47888. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47889. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47890. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47891. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47892. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47893. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47894. // Create effects
  47895. _this._createChromaticAberrationPostProcess(ratio);
  47896. _this._createHighlightsPostProcess(ratio);
  47897. _this._createDepthOfFieldPostProcess(ratio / 4);
  47898. // Set up pipeline
  47899. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47900. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47901. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47902. if (_this._highlightsGain === -1) {
  47903. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47904. }
  47905. // Finish
  47906. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47907. if (cameras) {
  47908. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47909. }
  47910. return _this;
  47911. }
  47912. // public methods (self explanatory)
  47913. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47914. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47915. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47916. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47917. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47918. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47919. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47920. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47921. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47922. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47923. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47924. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47925. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47926. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47927. };
  47928. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47929. this._highlightsPostProcess.updateEffect();
  47930. };
  47931. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47932. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47933. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47934. this._highlightsGain = amount;
  47935. };
  47936. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47937. if (this._highlightsGain === -1) {
  47938. this._highlightsGain = 1.0;
  47939. }
  47940. this._highlightsThreshold = amount;
  47941. };
  47942. LensRenderingPipeline.prototype.disableHighlights = function () {
  47943. this._highlightsGain = -1;
  47944. };
  47945. /**
  47946. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47947. */
  47948. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47949. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47950. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47951. this._chromaticAberrationPostProcess = undefined;
  47952. this._highlightsPostProcess = undefined;
  47953. this._depthOfFieldPostProcess = undefined;
  47954. this._grainTexture.dispose();
  47955. if (disableDepthRender)
  47956. this._scene.disableDepthRenderer();
  47957. };
  47958. // colors shifting and distortion
  47959. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47960. var _this = this;
  47961. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47962. [], // samplers
  47963. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47964. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47965. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47966. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47967. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47968. };
  47969. };
  47970. // highlights enhancing
  47971. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47972. var _this = this;
  47973. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47974. [], // samplers
  47975. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47976. this._highlightsPostProcess.onApply = function (effect) {
  47977. effect.setFloat('gain', _this._highlightsGain);
  47978. effect.setFloat('threshold', _this._highlightsThreshold);
  47979. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47980. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47981. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47982. };
  47983. };
  47984. // colors shifting and distortion
  47985. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47986. var _this = this;
  47987. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47988. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47989. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47990. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47991. this._depthOfFieldPostProcess.onApply = function (effect) {
  47992. effect.setTexture("depthSampler", _this._depthTexture);
  47993. effect.setTexture("grainSampler", _this._grainTexture);
  47994. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47995. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47996. effect.setFloat('grain_amount', _this._grainAmount);
  47997. effect.setBool('blur_noise', _this._blurNoise);
  47998. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47999. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48000. effect.setFloat('distortion', _this._distortion);
  48001. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48002. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48003. effect.setFloat('aperture', _this._dofAperture);
  48004. effect.setFloat('darken', _this._dofDarken);
  48005. effect.setFloat('edge_blur', _this._edgeBlur);
  48006. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48007. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48008. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48009. };
  48010. };
  48011. // creates a black and white random noise texture, 512x512
  48012. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48013. var size = 512;
  48014. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48015. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48016. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48017. var context = this._grainTexture.getContext();
  48018. var rand = function (min, max) {
  48019. return Math.random() * (max - min) + min;
  48020. };
  48021. var value;
  48022. for (var x = 0; x < size; x++) {
  48023. for (var y = 0; y < size; y++) {
  48024. value = Math.floor(rand(0.42, 0.58) * 255);
  48025. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48026. context.fillRect(x, y, 1, 1);
  48027. }
  48028. }
  48029. this._grainTexture.update(false);
  48030. };
  48031. return LensRenderingPipeline;
  48032. }(BABYLON.PostProcessRenderPipeline));
  48033. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48034. })(BABYLON || (BABYLON = {}));
  48035. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48036. //
  48037. // This post-process allows the modification of rendered colors by using
  48038. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48039. //
  48040. // The object needs to be provided an url to a texture containing the color
  48041. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48042. // Use an image editing software to tweak the LUT to match your needs.
  48043. //
  48044. // For an example of a color LUT, see here:
  48045. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48046. // For explanations on color grading, see here:
  48047. // http://udn.epicgames.com/Three/ColorGrading.html
  48048. //
  48049. var BABYLON;
  48050. (function (BABYLON) {
  48051. var ColorCorrectionPostProcess = (function (_super) {
  48052. __extends(ColorCorrectionPostProcess, _super);
  48053. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48054. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48055. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48056. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48057. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48058. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48059. _this.onApply = function (effect) {
  48060. effect.setTexture("colorTable", _this._colorTableTexture);
  48061. };
  48062. return _this;
  48063. }
  48064. return ColorCorrectionPostProcess;
  48065. }(BABYLON.PostProcess));
  48066. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48067. })(BABYLON || (BABYLON = {}));
  48068. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48069. var BABYLON;
  48070. (function (BABYLON) {
  48071. var AnaglyphFreeCamera = (function (_super) {
  48072. __extends(AnaglyphFreeCamera, _super);
  48073. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48074. var _this = _super.call(this, name, position, scene) || this;
  48075. _this.interaxialDistance = interaxialDistance;
  48076. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48077. return _this;
  48078. }
  48079. AnaglyphFreeCamera.prototype.getClassName = function () {
  48080. return "AnaglyphFreeCamera";
  48081. };
  48082. return AnaglyphFreeCamera;
  48083. }(BABYLON.FreeCamera));
  48084. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48085. var AnaglyphArcRotateCamera = (function (_super) {
  48086. __extends(AnaglyphArcRotateCamera, _super);
  48087. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48088. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48089. _this.interaxialDistance = interaxialDistance;
  48090. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48091. return _this;
  48092. }
  48093. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48094. return "AnaglyphArcRotateCamera";
  48095. };
  48096. return AnaglyphArcRotateCamera;
  48097. }(BABYLON.ArcRotateCamera));
  48098. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48099. var AnaglyphGamepadCamera = (function (_super) {
  48100. __extends(AnaglyphGamepadCamera, _super);
  48101. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48102. var _this = _super.call(this, name, position, scene) || this;
  48103. _this.interaxialDistance = interaxialDistance;
  48104. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48105. return _this;
  48106. }
  48107. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48108. return "AnaglyphGamepadCamera";
  48109. };
  48110. return AnaglyphGamepadCamera;
  48111. }(BABYLON.GamepadCamera));
  48112. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48113. var AnaglyphUniversalCamera = (function (_super) {
  48114. __extends(AnaglyphUniversalCamera, _super);
  48115. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48116. var _this = _super.call(this, name, position, scene) || this;
  48117. _this.interaxialDistance = interaxialDistance;
  48118. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48119. return _this;
  48120. }
  48121. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48122. return "AnaglyphUniversalCamera";
  48123. };
  48124. return AnaglyphUniversalCamera;
  48125. }(BABYLON.UniversalCamera));
  48126. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48127. var StereoscopicFreeCamera = (function (_super) {
  48128. __extends(StereoscopicFreeCamera, _super);
  48129. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48130. var _this = _super.call(this, name, position, scene) || this;
  48131. _this.interaxialDistance = interaxialDistance;
  48132. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48133. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48134. return _this;
  48135. }
  48136. StereoscopicFreeCamera.prototype.getClassName = function () {
  48137. return "StereoscopicFreeCamera";
  48138. };
  48139. return StereoscopicFreeCamera;
  48140. }(BABYLON.FreeCamera));
  48141. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48142. var StereoscopicArcRotateCamera = (function (_super) {
  48143. __extends(StereoscopicArcRotateCamera, _super);
  48144. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48145. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48146. _this.interaxialDistance = interaxialDistance;
  48147. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48148. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48149. return _this;
  48150. }
  48151. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48152. return "StereoscopicArcRotateCamera";
  48153. };
  48154. return StereoscopicArcRotateCamera;
  48155. }(BABYLON.ArcRotateCamera));
  48156. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48157. var StereoscopicGamepadCamera = (function (_super) {
  48158. __extends(StereoscopicGamepadCamera, _super);
  48159. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48160. var _this = _super.call(this, name, position, scene) || this;
  48161. _this.interaxialDistance = interaxialDistance;
  48162. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48163. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48164. return _this;
  48165. }
  48166. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48167. return "StereoscopicGamepadCamera";
  48168. };
  48169. return StereoscopicGamepadCamera;
  48170. }(BABYLON.GamepadCamera));
  48171. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48172. var StereoscopicUniversalCamera = (function (_super) {
  48173. __extends(StereoscopicUniversalCamera, _super);
  48174. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48175. var _this = _super.call(this, name, position, scene) || this;
  48176. _this.interaxialDistance = interaxialDistance;
  48177. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48178. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48179. return _this;
  48180. }
  48181. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48182. return "StereoscopicUniversalCamera";
  48183. };
  48184. return StereoscopicUniversalCamera;
  48185. }(BABYLON.UniversalCamera));
  48186. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48187. })(BABYLON || (BABYLON = {}));
  48188. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48189. var BABYLON;
  48190. (function (BABYLON) {
  48191. var HDRRenderingPipeline = (function (_super) {
  48192. __extends(HDRRenderingPipeline, _super);
  48193. /**
  48194. * @constructor
  48195. * @param {string} name - The rendering pipeline name
  48196. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48197. * @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)
  48198. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48199. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48200. */
  48201. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48202. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48203. var _this = _super.call(this, scene.getEngine(), name) || this;
  48204. /**
  48205. * Public members
  48206. */
  48207. // Gaussian Blur
  48208. /**
  48209. * Gaussian blur coefficient
  48210. * @type {number}
  48211. */
  48212. _this.gaussCoeff = 0.3;
  48213. /**
  48214. * Gaussian blur mean
  48215. * @type {number}
  48216. */
  48217. _this.gaussMean = 1.0;
  48218. /**
  48219. * Gaussian blur standard deviation
  48220. * @type {number}
  48221. */
  48222. _this.gaussStandDev = 0.8;
  48223. /**
  48224. * Gaussian blur multiplier. Multiplies the blur effect
  48225. * @type {number}
  48226. */
  48227. _this.gaussMultiplier = 4.0;
  48228. // HDR
  48229. /**
  48230. * Exposure, controls the overall intensity of the pipeline
  48231. * @type {number}
  48232. */
  48233. _this.exposure = 1.0;
  48234. /**
  48235. * Minimum luminance that the post-process can output. Luminance is >= 0
  48236. * @type {number}
  48237. */
  48238. _this.minimumLuminance = 1.0;
  48239. /**
  48240. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48241. * @type {number}
  48242. */
  48243. _this.maximumLuminance = 1e20;
  48244. /**
  48245. * Increase rate for luminance: eye adaptation speed to dark
  48246. * @type {number}
  48247. */
  48248. _this.luminanceIncreaserate = 0.5;
  48249. /**
  48250. * Decrease rate for luminance: eye adaptation speed to bright
  48251. * @type {number}
  48252. */
  48253. _this.luminanceDecreaseRate = 0.5;
  48254. // Bright pass
  48255. /**
  48256. * Minimum luminance needed to compute HDR
  48257. * @type {number}
  48258. */
  48259. _this.brightThreshold = 0.8;
  48260. _this._needUpdate = true;
  48261. _this._scene = scene;
  48262. // Bright pass
  48263. _this._createBrightPassPostProcess(scene, ratio);
  48264. // Down sample X4
  48265. _this._createDownSampleX4PostProcess(scene, ratio);
  48266. // Create gaussian blur post-processes
  48267. _this._createGaussianBlurPostProcess(scene, ratio);
  48268. // Texture adder
  48269. _this._createTextureAdderPostProcess(scene, ratio);
  48270. // Luminance generator
  48271. _this._createLuminanceGeneratorPostProcess(scene);
  48272. // HDR
  48273. _this._createHDRPostProcess(scene, ratio);
  48274. // Pass postprocess
  48275. if (originalPostProcess === null) {
  48276. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48277. }
  48278. else {
  48279. _this._originalPostProcess = originalPostProcess;
  48280. }
  48281. // Configure pipeline
  48282. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48283. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48284. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48285. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48286. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48288. var addDownSamplerPostProcess = function (id) {
  48289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48290. };
  48291. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48292. addDownSamplerPostProcess(i);
  48293. }
  48294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48295. // Finish
  48296. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48297. if (cameras !== null) {
  48298. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48299. }
  48300. _this.update();
  48301. return _this;
  48302. }
  48303. /**
  48304. * Tells the pipeline to update its post-processes
  48305. */
  48306. HDRRenderingPipeline.prototype.update = function () {
  48307. this._needUpdate = true;
  48308. };
  48309. /**
  48310. * Returns the current calculated luminance
  48311. */
  48312. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48313. return this._hdrCurrentLuminance;
  48314. };
  48315. /**
  48316. * Returns the currently drawn luminance
  48317. */
  48318. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48319. return this._hdrOutputLuminance;
  48320. };
  48321. /**
  48322. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48323. */
  48324. HDRRenderingPipeline.prototype.dispose = function () {
  48325. this._originalPostProcess = undefined;
  48326. this._brightPassPostProcess = undefined;
  48327. this._downSampleX4PostProcess = undefined;
  48328. this._guassianBlurHPostProcess = undefined;
  48329. this._guassianBlurVPostProcess = undefined;
  48330. this._textureAdderPostProcess = undefined;
  48331. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48332. this._downSamplePostProcesses[i] = undefined;
  48333. }
  48334. this._hdrPostProcess = undefined;
  48335. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48336. };
  48337. /**
  48338. * Creates the HDR post-process and computes the luminance adaptation
  48339. */
  48340. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48341. var _this = this;
  48342. var hdrLastLuminance = 0.0;
  48343. this._hdrOutputLuminance = -1.0;
  48344. this._hdrCurrentLuminance = 1.0;
  48345. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48346. this._hdrPostProcess.onApply = function (effect) {
  48347. if (_this._hdrOutputLuminance < 0.0) {
  48348. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48349. }
  48350. else {
  48351. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48352. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48353. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48354. }
  48355. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48356. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48357. }
  48358. else {
  48359. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48360. }
  48361. }
  48362. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48363. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48364. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48365. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48366. effect.setFloat("exposure", _this.exposure);
  48367. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48368. _this._needUpdate = false;
  48369. };
  48370. };
  48371. /**
  48372. * Texture Adder post-process
  48373. */
  48374. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48375. var _this = this;
  48376. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48377. this._textureAdderPostProcess.onApply = function (effect) {
  48378. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48379. };
  48380. };
  48381. /**
  48382. * Down sample X4 post-process
  48383. */
  48384. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48385. var _this = this;
  48386. var downSampleX4Offsets = new Array(32);
  48387. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48388. this._downSampleX4PostProcess.onApply = function (effect) {
  48389. if (_this._needUpdate) {
  48390. var id = 0;
  48391. for (var i = -2; i < 2; i++) {
  48392. for (var j = -2; j < 2; j++) {
  48393. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48394. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48395. id += 2;
  48396. }
  48397. }
  48398. }
  48399. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48400. };
  48401. };
  48402. /**
  48403. * Bright pass post-process
  48404. */
  48405. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48406. var _this = this;
  48407. var brightOffsets = new Array(8);
  48408. var brightPassCallback = function (effect) {
  48409. if (_this._needUpdate) {
  48410. var sU = (1.0 / _this._brightPassPostProcess.width);
  48411. var sV = (1.0 / _this._brightPassPostProcess.height);
  48412. brightOffsets[0] = -0.5 * sU;
  48413. brightOffsets[1] = 0.5 * sV;
  48414. brightOffsets[2] = 0.5 * sU;
  48415. brightOffsets[3] = 0.5 * sV;
  48416. brightOffsets[4] = -0.5 * sU;
  48417. brightOffsets[5] = -0.5 * sV;
  48418. brightOffsets[6] = 0.5 * sU;
  48419. brightOffsets[7] = -0.5 * sV;
  48420. }
  48421. effect.setArray2("dsOffsets", brightOffsets);
  48422. effect.setFloat("brightThreshold", _this.brightThreshold);
  48423. };
  48424. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48425. this._brightPassPostProcess.onApply = brightPassCallback;
  48426. };
  48427. /**
  48428. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48429. */
  48430. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48431. var _this = this;
  48432. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48433. var luminanceOffsets = new Array(8);
  48434. var downSampleOffsets = new Array(18);
  48435. var halfDestPixelSize;
  48436. this._downSamplePostProcesses = new Array(lumSteps);
  48437. // Utils for luminance
  48438. var luminanceUpdateSourceOffsets = function (width, height) {
  48439. var sU = (1.0 / width);
  48440. var sV = (1.0 / height);
  48441. luminanceOffsets[0] = -0.5 * sU;
  48442. luminanceOffsets[1] = 0.5 * sV;
  48443. luminanceOffsets[2] = 0.5 * sU;
  48444. luminanceOffsets[3] = 0.5 * sV;
  48445. luminanceOffsets[4] = -0.5 * sU;
  48446. luminanceOffsets[5] = -0.5 * sV;
  48447. luminanceOffsets[6] = 0.5 * sU;
  48448. luminanceOffsets[7] = -0.5 * sV;
  48449. };
  48450. var luminanceUpdateDestOffsets = function (width, height) {
  48451. var id = 0;
  48452. for (var x = -1; x < 2; x++) {
  48453. for (var y = -1; y < 2; y++) {
  48454. downSampleOffsets[id] = (x) / width;
  48455. downSampleOffsets[id + 1] = (y) / height;
  48456. id += 2;
  48457. }
  48458. }
  48459. };
  48460. // Luminance callback
  48461. var luminanceCallback = function (effect) {
  48462. if (_this._needUpdate) {
  48463. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48464. }
  48465. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48466. effect.setArray2("lumOffsets", luminanceOffsets);
  48467. };
  48468. // Down sample callbacks
  48469. var downSampleCallback = function (indice) {
  48470. var i = indice;
  48471. return function (effect) {
  48472. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48473. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48474. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48475. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48476. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48477. effect.setArray2("dsOffsets", downSampleOffsets);
  48478. };
  48479. };
  48480. var downSampleAfterRenderCallback = function (effect) {
  48481. // Unpack result
  48482. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48483. 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);
  48484. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48485. };
  48486. // Create luminance post-process
  48487. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48488. 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);
  48489. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48490. // Create down sample post-processes
  48491. for (var i = lumSteps - 2; i >= 0; i--) {
  48492. var length = Math.pow(3, i);
  48493. ratio = { width: length, height: length };
  48494. var defines = "#define DOWN_SAMPLE\n";
  48495. if (i === 0) {
  48496. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48497. }
  48498. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48499. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48500. if (i === 0) {
  48501. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48502. }
  48503. }
  48504. };
  48505. /**
  48506. * Gaussian blur post-processes. Horizontal and Vertical
  48507. */
  48508. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48509. var _this = this;
  48510. var blurOffsetsW = new Array(9);
  48511. var blurOffsetsH = new Array(9);
  48512. var blurWeights = new Array(9);
  48513. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48514. // Utils for gaussian blur
  48515. var calculateBlurOffsets = function (height) {
  48516. var lastOutputDimensions = {
  48517. width: scene.getEngine().getRenderWidth(),
  48518. height: scene.getEngine().getRenderHeight()
  48519. };
  48520. for (var i = 0; i < 9; i++) {
  48521. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48522. if (height) {
  48523. blurOffsetsH[i] = value;
  48524. }
  48525. else {
  48526. blurOffsetsW[i] = value;
  48527. }
  48528. }
  48529. };
  48530. var calculateWeights = function () {
  48531. var x = 0.0;
  48532. for (var i = 0; i < 9; i++) {
  48533. x = (i - 4.0) / 4.0;
  48534. 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));
  48535. }
  48536. };
  48537. // Callback
  48538. var gaussianBlurCallback = function (height) {
  48539. return function (effect) {
  48540. if (_this._needUpdate) {
  48541. calculateWeights();
  48542. calculateBlurOffsets(height);
  48543. }
  48544. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48545. effect.setArray("blurWeights", blurWeights);
  48546. effect.setFloat("multiplier", _this.gaussMultiplier);
  48547. };
  48548. };
  48549. // Create horizontal gaussian blur post-processes
  48550. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48551. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48552. // Create vertical gaussian blur post-process
  48553. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48554. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48555. };
  48556. return HDRRenderingPipeline;
  48557. }(BABYLON.PostProcessRenderPipeline));
  48558. // Luminance generator
  48559. HDRRenderingPipeline.LUM_STEPS = 6;
  48560. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48561. })(BABYLON || (BABYLON = {}));
  48562. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48563. var BABYLON;
  48564. (function (BABYLON) {
  48565. var FaceAdjacencies = (function () {
  48566. function FaceAdjacencies() {
  48567. this.edges = new Array();
  48568. this.edgesConnectedCount = 0;
  48569. }
  48570. return FaceAdjacencies;
  48571. }());
  48572. var EdgesRenderer = (function () {
  48573. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48574. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48575. if (epsilon === void 0) { epsilon = 0.95; }
  48576. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48577. this.edgesWidthScalerForOrthographic = 1000.0;
  48578. this.edgesWidthScalerForPerspective = 50.0;
  48579. this._linesPositions = new Array();
  48580. this._linesNormals = new Array();
  48581. this._linesIndices = new Array();
  48582. this._buffers = {};
  48583. this._checkVerticesInsteadOfIndices = false;
  48584. this._source = source;
  48585. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48586. this._epsilon = epsilon;
  48587. this._prepareRessources();
  48588. this._generateEdgesLines();
  48589. }
  48590. EdgesRenderer.prototype._prepareRessources = function () {
  48591. if (this._lineShader) {
  48592. return;
  48593. }
  48594. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48595. attributes: ["position", "normal"],
  48596. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48597. });
  48598. this._lineShader.disableDepthWrite = true;
  48599. this._lineShader.backFaceCulling = false;
  48600. };
  48601. EdgesRenderer.prototype.dispose = function () {
  48602. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48603. if (buffer) {
  48604. buffer.dispose();
  48605. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48606. }
  48607. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48608. if (buffer) {
  48609. buffer.dispose();
  48610. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48611. }
  48612. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48613. this._lineShader.dispose();
  48614. };
  48615. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48616. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48617. return 0;
  48618. }
  48619. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48620. return 1;
  48621. }
  48622. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48623. return 2;
  48624. }
  48625. return -1;
  48626. };
  48627. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48628. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48629. return 0;
  48630. }
  48631. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48632. return 1;
  48633. }
  48634. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48635. return 2;
  48636. }
  48637. return -1;
  48638. };
  48639. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48640. var needToCreateLine;
  48641. if (edge === undefined) {
  48642. needToCreateLine = true;
  48643. }
  48644. else {
  48645. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48646. needToCreateLine = dotProduct < this._epsilon;
  48647. }
  48648. if (needToCreateLine) {
  48649. var offset = this._linesPositions.length / 3;
  48650. var normal = p0.subtract(p1);
  48651. normal.normalize();
  48652. // Positions
  48653. this._linesPositions.push(p0.x);
  48654. this._linesPositions.push(p0.y);
  48655. this._linesPositions.push(p0.z);
  48656. this._linesPositions.push(p0.x);
  48657. this._linesPositions.push(p0.y);
  48658. this._linesPositions.push(p0.z);
  48659. this._linesPositions.push(p1.x);
  48660. this._linesPositions.push(p1.y);
  48661. this._linesPositions.push(p1.z);
  48662. this._linesPositions.push(p1.x);
  48663. this._linesPositions.push(p1.y);
  48664. this._linesPositions.push(p1.z);
  48665. // Normals
  48666. this._linesNormals.push(p1.x);
  48667. this._linesNormals.push(p1.y);
  48668. this._linesNormals.push(p1.z);
  48669. this._linesNormals.push(-1);
  48670. this._linesNormals.push(p1.x);
  48671. this._linesNormals.push(p1.y);
  48672. this._linesNormals.push(p1.z);
  48673. this._linesNormals.push(1);
  48674. this._linesNormals.push(p0.x);
  48675. this._linesNormals.push(p0.y);
  48676. this._linesNormals.push(p0.z);
  48677. this._linesNormals.push(-1);
  48678. this._linesNormals.push(p0.x);
  48679. this._linesNormals.push(p0.y);
  48680. this._linesNormals.push(p0.z);
  48681. this._linesNormals.push(1);
  48682. // Indices
  48683. this._linesIndices.push(offset);
  48684. this._linesIndices.push(offset + 1);
  48685. this._linesIndices.push(offset + 2);
  48686. this._linesIndices.push(offset);
  48687. this._linesIndices.push(offset + 2);
  48688. this._linesIndices.push(offset + 3);
  48689. }
  48690. };
  48691. EdgesRenderer.prototype._generateEdgesLines = function () {
  48692. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48693. var indices = this._source.getIndices();
  48694. // First let's find adjacencies
  48695. var adjacencies = new Array();
  48696. var faceNormals = new Array();
  48697. var index;
  48698. var faceAdjacencies;
  48699. // Prepare faces
  48700. for (index = 0; index < indices.length; index += 3) {
  48701. faceAdjacencies = new FaceAdjacencies();
  48702. var p0Index = indices[index];
  48703. var p1Index = indices[index + 1];
  48704. var p2Index = indices[index + 2];
  48705. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48706. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48707. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48708. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48709. faceNormal.normalize();
  48710. faceNormals.push(faceNormal);
  48711. adjacencies.push(faceAdjacencies);
  48712. }
  48713. // Scan
  48714. for (index = 0; index < adjacencies.length; index++) {
  48715. faceAdjacencies = adjacencies[index];
  48716. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48717. var otherFaceAdjacencies = adjacencies[otherIndex];
  48718. if (faceAdjacencies.edgesConnectedCount === 3) {
  48719. break;
  48720. }
  48721. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48722. continue;
  48723. }
  48724. var otherP0 = indices[otherIndex * 3];
  48725. var otherP1 = indices[otherIndex * 3 + 1];
  48726. var otherP2 = indices[otherIndex * 3 + 2];
  48727. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48728. var otherEdgeIndex;
  48729. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48730. continue;
  48731. }
  48732. switch (edgeIndex) {
  48733. case 0:
  48734. if (this._checkVerticesInsteadOfIndices) {
  48735. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48736. }
  48737. else {
  48738. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48739. }
  48740. break;
  48741. case 1:
  48742. if (this._checkVerticesInsteadOfIndices) {
  48743. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48744. }
  48745. else {
  48746. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48747. }
  48748. break;
  48749. case 2:
  48750. if (this._checkVerticesInsteadOfIndices) {
  48751. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48752. }
  48753. else {
  48754. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48755. }
  48756. break;
  48757. }
  48758. if (otherEdgeIndex === -1) {
  48759. continue;
  48760. }
  48761. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48762. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48763. faceAdjacencies.edgesConnectedCount++;
  48764. otherFaceAdjacencies.edgesConnectedCount++;
  48765. if (faceAdjacencies.edgesConnectedCount === 3) {
  48766. break;
  48767. }
  48768. }
  48769. }
  48770. }
  48771. // Create lines
  48772. for (index = 0; index < adjacencies.length; index++) {
  48773. // 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
  48774. var current = adjacencies[index];
  48775. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48776. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48777. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48778. }
  48779. // Merge into a single mesh
  48780. var engine = this._source.getScene().getEngine();
  48781. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48782. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48783. this._ib = engine.createIndexBuffer(this._linesIndices);
  48784. this._indicesCount = this._linesIndices.length;
  48785. };
  48786. EdgesRenderer.prototype.render = function () {
  48787. if (!this._lineShader.isReady()) {
  48788. return;
  48789. }
  48790. var scene = this._source.getScene();
  48791. var engine = scene.getEngine();
  48792. this._lineShader._preBind();
  48793. // VBOs
  48794. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48795. scene.resetCachedMaterial();
  48796. this._lineShader.setColor4("color", this._source.edgesColor);
  48797. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48798. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48799. }
  48800. else {
  48801. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48802. }
  48803. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48804. this._lineShader.bind(this._source.getWorldMatrix());
  48805. // Draw order
  48806. engine.draw(true, 0, this._indicesCount);
  48807. this._lineShader.unbind();
  48808. engine.setDepthWrite(true);
  48809. };
  48810. return EdgesRenderer;
  48811. }());
  48812. BABYLON.EdgesRenderer = EdgesRenderer;
  48813. })(BABYLON || (BABYLON = {}));
  48814. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48815. var BABYLON;
  48816. (function (BABYLON) {
  48817. var TonemappingOperator;
  48818. (function (TonemappingOperator) {
  48819. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48820. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48821. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48822. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48823. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48824. ;
  48825. var TonemapPostProcess = (function (_super) {
  48826. __extends(TonemapPostProcess, _super);
  48827. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48829. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48830. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48831. _this._operator = _operator;
  48832. _this.exposureAdjustment = exposureAdjustment;
  48833. var defines = "#define ";
  48834. if (_this._operator === TonemappingOperator.Hable)
  48835. defines += "HABLE_TONEMAPPING";
  48836. else if (_this._operator === TonemappingOperator.Reinhard)
  48837. defines += "REINHARD_TONEMAPPING";
  48838. else if (_this._operator === TonemappingOperator.HejiDawson)
  48839. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48840. else if (_this._operator === TonemappingOperator.Photographic)
  48841. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48842. //sadly a second call to create the effect.
  48843. _this.updateEffect(defines);
  48844. _this.onApply = function (effect) {
  48845. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48846. };
  48847. return _this;
  48848. }
  48849. return TonemapPostProcess;
  48850. }(BABYLON.PostProcess));
  48851. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48852. })(BABYLON || (BABYLON = {}));
  48853. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48854. var BABYLON;
  48855. (function (BABYLON) {
  48856. var ReflectionProbe = (function () {
  48857. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48859. var _this = this;
  48860. this.name = name;
  48861. this._viewMatrix = BABYLON.Matrix.Identity();
  48862. this._target = BABYLON.Vector3.Zero();
  48863. this._add = BABYLON.Vector3.Zero();
  48864. this.invertYAxis = false;
  48865. this.position = BABYLON.Vector3.Zero();
  48866. this._scene = scene;
  48867. this._scene.reflectionProbes.push(this);
  48868. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48869. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48870. switch (faceIndex) {
  48871. case 0:
  48872. _this._add.copyFromFloats(1, 0, 0);
  48873. break;
  48874. case 1:
  48875. _this._add.copyFromFloats(-1, 0, 0);
  48876. break;
  48877. case 2:
  48878. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48879. break;
  48880. case 3:
  48881. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48882. break;
  48883. case 4:
  48884. _this._add.copyFromFloats(0, 0, 1);
  48885. break;
  48886. case 5:
  48887. _this._add.copyFromFloats(0, 0, -1);
  48888. break;
  48889. }
  48890. if (_this._attachedMesh) {
  48891. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48892. }
  48893. _this.position.addToRef(_this._add, _this._target);
  48894. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48895. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48896. });
  48897. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48898. scene.updateTransformMatrix(true);
  48899. });
  48900. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48901. }
  48902. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48903. get: function () {
  48904. return this._renderTargetTexture.refreshRate;
  48905. },
  48906. set: function (value) {
  48907. this._renderTargetTexture.refreshRate = value;
  48908. },
  48909. enumerable: true,
  48910. configurable: true
  48911. });
  48912. ReflectionProbe.prototype.getScene = function () {
  48913. return this._scene;
  48914. };
  48915. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48916. get: function () {
  48917. return this._renderTargetTexture;
  48918. },
  48919. enumerable: true,
  48920. configurable: true
  48921. });
  48922. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48923. get: function () {
  48924. return this._renderTargetTexture.renderList;
  48925. },
  48926. enumerable: true,
  48927. configurable: true
  48928. });
  48929. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48930. this._attachedMesh = mesh;
  48931. };
  48932. ReflectionProbe.prototype.dispose = function () {
  48933. var index = this._scene.reflectionProbes.indexOf(this);
  48934. if (index !== -1) {
  48935. // Remove from the scene if found
  48936. this._scene.reflectionProbes.splice(index, 1);
  48937. }
  48938. if (this._renderTargetTexture) {
  48939. this._renderTargetTexture.dispose();
  48940. this._renderTargetTexture = null;
  48941. }
  48942. };
  48943. return ReflectionProbe;
  48944. }());
  48945. BABYLON.ReflectionProbe = ReflectionProbe;
  48946. })(BABYLON || (BABYLON = {}));
  48947. //# sourceMappingURL=babylon.reflectionProbe.js.map
  48948. var BABYLON;
  48949. (function (BABYLON) {
  48950. var SolidParticle = (function () {
  48951. /**
  48952. * Creates a Solid Particle object.
  48953. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48954. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48955. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48956. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48957. * `shapeId` (integer) is the model shape identifier in the SPS.
  48958. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48959. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48960. */
  48961. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48962. this.idx = 0; // particle global index
  48963. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48964. this.position = BABYLON.Vector3.Zero(); // position
  48965. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48966. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48967. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48968. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48969. this.alive = true; // alive
  48970. this.isVisible = true; // visibility
  48971. this._pos = 0; // index of this particle in the global "positions" array
  48972. this.shapeId = 0; // model shape id
  48973. this.idxInShape = 0; // index of the particle in its shape id
  48974. this.idx = particleIndex;
  48975. this._pos = positionIndex;
  48976. this._model = model;
  48977. this.shapeId = shapeId;
  48978. this.idxInShape = idxInShape;
  48979. this._sps = sps;
  48980. if (modelBoundingInfo) {
  48981. this._modelBoundingInfo = modelBoundingInfo;
  48982. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48983. }
  48984. }
  48985. Object.defineProperty(SolidParticle.prototype, "scale", {
  48986. /**
  48987. * legacy support, changed scale to scaling
  48988. */
  48989. get: function () {
  48990. return this.scaling;
  48991. },
  48992. set: function (scale) {
  48993. this.scaling = scale;
  48994. },
  48995. enumerable: true,
  48996. configurable: true
  48997. });
  48998. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48999. /**
  49000. * legacy support, changed quaternion to rotationQuaternion
  49001. */
  49002. get: function () {
  49003. return this.rotationQuaternion;
  49004. },
  49005. set: function (q) {
  49006. this.rotationQuaternion = q;
  49007. },
  49008. enumerable: true,
  49009. configurable: true
  49010. });
  49011. /**
  49012. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49013. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49014. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49015. */
  49016. SolidParticle.prototype.intersectsMesh = function (target) {
  49017. if (!this._boundingInfo || !target._boundingInfo) {
  49018. return false;
  49019. }
  49020. if (this._sps._bSphereOnly) {
  49021. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49022. }
  49023. return this._boundingInfo.intersects(target._boundingInfo, false);
  49024. };
  49025. return SolidParticle;
  49026. }());
  49027. BABYLON.SolidParticle = SolidParticle;
  49028. var ModelShape = (function () {
  49029. /**
  49030. * 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.
  49031. * SPS internal tool, don't use it manually.
  49032. */
  49033. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49034. this.shapeID = id;
  49035. this._shape = shape;
  49036. this._shapeUV = shapeUV;
  49037. this._positionFunction = posFunction;
  49038. this._vertexFunction = vtxFunction;
  49039. }
  49040. return ModelShape;
  49041. }());
  49042. BABYLON.ModelShape = ModelShape;
  49043. })(BABYLON || (BABYLON = {}));
  49044. //# sourceMappingURL=babylon.solidParticle.js.map
  49045. var BABYLON;
  49046. (function (BABYLON) {
  49047. /**
  49048. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49049. */
  49050. var SolidParticleSystem = (function () {
  49051. /**
  49052. * Creates a SPS (Solid Particle System) object.
  49053. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49054. * `scene` (Scene) is the scene in which the SPS is added.
  49055. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49056. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49057. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49058. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49059. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49060. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49061. */
  49062. function SolidParticleSystem(name, scene, options) {
  49063. // public members
  49064. /**
  49065. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49066. * Example : var p = SPS.particles[i];
  49067. */
  49068. this.particles = new Array();
  49069. /**
  49070. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49071. */
  49072. this.nbParticles = 0;
  49073. /**
  49074. * If the particles must ever face the camera (default false). Useful for planar particles.
  49075. */
  49076. this.billboard = false;
  49077. /**
  49078. * Recompute normals when adding a shape
  49079. */
  49080. this.recomputeNormals = true;
  49081. /**
  49082. * This a counter ofr your own usage. It's not set by any SPS functions.
  49083. */
  49084. this.counter = 0;
  49085. /**
  49086. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49087. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49088. */
  49089. this.vars = {};
  49090. this._positions = new Array();
  49091. this._indices = new Array();
  49092. this._normals = new Array();
  49093. this._colors = new Array();
  49094. this._uvs = new Array();
  49095. this._index = 0; // indices index
  49096. this._updatable = true;
  49097. this._pickable = false;
  49098. this._isVisibilityBoxLocked = false;
  49099. this._alwaysVisible = false;
  49100. this._shapeCounter = 0;
  49101. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49102. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49103. this._computeParticleColor = true;
  49104. this._computeParticleTexture = true;
  49105. this._computeParticleRotation = true;
  49106. this._computeParticleVertex = false;
  49107. this._computeBoundingBox = false;
  49108. this._cam_axisZ = BABYLON.Vector3.Zero();
  49109. this._cam_axisY = BABYLON.Vector3.Zero();
  49110. this._cam_axisX = BABYLON.Vector3.Zero();
  49111. this._axisX = BABYLON.Axis.X;
  49112. this._axisY = BABYLON.Axis.Y;
  49113. this._axisZ = BABYLON.Axis.Z;
  49114. this._camDir = BABYLON.Vector3.Zero();
  49115. this._rotMatrix = new BABYLON.Matrix();
  49116. this._invertMatrix = new BABYLON.Matrix();
  49117. this._rotated = BABYLON.Vector3.Zero();
  49118. this._quaternion = new BABYLON.Quaternion();
  49119. this._vertex = BABYLON.Vector3.Zero();
  49120. this._normal = BABYLON.Vector3.Zero();
  49121. this._yaw = 0.0;
  49122. this._pitch = 0.0;
  49123. this._roll = 0.0;
  49124. this._halfroll = 0.0;
  49125. this._halfpitch = 0.0;
  49126. this._halfyaw = 0.0;
  49127. this._sinRoll = 0.0;
  49128. this._cosRoll = 0.0;
  49129. this._sinPitch = 0.0;
  49130. this._cosPitch = 0.0;
  49131. this._sinYaw = 0.0;
  49132. this._cosYaw = 0.0;
  49133. this._w = 0.0;
  49134. this._minimum = BABYLON.Tmp.Vector3[0];
  49135. this._maximum = BABYLON.Tmp.Vector3[1];
  49136. this._scale = BABYLON.Tmp.Vector3[2];
  49137. this._translation = BABYLON.Tmp.Vector3[3];
  49138. this._minBbox = BABYLON.Tmp.Vector3[4];
  49139. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49140. this._particlesIntersect = false;
  49141. this._bSphereOnly = false;
  49142. this._bSphereRadiusFactor = 1.0;
  49143. this.name = name;
  49144. this._scene = scene;
  49145. this._camera = scene.activeCamera;
  49146. this._pickable = options ? options.isPickable : false;
  49147. this._particlesIntersect = options ? options.particleIntersection : false;
  49148. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49149. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49150. if (options && options.updatable) {
  49151. this._updatable = options.updatable;
  49152. }
  49153. else {
  49154. this._updatable = true;
  49155. }
  49156. if (this._pickable) {
  49157. this.pickedParticles = [];
  49158. }
  49159. }
  49160. /**
  49161. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49162. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49163. */
  49164. SolidParticleSystem.prototype.buildMesh = function () {
  49165. if (this.nbParticles === 0) {
  49166. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49167. this.addShape(triangle, 1);
  49168. triangle.dispose();
  49169. }
  49170. this._positions32 = new Float32Array(this._positions);
  49171. this._uvs32 = new Float32Array(this._uvs);
  49172. this._colors32 = new Float32Array(this._colors);
  49173. if (this.recomputeNormals) {
  49174. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49175. }
  49176. this._normals32 = new Float32Array(this._normals);
  49177. this._fixedNormal32 = new Float32Array(this._normals);
  49178. var vertexData = new BABYLON.VertexData();
  49179. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49180. vertexData.indices = this._indices;
  49181. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49182. if (this._uvs32) {
  49183. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49184. ;
  49185. }
  49186. if (this._colors32) {
  49187. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49188. }
  49189. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49190. vertexData.applyToMesh(mesh, this._updatable);
  49191. this.mesh = mesh;
  49192. this.mesh.isPickable = this._pickable;
  49193. // free memory
  49194. this._positions = null;
  49195. this._normals = null;
  49196. this._uvs = null;
  49197. this._colors = null;
  49198. if (!this._updatable) {
  49199. this.particles.length = 0;
  49200. }
  49201. return mesh;
  49202. };
  49203. /**
  49204. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49205. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49206. * Thus the particles generated from `digest()` have their property `position` set yet.
  49207. * `mesh` ( Mesh ) is the mesh to be digested
  49208. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49209. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49210. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49211. */
  49212. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49213. var size = (options && options.facetNb) || 1;
  49214. var number = (options && options.number);
  49215. var delta = (options && options.delta) || 0;
  49216. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49217. var meshInd = mesh.getIndices();
  49218. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49219. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49220. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49221. var f = 0; // facet counter
  49222. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49223. // compute size from number
  49224. if (number) {
  49225. number = (number > totalFacets) ? totalFacets : number;
  49226. size = Math.round(totalFacets / number);
  49227. delta = 0;
  49228. }
  49229. else {
  49230. size = (size > totalFacets) ? totalFacets : size;
  49231. }
  49232. var facetPos = []; // submesh positions
  49233. var facetInd = []; // submesh indices
  49234. var facetUV = []; // submesh UV
  49235. var facetCol = []; // submesh colors
  49236. var barycenter = BABYLON.Tmp.Vector3[0];
  49237. var rand;
  49238. var sizeO = size;
  49239. while (f < totalFacets) {
  49240. size = sizeO + Math.floor((1 + delta) * Math.random());
  49241. if (f > totalFacets - size) {
  49242. size = totalFacets - f;
  49243. }
  49244. // reset temp arrays
  49245. facetPos.length = 0;
  49246. facetInd.length = 0;
  49247. facetUV.length = 0;
  49248. facetCol.length = 0;
  49249. // iterate over "size" facets
  49250. var fi = 0;
  49251. for (var j = f * 3; j < (f + size) * 3; j++) {
  49252. facetInd.push(fi);
  49253. var i = meshInd[j];
  49254. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49255. if (meshUV) {
  49256. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49257. }
  49258. if (meshCol) {
  49259. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49260. }
  49261. fi++;
  49262. }
  49263. // create a model shape for each single particle
  49264. var idx = this.nbParticles;
  49265. var shape = this._posToShape(facetPos);
  49266. var shapeUV = this._uvsToShapeUV(facetUV);
  49267. // compute the barycenter of the shape
  49268. var v;
  49269. for (v = 0; v < shape.length; v++) {
  49270. barycenter.addInPlace(shape[v]);
  49271. }
  49272. barycenter.scaleInPlace(1 / shape.length);
  49273. // shift the shape from its barycenter to the origin
  49274. for (v = 0; v < shape.length; v++) {
  49275. shape[v].subtractInPlace(barycenter);
  49276. }
  49277. var bInfo;
  49278. if (this._particlesIntersect) {
  49279. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49280. }
  49281. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49282. // add the particle in the SPS
  49283. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49284. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49285. // initialize the particle position
  49286. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49287. this._index += shape.length;
  49288. idx++;
  49289. this.nbParticles++;
  49290. this._shapeCounter++;
  49291. f += size;
  49292. }
  49293. return this;
  49294. };
  49295. //reset copy
  49296. SolidParticleSystem.prototype._resetCopy = function () {
  49297. this._copy.position.x = 0;
  49298. this._copy.position.y = 0;
  49299. this._copy.position.z = 0;
  49300. this._copy.rotation.x = 0;
  49301. this._copy.rotation.y = 0;
  49302. this._copy.rotation.z = 0;
  49303. this._copy.rotationQuaternion = null;
  49304. this._copy.scaling.x = 1;
  49305. this._copy.scaling.y = 1;
  49306. this._copy.scaling.z = 1;
  49307. this._copy.uvs.x = 0;
  49308. this._copy.uvs.y = 0;
  49309. this._copy.uvs.z = 1;
  49310. this._copy.uvs.w = 1;
  49311. this._copy.color = null;
  49312. };
  49313. // _meshBuilder : inserts the shape model in the global SPS mesh
  49314. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49315. var i;
  49316. var u = 0;
  49317. var c = 0;
  49318. var n = 0;
  49319. this._resetCopy();
  49320. if (options && options.positionFunction) {
  49321. options.positionFunction(this._copy, idx, idxInShape);
  49322. }
  49323. if (this._copy.rotationQuaternion) {
  49324. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49325. }
  49326. else {
  49327. this._yaw = this._copy.rotation.y;
  49328. this._pitch = this._copy.rotation.x;
  49329. this._roll = this._copy.rotation.z;
  49330. this._quaternionRotationYPR();
  49331. }
  49332. this._quaternionToRotationMatrix();
  49333. for (i = 0; i < shape.length; i++) {
  49334. this._vertex.x = shape[i].x;
  49335. this._vertex.y = shape[i].y;
  49336. this._vertex.z = shape[i].z;
  49337. if (options && options.vertexFunction) {
  49338. options.vertexFunction(this._copy, this._vertex, i);
  49339. }
  49340. this._vertex.x *= this._copy.scaling.x;
  49341. this._vertex.y *= this._copy.scaling.y;
  49342. this._vertex.z *= this._copy.scaling.z;
  49343. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49344. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49345. if (meshUV) {
  49346. 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);
  49347. u += 2;
  49348. }
  49349. if (this._copy.color) {
  49350. this._color = this._copy.color;
  49351. }
  49352. else if (meshCol && meshCol[c] !== undefined) {
  49353. this._color.r = meshCol[c];
  49354. this._color.g = meshCol[c + 1];
  49355. this._color.b = meshCol[c + 2];
  49356. this._color.a = meshCol[c + 3];
  49357. }
  49358. else {
  49359. this._color.r = 1;
  49360. this._color.g = 1;
  49361. this._color.b = 1;
  49362. this._color.a = 1;
  49363. }
  49364. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49365. c += 4;
  49366. if (!this.recomputeNormals && meshNor) {
  49367. this._normal.x = meshNor[n];
  49368. this._normal.y = meshNor[n + 1];
  49369. this._normal.z = meshNor[n + 2];
  49370. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49371. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49372. n += 3;
  49373. }
  49374. }
  49375. for (i = 0; i < meshInd.length; i++) {
  49376. indices.push(p + meshInd[i]);
  49377. }
  49378. if (this._pickable) {
  49379. var nbfaces = meshInd.length / 3;
  49380. for (i = 0; i < nbfaces; i++) {
  49381. this.pickedParticles.push({ idx: idx, faceId: i });
  49382. }
  49383. }
  49384. };
  49385. // returns a shape array from positions array
  49386. SolidParticleSystem.prototype._posToShape = function (positions) {
  49387. var shape = [];
  49388. for (var i = 0; i < positions.length; i += 3) {
  49389. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49390. }
  49391. return shape;
  49392. };
  49393. // returns a shapeUV array from a Vector4 uvs
  49394. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49395. var shapeUV = [];
  49396. if (uvs) {
  49397. for (var i = 0; i < uvs.length; i++)
  49398. shapeUV.push(uvs[i]);
  49399. }
  49400. return shapeUV;
  49401. };
  49402. // adds a new particle object in the particles array
  49403. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49404. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49405. };
  49406. /**
  49407. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49408. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49409. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49410. * `nb` (positive integer) the number of particles to be created from this model
  49411. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49412. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49413. */
  49414. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49415. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49416. var meshInd = mesh.getIndices();
  49417. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49418. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49419. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49420. var bbInfo;
  49421. if (this._particlesIntersect) {
  49422. bbInfo = mesh.getBoundingInfo();
  49423. }
  49424. var shape = this._posToShape(meshPos);
  49425. var shapeUV = this._uvsToShapeUV(meshUV);
  49426. var posfunc = options ? options.positionFunction : null;
  49427. var vtxfunc = options ? options.vertexFunction : null;
  49428. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49429. // particles
  49430. var idx = this.nbParticles;
  49431. for (var i = 0; i < nb; i++) {
  49432. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49433. if (this._updatable) {
  49434. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49435. }
  49436. this._index += shape.length;
  49437. idx++;
  49438. }
  49439. this.nbParticles += nb;
  49440. this._shapeCounter++;
  49441. return this._shapeCounter - 1;
  49442. };
  49443. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49444. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49445. this._resetCopy();
  49446. if (particle._model._positionFunction) {
  49447. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49448. }
  49449. if (this._copy.rotationQuaternion) {
  49450. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49451. }
  49452. else {
  49453. this._yaw = this._copy.rotation.y;
  49454. this._pitch = this._copy.rotation.x;
  49455. this._roll = this._copy.rotation.z;
  49456. this._quaternionRotationYPR();
  49457. }
  49458. this._quaternionToRotationMatrix();
  49459. this._shape = particle._model._shape;
  49460. for (var pt = 0; pt < this._shape.length; pt++) {
  49461. this._vertex.x = this._shape[pt].x;
  49462. this._vertex.y = this._shape[pt].y;
  49463. this._vertex.z = this._shape[pt].z;
  49464. if (particle._model._vertexFunction) {
  49465. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49466. }
  49467. this._vertex.x *= this._copy.scaling.x;
  49468. this._vertex.y *= this._copy.scaling.y;
  49469. this._vertex.z *= this._copy.scaling.z;
  49470. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49471. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49472. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49473. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49474. }
  49475. particle.position.x = 0.0;
  49476. particle.position.y = 0.0;
  49477. particle.position.z = 0.0;
  49478. particle.rotation.x = 0.0;
  49479. particle.rotation.y = 0.0;
  49480. particle.rotation.z = 0.0;
  49481. particle.rotationQuaternion = null;
  49482. particle.scaling.x = 1.0;
  49483. particle.scaling.y = 1.0;
  49484. particle.scaling.z = 1.0;
  49485. };
  49486. /**
  49487. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49488. */
  49489. SolidParticleSystem.prototype.rebuildMesh = function () {
  49490. for (var p = 0; p < this.particles.length; p++) {
  49491. this._rebuildParticle(this.particles[p]);
  49492. }
  49493. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49494. };
  49495. /**
  49496. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49497. * This method calls `updateParticle()` for each particle of the SPS.
  49498. * For an animated SPS, it is usually called within the render loop.
  49499. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49500. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49501. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49502. */
  49503. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49504. if (start === void 0) { start = 0; }
  49505. if (end === void 0) { end = this.nbParticles - 1; }
  49506. if (update === void 0) { update = true; }
  49507. if (!this._updatable) {
  49508. return;
  49509. }
  49510. // custom beforeUpdate
  49511. this.beforeUpdateParticles(start, end, update);
  49512. this._cam_axisX.x = 1.0;
  49513. this._cam_axisX.y = 0.0;
  49514. this._cam_axisX.z = 0.0;
  49515. this._cam_axisY.x = 0.0;
  49516. this._cam_axisY.y = 1.0;
  49517. this._cam_axisY.z = 0.0;
  49518. this._cam_axisZ.x = 0.0;
  49519. this._cam_axisZ.y = 0.0;
  49520. this._cam_axisZ.z = 1.0;
  49521. // if the particles will always face the camera
  49522. if (this.billboard) {
  49523. // compute the camera position and un-rotate it by the current mesh rotation
  49524. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49525. this._quaternionToRotationMatrix();
  49526. this._rotMatrix.invertToRef(this._invertMatrix);
  49527. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49528. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49529. this._cam_axisZ.normalize();
  49530. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49531. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49532. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49533. this._cam_axisY.normalize();
  49534. this._cam_axisX.normalize();
  49535. }
  49536. }
  49537. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49538. var idx = 0;
  49539. var index = 0;
  49540. var colidx = 0;
  49541. var colorIndex = 0;
  49542. var uvidx = 0;
  49543. var uvIndex = 0;
  49544. var pt = 0;
  49545. if (this._computeBoundingBox) {
  49546. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49547. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49548. }
  49549. // particle loop
  49550. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49551. for (var p = start; p <= end; p++) {
  49552. this._particle = this.particles[p];
  49553. this._shape = this._particle._model._shape;
  49554. this._shapeUV = this._particle._model._shapeUV;
  49555. // call to custom user function to update the particle properties
  49556. this.updateParticle(this._particle);
  49557. if (this._particle.isVisible) {
  49558. // particle rotation matrix
  49559. if (this.billboard) {
  49560. this._particle.rotation.x = 0.0;
  49561. this._particle.rotation.y = 0.0;
  49562. }
  49563. if (this._computeParticleRotation || this.billboard) {
  49564. if (this._particle.rotationQuaternion) {
  49565. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49566. }
  49567. else {
  49568. this._yaw = this._particle.rotation.y;
  49569. this._pitch = this._particle.rotation.x;
  49570. this._roll = this._particle.rotation.z;
  49571. this._quaternionRotationYPR();
  49572. }
  49573. this._quaternionToRotationMatrix();
  49574. }
  49575. // particle vertex loop
  49576. for (pt = 0; pt < this._shape.length; pt++) {
  49577. idx = index + pt * 3;
  49578. colidx = colorIndex + pt * 4;
  49579. uvidx = uvIndex + pt * 2;
  49580. this._vertex.x = this._shape[pt].x;
  49581. this._vertex.y = this._shape[pt].y;
  49582. this._vertex.z = this._shape[pt].z;
  49583. if (this._computeParticleVertex) {
  49584. this.updateParticleVertex(this._particle, this._vertex, pt);
  49585. }
  49586. // positions
  49587. this._vertex.x *= this._particle.scaling.x;
  49588. this._vertex.y *= this._particle.scaling.y;
  49589. this._vertex.z *= this._particle.scaling.z;
  49590. 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];
  49591. 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;
  49592. 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;
  49593. 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;
  49594. 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;
  49595. 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;
  49596. 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;
  49597. if (this._computeBoundingBox) {
  49598. if (this._positions32[idx] < this._minimum.x) {
  49599. this._minimum.x = this._positions32[idx];
  49600. }
  49601. if (this._positions32[idx] > this._maximum.x) {
  49602. this._maximum.x = this._positions32[idx];
  49603. }
  49604. if (this._positions32[idx + 1] < this._minimum.y) {
  49605. this._minimum.y = this._positions32[idx + 1];
  49606. }
  49607. if (this._positions32[idx + 1] > this._maximum.y) {
  49608. this._maximum.y = this._positions32[idx + 1];
  49609. }
  49610. if (this._positions32[idx + 2] < this._minimum.z) {
  49611. this._minimum.z = this._positions32[idx + 2];
  49612. }
  49613. if (this._positions32[idx + 2] > this._maximum.z) {
  49614. this._maximum.z = this._positions32[idx + 2];
  49615. }
  49616. }
  49617. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49618. if (!this._computeParticleVertex) {
  49619. this._normal.x = this._fixedNormal32[idx];
  49620. this._normal.y = this._fixedNormal32[idx + 1];
  49621. this._normal.z = this._fixedNormal32[idx + 2];
  49622. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  49623. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  49624. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  49625. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  49626. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49627. 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;
  49628. 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;
  49629. }
  49630. if (this._computeParticleColor) {
  49631. this._colors32[colidx] = this._particle.color.r;
  49632. this._colors32[colidx + 1] = this._particle.color.g;
  49633. this._colors32[colidx + 2] = this._particle.color.b;
  49634. this._colors32[colidx + 3] = this._particle.color.a;
  49635. }
  49636. if (this._computeParticleTexture) {
  49637. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49638. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49639. }
  49640. }
  49641. }
  49642. else {
  49643. for (pt = 0; pt < this._shape.length; pt++) {
  49644. idx = index + pt * 3;
  49645. colidx = colorIndex + pt * 4;
  49646. uvidx = uvIndex + pt * 2;
  49647. this._positions32[idx] = this._camera.position.x;
  49648. this._positions32[idx + 1] = this._camera.position.y;
  49649. this._positions32[idx + 2] = this._camera.position.z;
  49650. this._normals32[idx] = 0.0;
  49651. this._normals32[idx + 1] = 0.0;
  49652. this._normals32[idx + 2] = 0.0;
  49653. if (this._computeParticleColor) {
  49654. this._colors32[colidx] = this._particle.color.r;
  49655. this._colors32[colidx + 1] = this._particle.color.g;
  49656. this._colors32[colidx + 2] = this._particle.color.b;
  49657. this._colors32[colidx + 3] = this._particle.color.a;
  49658. }
  49659. if (this._computeParticleTexture) {
  49660. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49661. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49662. }
  49663. }
  49664. }
  49665. // if the particle intersections must be computed : update the bbInfo
  49666. if (this._particlesIntersect) {
  49667. var bInfo = this._particle._boundingInfo;
  49668. var bBox = bInfo.boundingBox;
  49669. var bSphere = bInfo.boundingSphere;
  49670. if (!this._bSphereOnly) {
  49671. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49672. for (var b = 0; b < bBox.vectors.length; b++) {
  49673. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49674. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49675. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49676. 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];
  49677. 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;
  49678. 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;
  49679. 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;
  49680. 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;
  49681. 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;
  49682. 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;
  49683. }
  49684. bBox._update(this.mesh._worldMatrix);
  49685. }
  49686. // place and scale the particle bouding sphere in the SPS local system, then update it
  49687. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49688. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49689. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49690. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49691. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49692. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49693. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49694. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49695. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49696. 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));
  49697. bSphere._update(this.mesh._worldMatrix);
  49698. }
  49699. // increment indexes for the next particle
  49700. index = idx + 3;
  49701. colorIndex = colidx + 4;
  49702. uvIndex = uvidx + 2;
  49703. }
  49704. // if the VBO must be updated
  49705. if (update) {
  49706. if (this._computeParticleColor) {
  49707. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49708. }
  49709. if (this._computeParticleTexture) {
  49710. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49711. }
  49712. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49713. if (!this.mesh.areNormalsFrozen) {
  49714. if (this._computeParticleVertex) {
  49715. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49716. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49717. for (var i = 0; i < this._normals32.length; i++) {
  49718. this._fixedNormal32[i] = this._normals32[i];
  49719. }
  49720. }
  49721. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49722. }
  49723. }
  49724. if (this._computeBoundingBox) {
  49725. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49726. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49727. }
  49728. this.afterUpdateParticles(start, end, update);
  49729. };
  49730. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49731. this._halfroll = this._roll * 0.5;
  49732. this._halfpitch = this._pitch * 0.5;
  49733. this._halfyaw = this._yaw * 0.5;
  49734. this._sinRoll = Math.sin(this._halfroll);
  49735. this._cosRoll = Math.cos(this._halfroll);
  49736. this._sinPitch = Math.sin(this._halfpitch);
  49737. this._cosPitch = Math.cos(this._halfpitch);
  49738. this._sinYaw = Math.sin(this._halfyaw);
  49739. this._cosYaw = Math.cos(this._halfyaw);
  49740. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49741. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49742. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49743. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49744. };
  49745. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49746. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49747. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49748. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49749. this._rotMatrix.m[3] = 0;
  49750. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49751. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49752. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49753. this._rotMatrix.m[7] = 0;
  49754. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49755. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49756. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49757. this._rotMatrix.m[11] = 0;
  49758. this._rotMatrix.m[12] = 0;
  49759. this._rotMatrix.m[13] = 0;
  49760. this._rotMatrix.m[14] = 0;
  49761. this._rotMatrix.m[15] = 1.0;
  49762. };
  49763. /**
  49764. * Disposes the SPS
  49765. */
  49766. SolidParticleSystem.prototype.dispose = function () {
  49767. this.mesh.dispose();
  49768. this.vars = null;
  49769. // drop references to internal big arrays for the GC
  49770. this._positions = null;
  49771. this._indices = null;
  49772. this._normals = null;
  49773. this._uvs = null;
  49774. this._colors = null;
  49775. this._positions32 = null;
  49776. this._normals32 = null;
  49777. this._fixedNormal32 = null;
  49778. this._uvs32 = null;
  49779. this._colors32 = null;
  49780. this.pickedParticles = null;
  49781. };
  49782. /**
  49783. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49784. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49785. */
  49786. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49787. if (!this._isVisibilityBoxLocked) {
  49788. this.mesh.refreshBoundingInfo();
  49789. }
  49790. };
  49791. /**
  49792. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49793. * @param size the size (float) of the visibility box
  49794. * note : this doesn't lock the SPS mesh bounding box.
  49795. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49796. */
  49797. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49798. var vis = size / 2;
  49799. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49800. };
  49801. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49802. // getter and setter
  49803. get: function () {
  49804. return this._alwaysVisible;
  49805. },
  49806. /**
  49807. * Sets the SPS as always visible or not
  49808. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49809. */
  49810. set: function (val) {
  49811. this._alwaysVisible = val;
  49812. this.mesh.alwaysSelectAsActiveMesh = val;
  49813. },
  49814. enumerable: true,
  49815. configurable: true
  49816. });
  49817. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49818. get: function () {
  49819. return this._isVisibilityBoxLocked;
  49820. },
  49821. /**
  49822. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49823. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49824. */
  49825. set: function (val) {
  49826. this._isVisibilityBoxLocked = val;
  49827. this.mesh.getBoundingInfo().isLocked = val;
  49828. },
  49829. enumerable: true,
  49830. configurable: true
  49831. });
  49832. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49833. // getters
  49834. get: function () {
  49835. return this._computeParticleRotation;
  49836. },
  49837. // Optimizer setters
  49838. /**
  49839. * Tells to `setParticles()` to compute the particle rotations or not.
  49840. * Default value : true. The SPS is faster when it's set to false.
  49841. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49842. */
  49843. set: function (val) {
  49844. this._computeParticleRotation = val;
  49845. },
  49846. enumerable: true,
  49847. configurable: true
  49848. });
  49849. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49850. get: function () {
  49851. return this._computeParticleColor;
  49852. },
  49853. /**
  49854. * Tells to `setParticles()` to compute the particle colors or not.
  49855. * Default value : true. The SPS is faster when it's set to false.
  49856. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49857. */
  49858. set: function (val) {
  49859. this._computeParticleColor = val;
  49860. },
  49861. enumerable: true,
  49862. configurable: true
  49863. });
  49864. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49865. get: function () {
  49866. return this._computeParticleTexture;
  49867. },
  49868. /**
  49869. * Tells to `setParticles()` to compute the particle textures or not.
  49870. * Default value : true. The SPS is faster when it's set to false.
  49871. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49872. */
  49873. set: function (val) {
  49874. this._computeParticleTexture = val;
  49875. },
  49876. enumerable: true,
  49877. configurable: true
  49878. });
  49879. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49880. get: function () {
  49881. return this._computeParticleVertex;
  49882. },
  49883. /**
  49884. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49885. * Default value : false. The SPS is faster when it's set to false.
  49886. * Note : the particle custom vertex positions aren't stored values.
  49887. */
  49888. set: function (val) {
  49889. this._computeParticleVertex = val;
  49890. },
  49891. enumerable: true,
  49892. configurable: true
  49893. });
  49894. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49895. get: function () {
  49896. return this._computeBoundingBox;
  49897. },
  49898. /**
  49899. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49900. */
  49901. set: function (val) {
  49902. this._computeBoundingBox = val;
  49903. },
  49904. enumerable: true,
  49905. configurable: true
  49906. });
  49907. // =======================================================================
  49908. // Particle behavior logic
  49909. // these following methods may be overwritten by the user to fit his needs
  49910. /**
  49911. * This function does nothing. It may be overwritten to set all the particle first values.
  49912. * The SPS doesn't call this function, you may have to call it by your own.
  49913. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49914. */
  49915. SolidParticleSystem.prototype.initParticles = function () {
  49916. };
  49917. /**
  49918. * This function does nothing. It may be overwritten to recycle a particle.
  49919. * The SPS doesn't call this function, you may have to call it by your own.
  49920. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49921. */
  49922. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49923. return particle;
  49924. };
  49925. /**
  49926. * Updates a particle : this function should be overwritten by the user.
  49927. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49928. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49929. * ex : just set a particle position or velocity and recycle conditions
  49930. */
  49931. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49932. return particle;
  49933. };
  49934. /**
  49935. * Updates a vertex of a particle : it can be overwritten by the user.
  49936. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49937. * @param particle the current particle
  49938. * @param vertex the current index of the current particle
  49939. * @param pt the index of the current vertex in the particle shape
  49940. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49941. * ex : just set a vertex particle position
  49942. */
  49943. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49944. return vertex;
  49945. };
  49946. /**
  49947. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49948. * This does nothing and may be overwritten by the user.
  49949. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49950. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49951. * @param update the boolean update value actually passed to setParticles()
  49952. */
  49953. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49954. };
  49955. /**
  49956. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49957. * This will be passed three parameters.
  49958. * This does nothing and may be overwritten by the user.
  49959. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49960. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49961. * @param update the boolean update value actually passed to setParticles()
  49962. */
  49963. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49964. };
  49965. return SolidParticleSystem;
  49966. }());
  49967. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49968. })(BABYLON || (BABYLON = {}));
  49969. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49970. var BABYLON;
  49971. (function (BABYLON) {
  49972. var Internals;
  49973. (function (Internals) {
  49974. var FileFaceOrientation = (function () {
  49975. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49976. this.name = name;
  49977. this.worldAxisForNormal = worldAxisForNormal;
  49978. this.worldAxisForFileX = worldAxisForFileX;
  49979. this.worldAxisForFileY = worldAxisForFileY;
  49980. }
  49981. return FileFaceOrientation;
  49982. }());
  49983. ;
  49984. /**
  49985. * Helper class dealing with the extraction of spherical polynomial dataArray
  49986. * from a cube map.
  49987. */
  49988. var CubeMapToSphericalPolynomialTools = (function () {
  49989. function CubeMapToSphericalPolynomialTools() {
  49990. }
  49991. /**
  49992. * Converts a cubemap to the according Spherical Polynomial data.
  49993. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49994. *
  49995. * @param cubeInfo The Cube map to extract the information from.
  49996. * @return The Spherical Polynomial data.
  49997. */
  49998. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49999. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50000. var totalSolidAngle = 0.0;
  50001. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50002. var du = 2.0 / cubeInfo.size;
  50003. var dv = du;
  50004. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50005. var minUV = du * 0.5 - 1.0;
  50006. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50007. var fileFace = this.FileFaces[faceIndex];
  50008. var dataArray = cubeInfo[fileFace.name];
  50009. var v = minUV;
  50010. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50011. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50012. // Because SP is still linear, so summation is fine in that basis.
  50013. for (var y = 0; y < cubeInfo.size; y++) {
  50014. var u = minUV;
  50015. for (var x = 0; x < cubeInfo.size; x++) {
  50016. // World direction (not normalised)
  50017. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50018. worldDirection.normalize();
  50019. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50020. if (1) {
  50021. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50022. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50023. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50024. var color = new BABYLON.Color3(r, g, b);
  50025. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50026. }
  50027. else {
  50028. if (faceIndex == 0) {
  50029. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50030. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50031. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50032. }
  50033. else if (faceIndex == 1) {
  50034. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50035. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50036. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50037. }
  50038. else if (faceIndex == 2) {
  50039. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50040. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50041. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50042. }
  50043. else if (faceIndex == 3) {
  50044. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50045. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50046. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50047. }
  50048. else if (faceIndex == 4) {
  50049. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50050. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50051. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50052. }
  50053. else if (faceIndex == 5) {
  50054. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50055. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50056. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50057. }
  50058. 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]);
  50059. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50060. }
  50061. totalSolidAngle += deltaSolidAngle;
  50062. u += du;
  50063. }
  50064. v += dv;
  50065. }
  50066. }
  50067. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50068. var correction = correctSolidAngle / totalSolidAngle;
  50069. sphericalHarmonics.scale(correction);
  50070. // Additionally scale by pi -- audit needed
  50071. sphericalHarmonics.scale(1.0 / Math.PI);
  50072. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50073. };
  50074. return CubeMapToSphericalPolynomialTools;
  50075. }());
  50076. CubeMapToSphericalPolynomialTools.FileFaces = [
  50077. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50078. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50079. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50080. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50081. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50082. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50083. ];
  50084. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50085. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50086. })(BABYLON || (BABYLON = {}));
  50087. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50088. var BABYLON;
  50089. (function (BABYLON) {
  50090. var Internals;
  50091. (function (Internals) {
  50092. /**
  50093. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50094. */
  50095. var PanoramaToCubeMapTools = (function () {
  50096. function PanoramaToCubeMapTools() {
  50097. }
  50098. /**
  50099. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50100. *
  50101. * @param float32Array The source data.
  50102. * @param inputWidth The width of the input panorama.
  50103. * @param inputhHeight The height of the input panorama.
  50104. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50105. * @return The cubemap data
  50106. */
  50107. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50108. if (!float32Array) {
  50109. throw "ConvertPanoramaToCubemap: input cannot be null";
  50110. }
  50111. if (float32Array.length != inputWidth * inputHeight * 3) {
  50112. throw "ConvertPanoramaToCubemap: input size is wrong";
  50113. }
  50114. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50115. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50116. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50117. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50118. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50119. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50120. return {
  50121. front: textureFront,
  50122. back: textureBack,
  50123. left: textureLeft,
  50124. right: textureRight,
  50125. up: textureUp,
  50126. down: textureDown,
  50127. size: size
  50128. };
  50129. };
  50130. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50131. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50132. var textureArray = new Float32Array(buffer);
  50133. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50134. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50135. var dy = 1 / texSize;
  50136. var fy = 0;
  50137. for (var y = 0; y < texSize; y++) {
  50138. var xv1 = faceData[0];
  50139. var xv2 = faceData[2];
  50140. for (var x = 0; x < texSize; x++) {
  50141. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50142. v.normalize();
  50143. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50144. // 3 channels per pixels
  50145. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50146. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50147. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50148. xv1 = xv1.add(rotDX1);
  50149. xv2 = xv2.add(rotDX2);
  50150. }
  50151. fy += dy;
  50152. }
  50153. return textureArray;
  50154. };
  50155. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50156. var theta = Math.atan2(vDir.z, vDir.x);
  50157. var phi = Math.acos(vDir.y);
  50158. while (theta < -Math.PI)
  50159. theta += 2 * Math.PI;
  50160. while (theta > Math.PI)
  50161. theta -= 2 * Math.PI;
  50162. var dx = theta / Math.PI;
  50163. var dy = phi / Math.PI;
  50164. // recenter.
  50165. dx = dx * 0.5 + 0.5;
  50166. var px = Math.round(dx * inputWidth);
  50167. if (px < 0)
  50168. px = 0;
  50169. else if (px >= inputWidth)
  50170. px = inputWidth - 1;
  50171. var py = Math.round(dy * inputHeight);
  50172. if (py < 0)
  50173. py = 0;
  50174. else if (py >= inputHeight)
  50175. py = inputHeight - 1;
  50176. var inputY = (inputHeight - py - 1);
  50177. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50178. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50179. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50180. return {
  50181. r: r,
  50182. g: g,
  50183. b: b
  50184. };
  50185. };
  50186. return PanoramaToCubeMapTools;
  50187. }());
  50188. PanoramaToCubeMapTools.FACE_FRONT = [
  50189. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50190. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50191. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50192. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50193. ];
  50194. PanoramaToCubeMapTools.FACE_BACK = [
  50195. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50196. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50197. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50198. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50199. ];
  50200. PanoramaToCubeMapTools.FACE_RIGHT = [
  50201. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50202. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50203. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50204. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50205. ];
  50206. PanoramaToCubeMapTools.FACE_LEFT = [
  50207. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50208. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50209. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50210. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50211. ];
  50212. PanoramaToCubeMapTools.FACE_DOWN = [
  50213. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50214. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50215. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50216. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50217. ];
  50218. PanoramaToCubeMapTools.FACE_UP = [
  50219. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50220. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50221. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50222. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50223. ];
  50224. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50225. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50226. })(BABYLON || (BABYLON = {}));
  50227. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50228. var BABYLON;
  50229. (function (BABYLON) {
  50230. var Internals;
  50231. (function (Internals) {
  50232. ;
  50233. /**
  50234. * This groups tools to convert HDR texture to native colors array.
  50235. */
  50236. var HDRTools = (function () {
  50237. function HDRTools() {
  50238. }
  50239. HDRTools.Ldexp = function (mantissa, exponent) {
  50240. if (exponent > 1023) {
  50241. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50242. }
  50243. if (exponent < -1074) {
  50244. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50245. }
  50246. return mantissa * Math.pow(2, exponent);
  50247. };
  50248. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50249. if (exponent > 0) {
  50250. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50251. float32array[index + 0] = red * exponent;
  50252. float32array[index + 1] = green * exponent;
  50253. float32array[index + 2] = blue * exponent;
  50254. }
  50255. else {
  50256. float32array[index + 0] = 0;
  50257. float32array[index + 1] = 0;
  50258. float32array[index + 2] = 0;
  50259. }
  50260. };
  50261. HDRTools.readStringLine = function (uint8array, startIndex) {
  50262. var line = "";
  50263. var character = "";
  50264. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50265. character = String.fromCharCode(uint8array[i]);
  50266. if (character == "\n") {
  50267. break;
  50268. }
  50269. line += character;
  50270. }
  50271. return line;
  50272. };
  50273. /**
  50274. * Reads header information from an RGBE texture stored in a native array.
  50275. * More information on this format are available here:
  50276. * https://en.wikipedia.org/wiki/RGBE_image_format
  50277. *
  50278. * @param uint8array The binary file stored in native array.
  50279. * @return The header information.
  50280. */
  50281. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50282. var height = 0;
  50283. var width = 0;
  50284. var line = this.readStringLine(uint8array, 0);
  50285. if (line[0] != '#' || line[1] != '?') {
  50286. throw "Bad HDR Format.";
  50287. }
  50288. var endOfHeader = false;
  50289. var findFormat = false;
  50290. var lineIndex = 0;
  50291. do {
  50292. lineIndex += (line.length + 1);
  50293. line = this.readStringLine(uint8array, lineIndex);
  50294. if (line == "FORMAT=32-bit_rle_rgbe") {
  50295. findFormat = true;
  50296. }
  50297. else if (line.length == 0) {
  50298. endOfHeader = true;
  50299. }
  50300. } while (!endOfHeader);
  50301. if (!findFormat) {
  50302. throw "HDR Bad header format, unsupported FORMAT";
  50303. }
  50304. lineIndex += (line.length + 1);
  50305. line = this.readStringLine(uint8array, lineIndex);
  50306. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50307. var match = sizeRegexp.exec(line);
  50308. // TODO. Support +Y and -X if needed.
  50309. if (match.length < 3) {
  50310. throw "HDR Bad header format, no size";
  50311. }
  50312. width = parseInt(match[2]);
  50313. height = parseInt(match[1]);
  50314. if (width < 8 || width > 0x7fff) {
  50315. throw "HDR Bad header format, unsupported size";
  50316. }
  50317. lineIndex += (line.length + 1);
  50318. return {
  50319. height: height,
  50320. width: width,
  50321. dataPosition: lineIndex
  50322. };
  50323. };
  50324. /**
  50325. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50326. * This RGBE texture needs to store the information as a panorama.
  50327. *
  50328. * More information on this format are available here:
  50329. * https://en.wikipedia.org/wiki/RGBE_image_format
  50330. *
  50331. * @param buffer The binary file stored in an array buffer.
  50332. * @param size The expected size of the extracted cubemap.
  50333. * @return The Cube Map information.
  50334. */
  50335. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50336. var uint8array = new Uint8Array(buffer);
  50337. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50338. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50339. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50340. return cubeMapData;
  50341. };
  50342. /**
  50343. * Returns the pixels data extracted from an RGBE texture.
  50344. * This pixels will be stored left to right up to down in the R G B order in one array.
  50345. *
  50346. * More information on this format are available here:
  50347. * https://en.wikipedia.org/wiki/RGBE_image_format
  50348. *
  50349. * @param uint8array The binary file stored in an array buffer.
  50350. * @param hdrInfo The header information of the file.
  50351. * @return The pixels data in RGB right to left up to down order.
  50352. */
  50353. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50354. // Keep for multi format supports.
  50355. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50356. };
  50357. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50358. var num_scanlines = hdrInfo.height;
  50359. var scanline_width = hdrInfo.width;
  50360. var a, b, c, d, count;
  50361. var dataIndex = hdrInfo.dataPosition;
  50362. var index = 0, endIndex = 0, i = 0;
  50363. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50364. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50365. // 3 channels of 4 bytes per pixel in float.
  50366. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50367. var resultArray = new Float32Array(resultBuffer);
  50368. // read in each successive scanline
  50369. while (num_scanlines > 0) {
  50370. a = uint8array[dataIndex++];
  50371. b = uint8array[dataIndex++];
  50372. c = uint8array[dataIndex++];
  50373. d = uint8array[dataIndex++];
  50374. if (a != 2 || b != 2 || (c & 0x80)) {
  50375. // this file is not run length encoded
  50376. throw "HDR Bad header format, not RLE";
  50377. }
  50378. if (((c << 8) | d) != scanline_width) {
  50379. throw "HDR Bad header format, wrong scan line width";
  50380. }
  50381. index = 0;
  50382. // read each of the four channels for the scanline into the buffer
  50383. for (i = 0; i < 4; i++) {
  50384. endIndex = (i + 1) * scanline_width;
  50385. while (index < endIndex) {
  50386. a = uint8array[dataIndex++];
  50387. b = uint8array[dataIndex++];
  50388. if (a > 128) {
  50389. // a run of the same value
  50390. count = a - 128;
  50391. if ((count == 0) || (count > endIndex - index)) {
  50392. throw "HDR Bad Format, bad scanline data (run)";
  50393. }
  50394. while (count-- > 0) {
  50395. scanLineArray[index++] = b;
  50396. }
  50397. }
  50398. else {
  50399. // a non-run
  50400. count = a;
  50401. if ((count == 0) || (count > endIndex - index)) {
  50402. throw "HDR Bad Format, bad scanline data (non-run)";
  50403. }
  50404. scanLineArray[index++] = b;
  50405. if (--count > 0) {
  50406. for (var j = 0; j < count; j++) {
  50407. scanLineArray[index++] = uint8array[dataIndex++];
  50408. }
  50409. }
  50410. }
  50411. }
  50412. }
  50413. // now convert data from buffer into floats
  50414. for (i = 0; i < scanline_width; i++) {
  50415. a = scanLineArray[i];
  50416. b = scanLineArray[i + scanline_width];
  50417. c = scanLineArray[i + 2 * scanline_width];
  50418. d = scanLineArray[i + 3 * scanline_width];
  50419. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50420. }
  50421. num_scanlines--;
  50422. }
  50423. return resultArray;
  50424. };
  50425. return HDRTools;
  50426. }());
  50427. Internals.HDRTools = HDRTools;
  50428. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50429. })(BABYLON || (BABYLON = {}));
  50430. //# sourceMappingURL=babylon.tools.hdr.js.map
  50431. //_______________________________________________________________
  50432. // Extracted from CubeMapGen:
  50433. // https://code.google.com/archive/p/cubemapgen/
  50434. //
  50435. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50436. //_______________________________________________________________
  50437. var BABYLON;
  50438. (function (BABYLON) {
  50439. var Internals;
  50440. (function (Internals) {
  50441. /**
  50442. * The bounding box information used during the conversion process.
  50443. */
  50444. var CMGBoundinBox = (function () {
  50445. function CMGBoundinBox() {
  50446. this.min = new BABYLON.Vector3(0, 0, 0);
  50447. this.max = new BABYLON.Vector3(0, 0, 0);
  50448. this.clear();
  50449. }
  50450. CMGBoundinBox.prototype.clear = function () {
  50451. this.min.x = CMGBoundinBox.MAX;
  50452. this.min.y = CMGBoundinBox.MAX;
  50453. this.min.z = CMGBoundinBox.MAX;
  50454. this.max.x = CMGBoundinBox.MIN;
  50455. this.max.y = CMGBoundinBox.MIN;
  50456. this.max.z = CMGBoundinBox.MIN;
  50457. };
  50458. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50459. this.min.x = Math.min(this.min.x, x);
  50460. this.min.y = Math.min(this.min.y, y);
  50461. this.min.z = Math.min(this.min.z, z);
  50462. this.max.x = Math.max(this.max.x, x);
  50463. this.max.y = Math.max(this.max.y, y);
  50464. this.max.z = Math.max(this.max.z, z);
  50465. };
  50466. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50467. this.min.x = Math.max(this.min.x, x);
  50468. this.min.y = Math.max(this.min.y, y);
  50469. this.min.z = Math.max(this.min.z, z);
  50470. };
  50471. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50472. this.max.x = Math.min(this.max.x, x);
  50473. this.max.y = Math.min(this.max.y, y);
  50474. this.max.z = Math.min(this.max.z, z);
  50475. };
  50476. CMGBoundinBox.prototype.empty = function () {
  50477. if ((this.min.x > this.max.y) ||
  50478. (this.min.y > this.max.y) ||
  50479. (this.min.z > this.max.y)) {
  50480. return true;
  50481. }
  50482. else {
  50483. return false;
  50484. }
  50485. };
  50486. return CMGBoundinBox;
  50487. }());
  50488. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50489. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50490. /**
  50491. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50492. * required by the glossinees of a material.
  50493. *
  50494. * This only supports the cosine drop power as well as Warp fixup generation method.
  50495. *
  50496. * This is using the process from CubeMapGen described here:
  50497. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50498. */
  50499. var PMREMGenerator = (function () {
  50500. /**
  50501. * Constructor of the generator.
  50502. *
  50503. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50504. * @param inputSize The size of the cubemap faces
  50505. * @param outputSize The size of the output cubemap faces
  50506. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50507. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50508. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50509. * @param specularPower The max specular level of the desired cubemap
  50510. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50511. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50512. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50513. */
  50514. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50515. this.input = input;
  50516. this.inputSize = inputSize;
  50517. this.outputSize = outputSize;
  50518. this.maxNumMipLevels = maxNumMipLevels;
  50519. this.numChannels = numChannels;
  50520. this.isFloat = isFloat;
  50521. this.specularPower = specularPower;
  50522. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50523. this.excludeBase = excludeBase;
  50524. this.fixup = fixup;
  50525. this._outputSurface = [];
  50526. this._numMipLevels = 0;
  50527. }
  50528. /**
  50529. * Launches the filter process and return the result.
  50530. *
  50531. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50532. */
  50533. PMREMGenerator.prototype.filterCubeMap = function () {
  50534. // Init cubemap processor
  50535. this.init();
  50536. // Filters the cubemap
  50537. this.filterCubeMapMipChain();
  50538. // Returns the filtered mips.
  50539. return this._outputSurface;
  50540. };
  50541. PMREMGenerator.prototype.init = function () {
  50542. var i;
  50543. var j;
  50544. var mipLevelSize;
  50545. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50546. if (this.maxNumMipLevels == 0) {
  50547. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50548. }
  50549. //first miplevel size
  50550. mipLevelSize = this.outputSize;
  50551. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50552. for (j = 0; j < this.maxNumMipLevels; j++) {
  50553. this._outputSurface.length++;
  50554. this._outputSurface[j] = [];
  50555. //Iterate over faces for output images
  50556. for (i = 0; i < 6; i++) {
  50557. this._outputSurface[j].length++;
  50558. // Initializes a new array for the output.
  50559. if (this.isFloat) {
  50560. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50561. }
  50562. else {
  50563. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50564. }
  50565. }
  50566. //next mip level is half size
  50567. mipLevelSize >>= 1;
  50568. this._numMipLevels++;
  50569. //terminate if mip chain becomes too small
  50570. if (mipLevelSize == 0) {
  50571. this.maxNumMipLevels = j;
  50572. return;
  50573. }
  50574. }
  50575. };
  50576. //--------------------------------------------------------------------------------------
  50577. //Cube map filtering and mip chain generation.
  50578. // the cube map filtereing is specified using a number of parameters:
  50579. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50580. // indicates the region of the hemisphere to filter over for each tap.
  50581. //
  50582. // Note that the top mip level is also a filtered version of the original input images
  50583. // as well in order to create mip chains for diffuse environment illumination.
  50584. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50585. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50586. //
  50587. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50588. // is a_InitialMipAngle
  50589. //
  50590. // The angle for the subsequent levels of the mip chain are specified by their parents
  50591. // filtering angle and a per-level scale and bias
  50592. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50593. //
  50594. //--------------------------------------------------------------------------------------
  50595. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50596. // First, take count of the lighting model to modify SpecularPower
  50597. // 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;
  50598. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50599. //Cone angle start (for generating subsequent mip levels)
  50600. var currentSpecularPower = this.specularPower;
  50601. //Build filter lookup tables based on the source miplevel size
  50602. this.precomputeFilterLookupTables(this.inputSize);
  50603. // Note that we need to filter the first level before generating mipmap
  50604. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50605. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50606. // TODO : Write a function to copy and scale the base mipmap in output
  50607. // I am just lazy here and just put a high specular power value, and do some if.
  50608. if (this.excludeBase && (levelIndex == 0)) {
  50609. // 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).
  50610. currentSpecularPower = 100000.0;
  50611. }
  50612. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50613. var srcCubeImage = this.input;
  50614. var dstCubeImage = this._outputSurface[levelIndex];
  50615. var dstSize = this.outputSize >> levelIndex;
  50616. // Compute required angle.
  50617. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50618. // filter cube surfaces
  50619. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50620. // fix seams
  50621. if (this.fixup) {
  50622. this.fixupCubeEdges(dstCubeImage, dstSize);
  50623. }
  50624. // Decrease the specular power to generate the mipmap chain
  50625. // TODO : Use another method for Exclude (see first comment at start of the function
  50626. if (this.excludeBase && (levelIndex == 0)) {
  50627. currentSpecularPower = this.specularPower;
  50628. }
  50629. currentSpecularPower *= this.cosinePowerDropPerMip;
  50630. }
  50631. };
  50632. //--------------------------------------------------------------------------------------
  50633. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50634. // It allow to optimize the texel to access base on the specular power.
  50635. //--------------------------------------------------------------------------------------
  50636. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50637. // We want to find the alpha such that:
  50638. // cos(alpha)^cosinePower = epsilon
  50639. // That's: acos(epsilon^(1/cosinePower))
  50640. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50641. var angle = 180.0;
  50642. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50643. angle *= 180.0 / Math.PI; // Convert to degree
  50644. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50645. return angle;
  50646. };
  50647. //--------------------------------------------------------------------------------------
  50648. //Builds the following lookup tables prior to filtering:
  50649. // -normalizer cube map
  50650. // -tap weight lookup table
  50651. //
  50652. //--------------------------------------------------------------------------------------
  50653. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50654. var srcTexelAngle;
  50655. var iCubeFace;
  50656. //clear pre-existing normalizer cube map
  50657. this._normCubeMap = [];
  50658. //Normalized vectors per cubeface and per-texel solid angle
  50659. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50660. };
  50661. //--------------------------------------------------------------------------------------
  50662. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50663. //
  50664. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50665. //
  50666. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50667. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50668. // below
  50669. //--------------------------------------------------------------------------------------
  50670. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50671. var iCubeFace;
  50672. var u;
  50673. var v;
  50674. //iterate over cube faces
  50675. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50676. //First three channels for norm cube, and last channel for solid angle
  50677. this._normCubeMap.push(new Float32Array(size * size * 4));
  50678. //fast texture walk, build normalizer cube map
  50679. var facesData = this.input[iCubeFace];
  50680. for (v = 0; v < size; v++) {
  50681. for (u = 0; u < size; u++) {
  50682. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50683. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50684. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50685. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50686. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50687. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50688. }
  50689. }
  50690. }
  50691. };
  50692. //--------------------------------------------------------------------------------------
  50693. // Convert cubemap face texel coordinates and face idx to 3D vector
  50694. // note the U and V coords are integer coords and range from 0 to size-1
  50695. // this routine can be used to generate a normalizer cube map
  50696. //--------------------------------------------------------------------------------------
  50697. // SL BEGIN
  50698. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50699. var nvcU;
  50700. var nvcV;
  50701. var tempVec;
  50702. // Change from original AMD code
  50703. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50704. // + 0.5f is for texel center addressing
  50705. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50706. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50707. // warp fixup
  50708. if (fixup && size > 1) {
  50709. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50710. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50711. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50712. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50713. }
  50714. // Get current vector
  50715. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50716. // U contribution
  50717. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50718. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50719. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50720. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50721. // V contribution and Sum
  50722. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50723. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50724. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50725. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50726. //add face axis
  50727. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50728. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50729. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50730. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50731. //normalize vector
  50732. PMREMGenerator._vectorTemp.normalize();
  50733. return PMREMGenerator._vectorTemp;
  50734. };
  50735. //--------------------------------------------------------------------------------------
  50736. // Convert 3D vector to cubemap face texel coordinates and face idx
  50737. // note the U and V coords are integer coords and range from 0 to size-1
  50738. // this routine can be used to generate a normalizer cube map
  50739. //
  50740. // returns face IDX and texel coords
  50741. //--------------------------------------------------------------------------------------
  50742. // SL BEGIN
  50743. /*
  50744. Mapping Texture Coordinates to Cube Map Faces
  50745. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50746. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50747. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50748. map arrangement in Pixar's RenderMan package.
  50749. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50750. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50751. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50752. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50753. the major axis direction). The target column in the table below explains how the major axis direction
  50754. maps to the 2D image of a particular cube map target.
  50755. major axis
  50756. direction target sc tc ma
  50757. ---------- --------------------------------- --- --- ---
  50758. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50759. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50760. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50761. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50762. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50763. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50764. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50765. an updated (s,t) is calculated as follows
  50766. s = ( sc/|ma| + 1 ) / 2
  50767. t = ( tc/|ma| + 1 ) / 2
  50768. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50769. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50770. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50771. */
  50772. // Note this method return U and V in range from 0 to size-1
  50773. // SL END
  50774. // Store the information in vector3 for convenience (faceindex, u, v)
  50775. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50776. var maxCoord;
  50777. var faceIdx;
  50778. //absolute value 3
  50779. var absX = Math.abs(x);
  50780. var absY = Math.abs(y);
  50781. var absZ = Math.abs(z);
  50782. if (absX >= absY && absX >= absZ) {
  50783. maxCoord = absX;
  50784. if (x >= 0) {
  50785. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50786. }
  50787. else {
  50788. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50789. }
  50790. }
  50791. else if (absY >= absX && absY >= absZ) {
  50792. maxCoord = absY;
  50793. if (y >= 0) {
  50794. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50795. }
  50796. else {
  50797. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50798. }
  50799. }
  50800. else {
  50801. maxCoord = absZ;
  50802. if (z >= 0) {
  50803. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50804. }
  50805. else {
  50806. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50807. }
  50808. }
  50809. //divide through by max coord so face vector lies on cube face
  50810. var scale = 1 / maxCoord;
  50811. x *= scale;
  50812. y *= scale;
  50813. z *= scale;
  50814. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50815. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50816. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50817. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50818. // Modify original AMD code to return value from 0 to Size - 1
  50819. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50820. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50821. PMREMGenerator._vectorTemp.x = faceIdx;
  50822. PMREMGenerator._vectorTemp.y = u;
  50823. PMREMGenerator._vectorTemp.z = v;
  50824. return PMREMGenerator._vectorTemp;
  50825. };
  50826. //--------------------------------------------------------------------------------------
  50827. //Original code from Ignacio CastaÒo
  50828. // This formula is from Manne ÷hrstrˆm's thesis.
  50829. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50830. // cube face and return the area of the projection of that portion on the
  50831. // surface of the sphere.
  50832. //--------------------------------------------------------------------------------------
  50833. PMREMGenerator.prototype.areaElement = function (x, y) {
  50834. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50835. };
  50836. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50837. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50838. // (+ 0.5f is for texel center addressing)
  50839. u = (2.0 * (u + 0.5) / size) - 1.0;
  50840. v = (2.0 * (v + 0.5) / size) - 1.0;
  50841. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50842. var invResolution = 1.0 / size;
  50843. // U and V are the -1..1 texture coordinate on the current face.
  50844. // Get projected area for this texel
  50845. var x0 = u - invResolution;
  50846. var y0 = v - invResolution;
  50847. var x1 = u + invResolution;
  50848. var y1 = v + invResolution;
  50849. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50850. return solidAngle;
  50851. };
  50852. //--------------------------------------------------------------------------------------
  50853. //The key to the speed of these filtering routines is to quickly define a per-face
  50854. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50855. // Later these pixels are selectively processed based on their dot products to see if
  50856. // they reside within the filtering cone.
  50857. //
  50858. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50859. // of the number of texels needed to be covered in width and height order to filter the
  50860. // region. the bounding box for the center taps face is defined first, and if the
  50861. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50862. // defined next
  50863. //--------------------------------------------------------------------------------------
  50864. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50865. // note that pixels within these regions may be rejected
  50866. // based on the anlge
  50867. var iCubeFace;
  50868. var u;
  50869. var v;
  50870. // bounding box per face to specify region to process
  50871. var filterExtents = [];
  50872. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50873. filterExtents.push(new CMGBoundinBox());
  50874. }
  50875. // min angle a src texel can cover (in degrees)
  50876. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50877. // angle about center tap to define filter cone
  50878. // filter angle is 1/2 the cone angle
  50879. var filterAngle = filterConeAngle / 2.0;
  50880. //ensure filter angle is larger than a texel
  50881. if (filterAngle < srcTexelAngle) {
  50882. filterAngle = srcTexelAngle;
  50883. }
  50884. //ensure filter cone is always smaller than the hemisphere
  50885. if (filterAngle > 90.0) {
  50886. filterAngle = 90.0;
  50887. }
  50888. // the maximum number of texels in 1D the filter cone angle will cover
  50889. // used to determine bounding box size for filter extents
  50890. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50891. // ensure conservative region always covers at least one texel
  50892. if (filterSize < 1) {
  50893. filterSize = 1;
  50894. }
  50895. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50896. // reside within the cone angle
  50897. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50898. // process required faces
  50899. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50900. //iterate over dst cube map face texel
  50901. for (v = 0; v < dstSize; v++) {
  50902. for (u = 0; u < dstSize; u++) {
  50903. //get center tap direction
  50904. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50905. //clear old per-face filter extents
  50906. this.clearFilterExtents(filterExtents);
  50907. //define per-face filter extents
  50908. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50909. //perform filtering of src faces using filter extents
  50910. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50911. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50912. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50913. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50914. }
  50915. }
  50916. }
  50917. };
  50918. //--------------------------------------------------------------------------------------
  50919. //Clear filter extents for the 6 cube map faces
  50920. //--------------------------------------------------------------------------------------
  50921. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50922. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50923. filterExtents[iCubeFaces].clear();
  50924. }
  50925. };
  50926. //--------------------------------------------------------------------------------------
  50927. //Define per-face bounding box filter extents
  50928. //
  50929. // These define conservative texel regions in each of the faces the filter can possibly
  50930. // process. When the pixels in the regions are actually processed, the dot product
  50931. // between the tap vector and the center tap vector is used to determine the weight of
  50932. // the tap and whether or not the tap is within the cone.
  50933. //
  50934. //--------------------------------------------------------------------------------------
  50935. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50936. //neighboring face and bleed over amount, and width of BBOX for
  50937. // left, right, top, and bottom edges of this face
  50938. var bleedOverAmount = [0, 0, 0, 0];
  50939. var bleedOverBBoxMin = [0, 0, 0, 0];
  50940. var bleedOverBBoxMax = [0, 0, 0, 0];
  50941. var neighborFace;
  50942. var neighborEdge;
  50943. var oppositeFaceIdx;
  50944. //get face idx, and u, v info from center tap dir
  50945. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50946. var faceIdx = result.x;
  50947. var u = result.y;
  50948. var v = result.z;
  50949. //define bbox size within face
  50950. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50951. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50952. filterExtents[faceIdx].clampMin(0, 0, 0);
  50953. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50954. //u and v extent in face corresponding to center tap
  50955. var minU = filterExtents[faceIdx].min.x;
  50956. var minV = filterExtents[faceIdx].min.y;
  50957. var maxU = filterExtents[faceIdx].max.x;
  50958. var maxV = filterExtents[faceIdx].max.y;
  50959. //bleed over amounts for face across u=0 edge (left)
  50960. bleedOverAmount[0] = (bboxSize - u);
  50961. bleedOverBBoxMin[0] = minV;
  50962. bleedOverBBoxMax[0] = maxV;
  50963. //bleed over amounts for face across u=1 edge (right)
  50964. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50965. bleedOverBBoxMin[1] = minV;
  50966. bleedOverBBoxMax[1] = maxV;
  50967. //bleed over to face across v=0 edge (up)
  50968. bleedOverAmount[2] = (bboxSize - v);
  50969. bleedOverBBoxMin[2] = minU;
  50970. bleedOverBBoxMax[2] = maxU;
  50971. //bleed over to face across v=1 edge (down)
  50972. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50973. bleedOverBBoxMin[3] = minU;
  50974. bleedOverBBoxMax[3] = maxU;
  50975. //compute bleed over regions in neighboring faces
  50976. for (var i = 0; i < 4; i++) {
  50977. if (bleedOverAmount[i] > 0) {
  50978. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50979. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50980. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50981. // be flipped: the cases are
  50982. // if a left edge mates with a left or bottom edge on the neighbor
  50983. // if a top edge mates with a top or right edge on the neighbor
  50984. // if a right edge mates with a right or top edge on the neighbor
  50985. // if a bottom edge mates with a bottom or left edge on the neighbor
  50986. //Seeing as the edges are enumerated as follows
  50987. // left =0
  50988. // right =1
  50989. // top =2
  50990. // bottom =3
  50991. //
  50992. // so if the edge enums are the same, or the sum of the enums == 3,
  50993. // the bbox needs to be flipped
  50994. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50995. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50996. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50997. }
  50998. //The way the bounding box is extended onto the neighboring face
  50999. // depends on which edge of neighboring face abuts with this one
  51000. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51001. case PMREMGenerator.CP_EDGE_LEFT:
  51002. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51003. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51004. break;
  51005. case PMREMGenerator.CP_EDGE_RIGHT:
  51006. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51007. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51008. break;
  51009. case PMREMGenerator.CP_EDGE_TOP:
  51010. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51011. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51012. break;
  51013. case PMREMGenerator.CP_EDGE_BOTTOM:
  51014. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51015. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51016. break;
  51017. }
  51018. //clamp filter extents in non-center tap faces to remain within surface
  51019. filterExtents[neighborFace].clampMin(0, 0, 0);
  51020. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51021. }
  51022. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51023. // from the center tap face, then process the opposite face entirely for now.
  51024. //Note that the cases in which this happens, what usually happens is that
  51025. // more than one edge bleeds onto the opposite face, and the bounding box
  51026. // encompasses the entire cube map face.
  51027. if (bleedOverAmount[i] > srcSize) {
  51028. //determine opposite face
  51029. switch (faceIdx) {
  51030. case PMREMGenerator.CP_FACE_X_POS:
  51031. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51032. break;
  51033. case PMREMGenerator.CP_FACE_X_NEG:
  51034. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51035. break;
  51036. case PMREMGenerator.CP_FACE_Y_POS:
  51037. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51038. break;
  51039. case PMREMGenerator.CP_FACE_Y_NEG:
  51040. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51041. break;
  51042. case PMREMGenerator.CP_FACE_Z_POS:
  51043. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51044. break;
  51045. case PMREMGenerator.CP_FACE_Z_NEG:
  51046. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51047. break;
  51048. default:
  51049. break;
  51050. }
  51051. //just encompass entire face for now
  51052. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51053. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51054. }
  51055. }
  51056. };
  51057. //--------------------------------------------------------------------------------------
  51058. //ProcessFilterExtents
  51059. // Process bounding box in each cube face
  51060. //
  51061. //--------------------------------------------------------------------------------------
  51062. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51063. //accumulators are 64-bit floats in order to have the precision needed
  51064. // over a summation of a large number of pixels
  51065. var dstAccum = [0, 0, 0, 0];
  51066. var weightAccum = 0;
  51067. var k = 0;
  51068. var nSrcChannels = this.numChannels;
  51069. // norm cube map and srcCubeMap have same face width
  51070. var faceWidth = srcSize;
  51071. //amount to add to pointer to move to next scanline in images
  51072. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51073. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51074. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51075. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51076. // iterate over cubefaces
  51077. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51078. //if bbox is non empty
  51079. if (!filterExtents[iFaceIdx].empty()) {
  51080. var uStart = filterExtents[iFaceIdx].min.x;
  51081. var vStart = filterExtents[iFaceIdx].min.y;
  51082. var uEnd = filterExtents[iFaceIdx].max.x;
  51083. var vEnd = filterExtents[iFaceIdx].max.y;
  51084. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51085. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51086. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51087. for (var v = vStart; v <= vEnd; v++) {
  51088. var normCubeRowWalk = 0;
  51089. var srcCubeRowWalk = 0;
  51090. for (var u = uStart; u <= uEnd; u++) {
  51091. //pointer to direction in cube map associated with texel
  51092. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51093. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51094. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51095. //check dot product to see if texel is within cone
  51096. var tapDotProd = texelVectX * centerTapDir.x +
  51097. texelVectY * centerTapDir.y +
  51098. texelVectZ * centerTapDir.z;
  51099. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51100. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51101. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51102. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51103. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51104. // so just adding one to specularpower do the trick.
  51105. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51106. //iterate over channels
  51107. for (k = 0; k < nSrcChannels; k++) {
  51108. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51109. srcCubeRowWalk++;
  51110. }
  51111. weightAccum += weight; //accumulate weight
  51112. }
  51113. else {
  51114. //step across source pixel
  51115. srcCubeRowWalk += nSrcChannels;
  51116. }
  51117. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51118. }
  51119. startIndexNormCubeMap += normCubePitch;
  51120. startIndexSrcCubeMap += srcCubePitch;
  51121. }
  51122. }
  51123. }
  51124. //divide through by weights if weight is non zero
  51125. if (weightAccum != 0.0) {
  51126. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51127. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51128. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51129. if (this.numChannels > 3) {
  51130. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51131. }
  51132. }
  51133. else {
  51134. // otherwise sample nearest
  51135. // get face idx and u, v texel coordinate in face
  51136. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51137. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51138. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51139. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51140. if (this.numChannels > 3) {
  51141. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51142. }
  51143. }
  51144. return PMREMGenerator._vectorTemp;
  51145. };
  51146. //--------------------------------------------------------------------------------------
  51147. // Fixup cube edges
  51148. //
  51149. // average texels on cube map faces across the edges
  51150. // WARP/BENT Method Only.
  51151. //--------------------------------------------------------------------------------------
  51152. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51153. var k;
  51154. var j;
  51155. var i;
  51156. var iFace;
  51157. var iCorner = 0;
  51158. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51159. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51160. // note that if functionality to filter across the three texels for each corner, then
  51161. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51162. var cornerPtr = [
  51163. [[], [], []],
  51164. [[], [], []],
  51165. [[], [], []],
  51166. [[], [], []],
  51167. [[], [], []],
  51168. [[], [], []],
  51169. [[], [], []],
  51170. [[], [], []]
  51171. ];
  51172. //if there is no fixup, or fixup width = 0, do nothing
  51173. if (cubeMapSize < 1) {
  51174. return;
  51175. }
  51176. //special case 1x1 cubemap, average face colors
  51177. if (cubeMapSize == 1) {
  51178. //iterate over channels
  51179. for (k = 0; k < this.numChannels; k++) {
  51180. var accum = 0.0;
  51181. //iterate over faces to accumulate face colors
  51182. for (iFace = 0; iFace < 6; iFace++) {
  51183. accum += cubeMap[iFace][k];
  51184. }
  51185. //compute average over 6 face colors
  51186. accum /= 6.0;
  51187. //iterate over faces to distribute face colors
  51188. for (iFace = 0; iFace < 6; iFace++) {
  51189. cubeMap[iFace][k] = accum;
  51190. }
  51191. }
  51192. return;
  51193. }
  51194. //iterate over faces to collect list of corner texel pointers
  51195. for (iFace = 0; iFace < 6; iFace++) {
  51196. //the 4 corner pointers for this face
  51197. faceCornerStartIndicies[0] = [iFace, 0];
  51198. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51199. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51200. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51201. //iterate over face corners to collect cube corner pointers
  51202. for (iCorner = 0; iCorner < 4; iCorner++) {
  51203. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51204. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51205. cornerNumPtrs[corner]++;
  51206. }
  51207. }
  51208. //iterate over corners to average across corner tap values
  51209. for (iCorner = 0; iCorner < 8; iCorner++) {
  51210. for (k = 0; k < this.numChannels; k++) {
  51211. var cornerTapAccum = 0.0;
  51212. //iterate over corner texels and average results
  51213. for (i = 0; i < 3; i++) {
  51214. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51215. }
  51216. //divide by 3 to compute average of corner tap values
  51217. cornerTapAccum *= (1.0 / 3.0);
  51218. //iterate over corner texels and average results
  51219. for (i = 0; i < 3; i++) {
  51220. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51221. }
  51222. }
  51223. }
  51224. //iterate over the twelve edges of the cube to average across edges
  51225. for (i = 0; i < 12; i++) {
  51226. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51227. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51228. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51229. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51230. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51231. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51232. var edgeWalk = 0;
  51233. var neighborEdgeWalk = 0;
  51234. //Determine walking pointers based on edge type
  51235. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51236. switch (edge) {
  51237. case PMREMGenerator.CP_EDGE_LEFT:
  51238. // no change to faceEdgeStartPtr
  51239. edgeWalk = this.numChannels * cubeMapSize;
  51240. break;
  51241. case PMREMGenerator.CP_EDGE_RIGHT:
  51242. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51243. edgeWalk = this.numChannels * cubeMapSize;
  51244. break;
  51245. case PMREMGenerator.CP_EDGE_TOP:
  51246. // no change to faceEdgeStartPtr
  51247. edgeWalk = this.numChannels;
  51248. break;
  51249. case PMREMGenerator.CP_EDGE_BOTTOM:
  51250. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51251. edgeWalk = this.numChannels;
  51252. break;
  51253. }
  51254. //For certain types of edge abutments, the neighbor edge walk needs to
  51255. // be flipped: the cases are
  51256. // if a left edge mates with a left or bottom edge on the neighbor
  51257. // if a top edge mates with a top or right edge on the neighbor
  51258. // if a right edge mates with a right or top edge on the neighbor
  51259. // if a bottom edge mates with a bottom or left edge on the neighbor
  51260. //Seeing as the edges are enumerated as follows
  51261. // left =0
  51262. // right =1
  51263. // top =2
  51264. // bottom =3
  51265. //
  51266. //If the edge enums are the same, or the sum of the enums == 3,
  51267. // the neighbor edge walk needs to be flipped
  51268. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51269. switch (neighborEdge) {
  51270. case PMREMGenerator.CP_EDGE_LEFT:
  51271. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51272. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51273. break;
  51274. case PMREMGenerator.CP_EDGE_RIGHT:
  51275. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51276. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51277. break;
  51278. case PMREMGenerator.CP_EDGE_TOP:
  51279. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51280. neighborEdgeWalk = -this.numChannels;
  51281. break;
  51282. case PMREMGenerator.CP_EDGE_BOTTOM:
  51283. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51284. neighborEdgeWalk = -this.numChannels;
  51285. break;
  51286. }
  51287. }
  51288. else {
  51289. //swapped direction neighbor edge walk
  51290. switch (neighborEdge) {
  51291. case PMREMGenerator.CP_EDGE_LEFT:
  51292. //no change to neighborEdgeStartPtr for this case since it points
  51293. // to the upper left corner already
  51294. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51295. break;
  51296. case PMREMGenerator.CP_EDGE_RIGHT:
  51297. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51298. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51299. break;
  51300. case PMREMGenerator.CP_EDGE_TOP:
  51301. //no change to neighborEdgeStartPtr for this case since it points
  51302. // to the upper left corner already
  51303. neighborEdgeWalk = this.numChannels;
  51304. break;
  51305. case PMREMGenerator.CP_EDGE_BOTTOM:
  51306. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51307. neighborEdgeWalk = this.numChannels;
  51308. break;
  51309. }
  51310. }
  51311. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51312. //nearby neighborhood
  51313. //step ahead one texel on edge
  51314. edgeStartIndex += edgeWalk;
  51315. neighborEdgeStartIndex += neighborEdgeWalk;
  51316. // note that this loop does not process the corner texels, since they have already been
  51317. // averaged across faces across earlier
  51318. for (j = 1; j < (cubeMapSize - 1); j++) {
  51319. //for each set of taps along edge, average them
  51320. // and rewrite the results into the edges
  51321. for (k = 0; k < this.numChannels; k++) {
  51322. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51323. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51324. //compute average of tap intensity values
  51325. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51326. //propagate average of taps to edge taps
  51327. cubeMap[face][edgeStartIndex + k] = avgTap;
  51328. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51329. }
  51330. edgeStartIndex += edgeWalk;
  51331. neighborEdgeStartIndex += neighborEdgeWalk;
  51332. }
  51333. }
  51334. };
  51335. return PMREMGenerator;
  51336. }());
  51337. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51338. PMREMGenerator.CP_UDIR = 0;
  51339. PMREMGenerator.CP_VDIR = 1;
  51340. PMREMGenerator.CP_FACEAXIS = 2;
  51341. //used to index cube faces
  51342. PMREMGenerator.CP_FACE_X_POS = 0;
  51343. PMREMGenerator.CP_FACE_X_NEG = 1;
  51344. PMREMGenerator.CP_FACE_Y_POS = 2;
  51345. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51346. PMREMGenerator.CP_FACE_Z_POS = 4;
  51347. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51348. //used to index image edges
  51349. // NOTE.. the actual number corresponding to the edge is important
  51350. // do not change these, or the code will break
  51351. //
  51352. // CP_EDGE_LEFT is u = 0
  51353. // CP_EDGE_RIGHT is u = width-1
  51354. // CP_EDGE_TOP is v = 0
  51355. // CP_EDGE_BOTTOM is v = height-1
  51356. PMREMGenerator.CP_EDGE_LEFT = 0;
  51357. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51358. PMREMGenerator.CP_EDGE_TOP = 2;
  51359. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51360. //corners of CUBE map (P or N specifys if it corresponds to the
  51361. // positive or negative direction each of X, Y, and Z
  51362. PMREMGenerator.CP_CORNER_NNN = 0;
  51363. PMREMGenerator.CP_CORNER_NNP = 1;
  51364. PMREMGenerator.CP_CORNER_NPN = 2;
  51365. PMREMGenerator.CP_CORNER_NPP = 3;
  51366. PMREMGenerator.CP_CORNER_PNN = 4;
  51367. PMREMGenerator.CP_CORNER_PNP = 5;
  51368. PMREMGenerator.CP_CORNER_PPN = 6;
  51369. PMREMGenerator.CP_CORNER_PPP = 7;
  51370. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51371. //3x2 matrices that map cube map indexing vectors in 3d
  51372. // (after face selection and divide through by the
  51373. // _ABSOLUTE VALUE_ of the max coord)
  51374. // into NVC space
  51375. //Note this currently assumes the D3D cube face ordering and orientation
  51376. PMREMGenerator._sgFace2DMapping = [
  51377. //XPOS face
  51378. [[0, 0, -1],
  51379. [0, -1, 0],
  51380. [1, 0, 0]],
  51381. //XNEG face
  51382. [[0, 0, 1],
  51383. [0, -1, 0],
  51384. [-1, 0, 0]],
  51385. //YPOS face
  51386. [[1, 0, 0],
  51387. [0, 0, 1],
  51388. [0, 1, 0]],
  51389. //YNEG face
  51390. [[1, 0, 0],
  51391. [0, 0, -1],
  51392. [0, -1, 0]],
  51393. //ZPOS face
  51394. [[1, 0, 0],
  51395. [0, -1, 0],
  51396. [0, 0, 1]],
  51397. //ZNEG face
  51398. [[-1, 0, 0],
  51399. [0, -1, 0],
  51400. [0, 0, -1]],
  51401. ];
  51402. //------------------------------------------------------------------------------
  51403. // D3D cube map face specification
  51404. // mapping from 3D x,y,z cube map lookup coordinates
  51405. // to 2D within face u,v coordinates
  51406. //
  51407. // --------------------> U direction
  51408. // | (within-face texture space)
  51409. // | _____
  51410. // | | |
  51411. // | | +Y |
  51412. // | _____|_____|_____ _____
  51413. // | | | | | |
  51414. // | | -X | +Z | +X | -Z |
  51415. // | |_____|_____|_____|_____|
  51416. // | | |
  51417. // | | -Y |
  51418. // | |_____|
  51419. // |
  51420. // v V direction
  51421. // (within-face texture space)
  51422. //------------------------------------------------------------------------------
  51423. //Information about neighbors and how texture coorrdinates change across faces
  51424. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51425. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51426. //Note this currently assumes the D3D cube face ordering and orientation
  51427. PMREMGenerator._sgCubeNgh = [
  51428. //XPOS face
  51429. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51430. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51431. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51432. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51433. //XNEG face
  51434. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51435. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51436. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51437. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51438. //YPOS face
  51439. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51440. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51441. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51442. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51443. //YNEG face
  51444. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51445. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51446. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51447. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51448. //ZPOS face
  51449. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51450. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51451. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51452. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51453. //ZNEG face
  51454. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51455. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51456. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51457. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51458. ];
  51459. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51460. // this table is used to average over the edges.
  51461. PMREMGenerator._sgCubeEdgeList = [
  51462. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51463. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51464. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51465. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51466. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51467. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51468. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51469. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51470. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51471. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51472. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51473. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51474. ];
  51475. //Information about which of the 8 cube corners are correspond to the
  51476. // the 4 corners in each cube face
  51477. // the order is upper left, upper right, lower left, lower right
  51478. PMREMGenerator._sgCubeCornerList = [
  51479. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51480. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51481. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51482. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51483. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51484. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51485. ];
  51486. Internals.PMREMGenerator = PMREMGenerator;
  51487. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51488. })(BABYLON || (BABYLON = {}));
  51489. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  51490. var BABYLON;
  51491. (function (BABYLON) {
  51492. /**
  51493. * This represents a texture coming from an HDR input.
  51494. *
  51495. * The only supported format is currently panorama picture stored in RGBE format.
  51496. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51497. */
  51498. var HDRCubeTexture = (function (_super) {
  51499. __extends(HDRCubeTexture, _super);
  51500. /**
  51501. * Instantiates an HDRTexture from the following parameters.
  51502. *
  51503. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51504. * @param scene The scene the texture will be used in
  51505. * @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.
  51506. * @param noMipmap Forces to not generate the mipmap if true
  51507. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51508. * @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)
  51509. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51510. */
  51511. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51512. if (noMipmap === void 0) { noMipmap = false; }
  51513. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51514. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51515. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51516. var _this = _super.call(this, scene) || this;
  51517. _this._useInGammaSpace = false;
  51518. _this._generateHarmonics = true;
  51519. _this._isBABYLONPreprocessed = false;
  51520. /**
  51521. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51522. */
  51523. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51524. /**
  51525. * The spherical polynomial data extracted from the texture.
  51526. */
  51527. _this.sphericalPolynomial = null;
  51528. /**
  51529. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51530. * This is usefull at run time to apply the good shader.
  51531. */
  51532. _this.isPMREM = false;
  51533. if (!url) {
  51534. return _this;
  51535. }
  51536. _this.name = url;
  51537. _this.url = url;
  51538. _this.hasAlpha = false;
  51539. _this.isCube = true;
  51540. _this._textureMatrix = BABYLON.Matrix.Identity();
  51541. if (size) {
  51542. _this._isBABYLONPreprocessed = false;
  51543. _this._noMipmap = noMipmap;
  51544. _this._size = size;
  51545. _this._useInGammaSpace = useInGammaSpace;
  51546. _this._usePMREMGenerator = usePMREMGenerator &&
  51547. scene.getEngine().getCaps().textureLOD &&
  51548. _this.getScene().getEngine().getCaps().textureFloat &&
  51549. !_this._useInGammaSpace;
  51550. }
  51551. else {
  51552. _this._isBABYLONPreprocessed = true;
  51553. _this._noMipmap = false;
  51554. _this._useInGammaSpace = false;
  51555. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51556. _this.getScene().getEngine().getCaps().textureFloat &&
  51557. !_this._useInGammaSpace;
  51558. }
  51559. _this.isPMREM = _this._usePMREMGenerator;
  51560. _this._texture = _this._getFromCache(url, _this._noMipmap);
  51561. if (!_this._texture) {
  51562. if (!scene.useDelayedTextureLoading) {
  51563. _this.loadTexture();
  51564. }
  51565. else {
  51566. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51567. }
  51568. }
  51569. return _this;
  51570. }
  51571. /**
  51572. * Occurs when the file is a preprocessed .babylon.hdr file.
  51573. */
  51574. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51575. var _this = this;
  51576. var mipLevels = 0;
  51577. var floatArrayView = null;
  51578. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51579. var mips = [];
  51580. var startIndex = 30;
  51581. for (var level = 0; level < mipLevels; level++) {
  51582. mips.push([]);
  51583. // Fill each pixel of the mip level.
  51584. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51585. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51586. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51587. mips[level].push(faceData);
  51588. startIndex += faceSize;
  51589. }
  51590. }
  51591. return mips;
  51592. } : null;
  51593. var callback = function (buffer) {
  51594. // Create Native Array Views
  51595. var intArrayView = new Int32Array(buffer);
  51596. floatArrayView = new Float32Array(buffer);
  51597. // Fill header.
  51598. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51599. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51600. // Update Texture Information.
  51601. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51602. // Fill polynomial information.
  51603. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51604. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51605. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51606. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51607. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51608. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51609. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51610. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51611. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51612. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51613. // Fill pixel data.
  51614. mipLevels = intArrayView[29]; // Number of mip levels.
  51615. var startIndex = 30;
  51616. var data = [];
  51617. var faceSize = Math.pow(_this._size, 2) * 3;
  51618. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51619. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51620. startIndex += faceSize;
  51621. }
  51622. var results = [];
  51623. var byteArray = null;
  51624. // Push each faces.
  51625. for (var k = 0; k < 6; k++) {
  51626. var dataFace = null;
  51627. // If special cases.
  51628. if (!mipmapGenerator) {
  51629. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51630. dataFace = data[j];
  51631. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51632. // 3 channels of 1 bytes per pixel in bytes.
  51633. var byteBuffer = new ArrayBuffer(faceSize);
  51634. byteArray = new Uint8Array(byteBuffer);
  51635. }
  51636. for (var i = 0; i < _this._size * _this._size; i++) {
  51637. // Put in gamma space if requested.
  51638. if (_this._useInGammaSpace) {
  51639. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51640. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51641. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51642. }
  51643. // Convert to int texture for fallback.
  51644. if (byteArray) {
  51645. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51646. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51647. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51648. // May use luminance instead if the result is not accurate.
  51649. var max = Math.max(Math.max(r, g), b);
  51650. if (max > 255) {
  51651. var scale = 255 / max;
  51652. r *= scale;
  51653. g *= scale;
  51654. b *= scale;
  51655. }
  51656. byteArray[(i * 3) + 0] = r;
  51657. byteArray[(i * 3) + 1] = g;
  51658. byteArray[(i * 3) + 2] = b;
  51659. }
  51660. }
  51661. }
  51662. else {
  51663. dataFace = data[k];
  51664. }
  51665. // Fill the array accordingly.
  51666. if (byteArray) {
  51667. results.push(byteArray);
  51668. }
  51669. else {
  51670. results.push(dataFace);
  51671. }
  51672. }
  51673. return results;
  51674. };
  51675. 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);
  51676. };
  51677. /**
  51678. * Occurs when the file is raw .hdr file.
  51679. */
  51680. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51681. var _this = this;
  51682. var callback = function (buffer) {
  51683. // Extract the raw linear data.
  51684. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51685. // Generate harmonics if needed.
  51686. if (_this._generateHarmonics) {
  51687. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51688. }
  51689. var results = [];
  51690. var byteArray = null;
  51691. // Push each faces.
  51692. for (var j = 0; j < 6; j++) {
  51693. // Create uintarray fallback.
  51694. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51695. // 3 channels of 1 bytes per pixel in bytes.
  51696. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51697. byteArray = new Uint8Array(byteBuffer);
  51698. }
  51699. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51700. // If special cases.
  51701. if (_this._useInGammaSpace || byteArray) {
  51702. for (var i = 0; i < _this._size * _this._size; i++) {
  51703. // Put in gamma space if requested.
  51704. if (_this._useInGammaSpace) {
  51705. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51706. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51707. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51708. }
  51709. // Convert to int texture for fallback.
  51710. if (byteArray) {
  51711. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51712. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51713. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51714. // May use luminance instead if the result is not accurate.
  51715. var max = Math.max(Math.max(r, g), b);
  51716. if (max > 255) {
  51717. var scale = 255 / max;
  51718. r *= scale;
  51719. g *= scale;
  51720. b *= scale;
  51721. }
  51722. byteArray[(i * 3) + 0] = r;
  51723. byteArray[(i * 3) + 1] = g;
  51724. byteArray[(i * 3) + 2] = b;
  51725. }
  51726. }
  51727. }
  51728. if (byteArray) {
  51729. results.push(byteArray);
  51730. }
  51731. else {
  51732. results.push(dataFace);
  51733. }
  51734. }
  51735. return results;
  51736. };
  51737. var mipmapGenerator = null;
  51738. if (!this._noMipmap &&
  51739. this._usePMREMGenerator) {
  51740. mipmapGenerator = function (data) {
  51741. // Custom setup of the generator matching with the PBR shader values.
  51742. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51743. return generator.filterCubeMap();
  51744. };
  51745. }
  51746. 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);
  51747. };
  51748. /**
  51749. * Starts the loading process of the texture.
  51750. */
  51751. HDRCubeTexture.prototype.loadTexture = function () {
  51752. if (this._isBABYLONPreprocessed) {
  51753. this.loadBabylonTexture();
  51754. }
  51755. else {
  51756. this.loadHDRTexture();
  51757. }
  51758. };
  51759. HDRCubeTexture.prototype.clone = function () {
  51760. var size = this._isBABYLONPreprocessed ? null : this._size;
  51761. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51762. // Base texture
  51763. newTexture.level = this.level;
  51764. newTexture.wrapU = this.wrapU;
  51765. newTexture.wrapV = this.wrapV;
  51766. newTexture.coordinatesIndex = this.coordinatesIndex;
  51767. newTexture.coordinatesMode = this.coordinatesMode;
  51768. return newTexture;
  51769. };
  51770. // Methods
  51771. HDRCubeTexture.prototype.delayLoad = function () {
  51772. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51773. return;
  51774. }
  51775. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51776. this._texture = this._getFromCache(this.url, this._noMipmap);
  51777. if (!this._texture) {
  51778. this.loadTexture();
  51779. }
  51780. };
  51781. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51782. return this._textureMatrix;
  51783. };
  51784. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51785. var texture = null;
  51786. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51787. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51788. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51789. texture.name = parsedTexture.name;
  51790. texture.hasAlpha = parsedTexture.hasAlpha;
  51791. texture.level = parsedTexture.level;
  51792. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51793. }
  51794. return texture;
  51795. };
  51796. HDRCubeTexture.prototype.serialize = function () {
  51797. if (!this.name) {
  51798. return null;
  51799. }
  51800. var serializationObject = {};
  51801. serializationObject.name = this.name;
  51802. serializationObject.hasAlpha = this.hasAlpha;
  51803. serializationObject.isCube = true;
  51804. serializationObject.level = this.level;
  51805. serializationObject.size = this._size;
  51806. serializationObject.coordinatesMode = this.coordinatesMode;
  51807. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51808. serializationObject.generateHarmonics = this._generateHarmonics;
  51809. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51810. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51811. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51812. return serializationObject;
  51813. };
  51814. /**
  51815. * Saves as a file the data contained in the texture in a binary format.
  51816. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51817. * as the spherical used in the lighting.
  51818. * @param url The HDR file url.
  51819. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51820. * @param onError Method called if any error happens during download.
  51821. * @return The packed binary data.
  51822. */
  51823. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51824. if (onError === void 0) { onError = null; }
  51825. var callback = function (buffer) {
  51826. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51827. // Returns a URL you can use as a href.
  51828. var objUrl = window.URL.createObjectURL(data);
  51829. // Simulates a link to it and click to dowload.
  51830. var a = document.createElement("a");
  51831. document.body.appendChild(a);
  51832. a.style.display = "none";
  51833. a.href = objUrl;
  51834. a.download = "envmap.babylon.hdr";
  51835. a.click();
  51836. };
  51837. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51838. };
  51839. /**
  51840. * Serializes the data contained in the texture in a binary format.
  51841. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51842. * as the spherical used in the lighting.
  51843. * @param url The HDR file url.
  51844. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51845. * @param onError Method called if any error happens during download.
  51846. * @return The packed binary data.
  51847. */
  51848. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51849. if (onError === void 0) { onError = null; }
  51850. // Needs the url tho create the texture.
  51851. if (!url) {
  51852. return null;
  51853. }
  51854. // Check Power of two size.
  51855. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51856. return null;
  51857. }
  51858. var getDataCallback = function (dataBuffer) {
  51859. // Extract the raw linear data.
  51860. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51861. // Generate harmonics if needed.
  51862. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51863. // Generate seamless faces
  51864. var mipGeneratorArray = [];
  51865. // Data are known to be in +X +Y +Z -X -Y -Z
  51866. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51867. mipGeneratorArray.push(cubeData.right); // +X
  51868. mipGeneratorArray.push(cubeData.left); // -X
  51869. mipGeneratorArray.push(cubeData.up); // +Y
  51870. mipGeneratorArray.push(cubeData.down); // -Y
  51871. mipGeneratorArray.push(cubeData.front); // +Z
  51872. mipGeneratorArray.push(cubeData.back); // -Z
  51873. // Custom setup of the generator matching with the PBR shader values.
  51874. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51875. var mippedData = generator.filterCubeMap();
  51876. // Compute required byte length.
  51877. var byteLength = 1 * 4; // Raw Data Version int32.
  51878. byteLength += 4; // CubeMap max mip face size int32.
  51879. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51880. // Add data size.
  51881. byteLength += 4; // Number of mip levels int32.
  51882. for (var level = 0; level < mippedData.length; level++) {
  51883. var mipSize = size >> level;
  51884. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51885. }
  51886. // Prepare binary structure.
  51887. var buffer = new ArrayBuffer(byteLength);
  51888. var intArrayView = new Int32Array(buffer);
  51889. var floatArrayView = new Float32Array(buffer);
  51890. // Fill header.
  51891. intArrayView[0] = 1; // Version 1.
  51892. intArrayView[1] = size; // CubeMap max mip face size.
  51893. // Fill polynomial information.
  51894. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51895. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51896. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51897. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51898. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51899. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51900. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51901. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51902. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51903. // Fill pixel data.
  51904. intArrayView[29] = mippedData.length; // Number of mip levels.
  51905. var startIndex = 30;
  51906. for (var level = 0; level < mippedData.length; level++) {
  51907. // Fill each pixel of the mip level.
  51908. var faceSize = Math.pow(size >> level, 2) * 3;
  51909. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51910. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51911. startIndex += faceSize;
  51912. }
  51913. }
  51914. // Callback.
  51915. callback(buffer);
  51916. };
  51917. // Download and process.
  51918. BABYLON.Tools.LoadFile(url, function (data) {
  51919. getDataCallback(data);
  51920. }, null, null, true, onError);
  51921. };
  51922. return HDRCubeTexture;
  51923. }(BABYLON.BaseTexture));
  51924. HDRCubeTexture._facesMapping = [
  51925. "right",
  51926. "up",
  51927. "front",
  51928. "left",
  51929. "down",
  51930. "back"
  51931. ];
  51932. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51933. })(BABYLON || (BABYLON = {}));
  51934. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51935. var BABYLON;
  51936. (function (BABYLON) {
  51937. var Debug;
  51938. (function (Debug) {
  51939. /**
  51940. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51941. */
  51942. var SkeletonViewer = (function () {
  51943. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51944. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51945. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51946. this.skeleton = skeleton;
  51947. this.mesh = mesh;
  51948. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51949. this.renderingGroupId = renderingGroupId;
  51950. this.color = BABYLON.Color3.White();
  51951. this._debugLines = [];
  51952. this._isEnabled = false;
  51953. this._scene = scene;
  51954. this.update();
  51955. this._renderFunction = this.update.bind(this);
  51956. }
  51957. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51958. get: function () {
  51959. return this._isEnabled;
  51960. },
  51961. set: function (value) {
  51962. if (this._isEnabled === value) {
  51963. return;
  51964. }
  51965. this._isEnabled = value;
  51966. if (value) {
  51967. this._scene.registerBeforeRender(this._renderFunction);
  51968. }
  51969. else {
  51970. this._scene.unregisterBeforeRender(this._renderFunction);
  51971. }
  51972. },
  51973. enumerable: true,
  51974. configurable: true
  51975. });
  51976. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51977. if (x === void 0) { x = 0; }
  51978. if (y === void 0) { y = 0; }
  51979. if (z === void 0) { z = 0; }
  51980. var tmat = BABYLON.Tmp.Matrix[0];
  51981. var parentBone = bone.getParent();
  51982. tmat.copyFrom(bone.getLocalMatrix());
  51983. if (x !== 0 || y !== 0 || z !== 0) {
  51984. var tmat2 = BABYLON.Tmp.Matrix[1];
  51985. BABYLON.Matrix.IdentityToRef(tmat2);
  51986. tmat2.m[12] = x;
  51987. tmat2.m[13] = y;
  51988. tmat2.m[14] = z;
  51989. tmat2.multiplyToRef(tmat, tmat);
  51990. }
  51991. if (parentBone) {
  51992. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51993. }
  51994. tmat.multiplyToRef(meshMat, tmat);
  51995. position.x = tmat.m[12];
  51996. position.y = tmat.m[13];
  51997. position.z = tmat.m[14];
  51998. };
  51999. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52000. var len = bones.length;
  52001. for (var i = 0; i < len; i++) {
  52002. var bone = bones[i];
  52003. var points = this._debugLines[i];
  52004. if (!points) {
  52005. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52006. this._debugLines[i] = points;
  52007. }
  52008. this._getBonePosition(points[0], bone, meshMat);
  52009. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52010. }
  52011. };
  52012. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52013. var len = bones.length;
  52014. var boneNum = 0;
  52015. for (var i = len - 1; i >= 0; i--) {
  52016. var childBone = bones[i];
  52017. var parentBone = childBone.getParent();
  52018. if (!parentBone) {
  52019. continue;
  52020. }
  52021. var points = this._debugLines[boneNum];
  52022. if (!points) {
  52023. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52024. this._debugLines[boneNum] = points;
  52025. }
  52026. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52027. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52028. boneNum++;
  52029. }
  52030. };
  52031. SkeletonViewer.prototype.update = function () {
  52032. if (this.autoUpdateBonesMatrices) {
  52033. this.skeleton.computeAbsoluteTransforms();
  52034. }
  52035. if (this.skeleton.bones[0].length === undefined) {
  52036. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52037. }
  52038. else {
  52039. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52040. }
  52041. if (!this._debugMesh) {
  52042. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52043. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52044. }
  52045. else {
  52046. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52047. }
  52048. this._debugMesh.color = this.color;
  52049. };
  52050. SkeletonViewer.prototype.dispose = function () {
  52051. if (this._debugMesh) {
  52052. this.isEnabled = false;
  52053. this._debugMesh.dispose();
  52054. this._debugMesh = null;
  52055. }
  52056. };
  52057. return SkeletonViewer;
  52058. }());
  52059. Debug.SkeletonViewer = SkeletonViewer;
  52060. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52061. })(BABYLON || (BABYLON = {}));
  52062. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52063. var BABYLON;
  52064. (function (BABYLON) {
  52065. var Debug;
  52066. (function (Debug) {
  52067. var AxesViewer = (function () {
  52068. function AxesViewer(scene, scaleLines) {
  52069. if (scaleLines === void 0) { scaleLines = 1; }
  52070. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52071. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52072. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52073. this.scaleLines = 1;
  52074. this.scaleLines = scaleLines;
  52075. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52076. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52077. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52078. this._xmesh.renderingGroupId = 2;
  52079. this._ymesh.renderingGroupId = 2;
  52080. this._zmesh.renderingGroupId = 2;
  52081. this._xmesh.material.checkReadyOnlyOnce = true;
  52082. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52083. this._ymesh.material.checkReadyOnlyOnce = true;
  52084. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52085. this._zmesh.material.checkReadyOnlyOnce = true;
  52086. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52087. this.scene = scene;
  52088. }
  52089. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52090. var scaleLines = this.scaleLines;
  52091. var point1 = this._xline[0];
  52092. var point2 = this._xline[1];
  52093. point1.x = position.x;
  52094. point1.y = position.y;
  52095. point1.z = position.z;
  52096. point2.x = point1.x + xaxis.x * scaleLines;
  52097. point2.y = point1.y + xaxis.y * scaleLines;
  52098. point2.z = point1.z + xaxis.z * scaleLines;
  52099. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52100. point1 = this._yline[0];
  52101. point2 = this._yline[1];
  52102. point1.x = position.x;
  52103. point1.y = position.y;
  52104. point1.z = position.z;
  52105. point2.x = point1.x + yaxis.x * scaleLines;
  52106. point2.y = point1.y + yaxis.y * scaleLines;
  52107. point2.z = point1.z + yaxis.z * scaleLines;
  52108. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52109. point1 = this._zline[0];
  52110. point2 = this._zline[1];
  52111. point1.x = position.x;
  52112. point1.y = position.y;
  52113. point1.z = position.z;
  52114. point2.x = point1.x + zaxis.x * scaleLines;
  52115. point2.y = point1.y + zaxis.y * scaleLines;
  52116. point2.z = point1.z + zaxis.z * scaleLines;
  52117. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52118. };
  52119. AxesViewer.prototype.dispose = function () {
  52120. if (this._xmesh) {
  52121. this._xmesh.dispose();
  52122. this._ymesh.dispose();
  52123. this._zmesh.dispose();
  52124. this._xmesh = null;
  52125. this._ymesh = null;
  52126. this._zmesh = null;
  52127. this._xline = null;
  52128. this._yline = null;
  52129. this._zline = null;
  52130. this.scene = null;
  52131. }
  52132. };
  52133. return AxesViewer;
  52134. }());
  52135. Debug.AxesViewer = AxesViewer;
  52136. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52137. })(BABYLON || (BABYLON = {}));
  52138. //# sourceMappingURL=babylon.axesViewer.js.map
  52139. var BABYLON;
  52140. (function (BABYLON) {
  52141. var Debug;
  52142. (function (Debug) {
  52143. var BoneAxesViewer = (function (_super) {
  52144. __extends(BoneAxesViewer, _super);
  52145. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52146. if (scaleLines === void 0) { scaleLines = 1; }
  52147. var _this = _super.call(this, scene, scaleLines) || this;
  52148. _this.pos = BABYLON.Vector3.Zero();
  52149. _this.xaxis = BABYLON.Vector3.Zero();
  52150. _this.yaxis = BABYLON.Vector3.Zero();
  52151. _this.zaxis = BABYLON.Vector3.Zero();
  52152. _this.mesh = mesh;
  52153. _this.bone = bone;
  52154. return _this;
  52155. }
  52156. BoneAxesViewer.prototype.update = function () {
  52157. var bone = this.bone;
  52158. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52159. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52160. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52161. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52162. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52163. };
  52164. BoneAxesViewer.prototype.dispose = function () {
  52165. if (this.pos) {
  52166. this.pos = null;
  52167. this.xaxis = null;
  52168. this.yaxis = null;
  52169. this.zaxis = null;
  52170. this.mesh = null;
  52171. this.bone = null;
  52172. _super.prototype.dispose.call(this);
  52173. }
  52174. };
  52175. return BoneAxesViewer;
  52176. }(Debug.AxesViewer));
  52177. Debug.BoneAxesViewer = BoneAxesViewer;
  52178. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52179. })(BABYLON || (BABYLON = {}));
  52180. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52181. var BABYLON;
  52182. (function (BABYLON) {
  52183. /**
  52184. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52185. * It can help converting any input color in a desired output one. This can then be used to create effects
  52186. * from sepia, black and white to sixties or futuristic rendering...
  52187. *
  52188. * The only supported format is currently 3dl.
  52189. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52190. */
  52191. var ColorGradingTexture = (function (_super) {
  52192. __extends(ColorGradingTexture, _super);
  52193. /**
  52194. * Instantiates a ColorGradingTexture from the following parameters.
  52195. *
  52196. * @param url The location of the color gradind data (currently only supporting 3dl)
  52197. * @param scene The scene the texture will be used in
  52198. */
  52199. function ColorGradingTexture(url, scene) {
  52200. var _this = _super.call(this, scene) || this;
  52201. if (!url) {
  52202. return _this;
  52203. }
  52204. _this._textureMatrix = BABYLON.Matrix.Identity();
  52205. _this.name = url;
  52206. _this.url = url;
  52207. _this.hasAlpha = false;
  52208. _this.isCube = false;
  52209. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52210. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52211. _this.anisotropicFilteringLevel = 1;
  52212. _this._texture = _this._getFromCache(url, true);
  52213. if (!_this._texture) {
  52214. if (!scene.useDelayedTextureLoading) {
  52215. _this.loadTexture();
  52216. }
  52217. else {
  52218. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52219. }
  52220. }
  52221. return _this;
  52222. }
  52223. /**
  52224. * Returns the texture matrix used in most of the material.
  52225. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52226. */
  52227. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52228. return this._textureMatrix;
  52229. };
  52230. /**
  52231. * Occurs when the file being loaded is a .3dl LUT file.
  52232. */
  52233. ColorGradingTexture.prototype.load3dlTexture = function () {
  52234. var _this = this;
  52235. var mipLevels = 0;
  52236. var floatArrayView = null;
  52237. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52238. this._texture = texture;
  52239. var callback = function (text) {
  52240. var data;
  52241. var tempData;
  52242. var line;
  52243. var lines = text.split('\n');
  52244. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52245. var maxColor = 0;
  52246. for (var i = 0; i < lines.length; i++) {
  52247. line = lines[i];
  52248. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52249. continue;
  52250. if (line.indexOf('#') === 0)
  52251. continue;
  52252. var words = line.split(" ");
  52253. if (size === 0) {
  52254. // Number of space + one
  52255. size = words.length;
  52256. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52257. tempData = new Float32Array(size * size * size * 4);
  52258. continue;
  52259. }
  52260. if (size != 0) {
  52261. var r = Math.max(parseInt(words[0]), 0);
  52262. var g = Math.max(parseInt(words[1]), 0);
  52263. var b = Math.max(parseInt(words[2]), 0);
  52264. maxColor = Math.max(r, maxColor);
  52265. maxColor = Math.max(g, maxColor);
  52266. maxColor = Math.max(b, maxColor);
  52267. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52268. tempData[pixelStorageIndex + 0] = r;
  52269. tempData[pixelStorageIndex + 1] = g;
  52270. tempData[pixelStorageIndex + 2] = b;
  52271. tempData[pixelStorageIndex + 3] = 0;
  52272. pixelIndexSlice++;
  52273. if (pixelIndexSlice % size == 0) {
  52274. pixelIndexH++;
  52275. pixelIndexSlice = 0;
  52276. if (pixelIndexH % size == 0) {
  52277. pixelIndexW++;
  52278. pixelIndexH = 0;
  52279. }
  52280. }
  52281. }
  52282. }
  52283. for (var i = 0; i < tempData.length; i++) {
  52284. var value = tempData[i];
  52285. data[i] = (value / maxColor * 255);
  52286. }
  52287. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52288. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52289. };
  52290. BABYLON.Tools.LoadFile(this.url, callback);
  52291. return this._texture;
  52292. };
  52293. /**
  52294. * Starts the loading process of the texture.
  52295. */
  52296. ColorGradingTexture.prototype.loadTexture = function () {
  52297. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52298. this.load3dlTexture();
  52299. }
  52300. };
  52301. /**
  52302. * Clones the color gradind texture.
  52303. */
  52304. ColorGradingTexture.prototype.clone = function () {
  52305. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52306. // Base texture
  52307. newTexture.level = this.level;
  52308. return newTexture;
  52309. };
  52310. /**
  52311. * Called during delayed load for textures.
  52312. */
  52313. ColorGradingTexture.prototype.delayLoad = function () {
  52314. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52315. return;
  52316. }
  52317. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52318. this._texture = this._getFromCache(this.url, true);
  52319. if (!this._texture) {
  52320. this.loadTexture();
  52321. }
  52322. };
  52323. /**
  52324. * Binds the color grading to the shader.
  52325. * @param colorGrading The texture to bind
  52326. * @param effect The effect to bind to
  52327. */
  52328. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52329. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52330. var x = colorGrading.level; // Texture Level
  52331. var y = colorGrading.getSize().height; // Texture Size example with 8
  52332. var z = y - 1.0; // SizeMinusOne 8 - 1
  52333. var w = 1 / y; // Space of 1 slice 1 / 8
  52334. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52335. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52336. 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
  52337. 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
  52338. 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
  52339. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52340. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52341. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52342. };
  52343. /**
  52344. * Prepare the list of uniforms associated with the ColorGrading effects.
  52345. * @param uniformsList The list of uniforms used in the effect
  52346. * @param samplersList The list of samplers used in the effect
  52347. */
  52348. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52349. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52350. samplersList.push("cameraColorGrading2DSampler");
  52351. };
  52352. /**
  52353. * Parses a color grading texture serialized by Babylon.
  52354. * @param parsedTexture The texture information being parsedTexture
  52355. * @param scene The scene to load the texture in
  52356. * @param rootUrl The root url of the data assets to load
  52357. * @return A color gradind texture
  52358. */
  52359. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52360. var texture = null;
  52361. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52362. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52363. texture.name = parsedTexture.name;
  52364. texture.level = parsedTexture.level;
  52365. }
  52366. return texture;
  52367. };
  52368. /**
  52369. * Serializes the LUT texture to json format.
  52370. */
  52371. ColorGradingTexture.prototype.serialize = function () {
  52372. if (!this.name) {
  52373. return null;
  52374. }
  52375. var serializationObject = {};
  52376. serializationObject.name = this.name;
  52377. serializationObject.level = this.level;
  52378. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52379. return serializationObject;
  52380. };
  52381. return ColorGradingTexture;
  52382. }(BABYLON.BaseTexture));
  52383. /**
  52384. * Empty line regex stored for GC.
  52385. */
  52386. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52387. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52388. })(BABYLON || (BABYLON = {}));
  52389. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52390. var BABYLON;
  52391. (function (BABYLON) {
  52392. /**
  52393. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52394. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52395. * 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;
  52396. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52397. */
  52398. var ColorCurves = (function () {
  52399. function ColorCurves() {
  52400. this._dirty = true;
  52401. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52402. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52403. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52404. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52405. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52406. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52407. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52408. this._globalHue = 30;
  52409. this._globalDensity = 0;
  52410. this._globalSaturation = 0;
  52411. this._globalExposure = 0;
  52412. this._highlightsHue = 30;
  52413. this._highlightsDensity = 0;
  52414. this._highlightsSaturation = 0;
  52415. this._highlightsExposure = 0;
  52416. this._midtonesHue = 30;
  52417. this._midtonesDensity = 0;
  52418. this._midtonesSaturation = 0;
  52419. this._midtonesExposure = 0;
  52420. this._shadowsHue = 30;
  52421. this._shadowsDensity = 0;
  52422. this._shadowsSaturation = 0;
  52423. this._shadowsExposure = 0;
  52424. }
  52425. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52426. /**
  52427. * Gets the global Hue value.
  52428. * 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).
  52429. */
  52430. get: function () {
  52431. return this._globalHue;
  52432. },
  52433. /**
  52434. * Sets the global Hue value.
  52435. * 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).
  52436. */
  52437. set: function (value) {
  52438. this._globalHue = value;
  52439. this._dirty = true;
  52440. },
  52441. enumerable: true,
  52442. configurable: true
  52443. });
  52444. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52445. /**
  52446. * Gets the global Density value.
  52447. * 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.
  52448. * Values less than zero provide a filter of opposite hue.
  52449. */
  52450. get: function () {
  52451. return this._globalDensity;
  52452. },
  52453. /**
  52454. * Sets the global Density value.
  52455. * 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.
  52456. * Values less than zero provide a filter of opposite hue.
  52457. */
  52458. set: function (value) {
  52459. this._globalDensity = value;
  52460. this._dirty = true;
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52466. /**
  52467. * Gets the global Saturation value.
  52468. * 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.
  52469. */
  52470. get: function () {
  52471. return this._globalSaturation;
  52472. },
  52473. /**
  52474. * Sets the global Saturation value.
  52475. * 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.
  52476. */
  52477. set: function (value) {
  52478. this._globalSaturation = value;
  52479. this._dirty = true;
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52485. /**
  52486. * Gets the highlights Hue value.
  52487. * 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).
  52488. */
  52489. get: function () {
  52490. return this._highlightsHue;
  52491. },
  52492. /**
  52493. * Sets the highlights Hue value.
  52494. * 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).
  52495. */
  52496. set: function (value) {
  52497. this._highlightsHue = value;
  52498. this._dirty = true;
  52499. },
  52500. enumerable: true,
  52501. configurable: true
  52502. });
  52503. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52504. /**
  52505. * Gets the highlights Density value.
  52506. * 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.
  52507. * Values less than zero provide a filter of opposite hue.
  52508. */
  52509. get: function () {
  52510. return this._highlightsDensity;
  52511. },
  52512. /**
  52513. * Sets the highlights Density value.
  52514. * 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.
  52515. * Values less than zero provide a filter of opposite hue.
  52516. */
  52517. set: function (value) {
  52518. this._highlightsDensity = value;
  52519. this._dirty = true;
  52520. },
  52521. enumerable: true,
  52522. configurable: true
  52523. });
  52524. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52525. /**
  52526. * Gets the highlights Saturation value.
  52527. * 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.
  52528. */
  52529. get: function () {
  52530. return this._highlightsSaturation;
  52531. },
  52532. /**
  52533. * Sets the highlights Saturation value.
  52534. * 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.
  52535. */
  52536. set: function (value) {
  52537. this._highlightsSaturation = value;
  52538. this._dirty = true;
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52544. /**
  52545. * Gets the highlights Exposure value.
  52546. * 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.
  52547. */
  52548. get: function () {
  52549. return this._highlightsExposure;
  52550. },
  52551. /**
  52552. * Sets the highlights Exposure value.
  52553. * 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.
  52554. */
  52555. set: function (value) {
  52556. this._highlightsExposure = value;
  52557. this._dirty = true;
  52558. },
  52559. enumerable: true,
  52560. configurable: true
  52561. });
  52562. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52563. /**
  52564. * Gets the midtones Hue value.
  52565. * 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).
  52566. */
  52567. get: function () {
  52568. return this._midtonesHue;
  52569. },
  52570. /**
  52571. * Sets the midtones Hue value.
  52572. * 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).
  52573. */
  52574. set: function (value) {
  52575. this._midtonesHue = value;
  52576. this._dirty = true;
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52582. /**
  52583. * Gets the midtones Density value.
  52584. * 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.
  52585. * Values less than zero provide a filter of opposite hue.
  52586. */
  52587. get: function () {
  52588. return this._midtonesDensity;
  52589. },
  52590. /**
  52591. * Sets the midtones Density value.
  52592. * 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.
  52593. * Values less than zero provide a filter of opposite hue.
  52594. */
  52595. set: function (value) {
  52596. this._midtonesDensity = value;
  52597. this._dirty = true;
  52598. },
  52599. enumerable: true,
  52600. configurable: true
  52601. });
  52602. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52603. /**
  52604. * Gets the midtones Saturation value.
  52605. * 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.
  52606. */
  52607. get: function () {
  52608. return this._midtonesSaturation;
  52609. },
  52610. /**
  52611. * Sets the midtones Saturation value.
  52612. * 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.
  52613. */
  52614. set: function (value) {
  52615. this._midtonesSaturation = value;
  52616. this._dirty = true;
  52617. },
  52618. enumerable: true,
  52619. configurable: true
  52620. });
  52621. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52622. /**
  52623. * Gets the midtones Exposure value.
  52624. * 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.
  52625. */
  52626. get: function () {
  52627. return this._midtonesExposure;
  52628. },
  52629. /**
  52630. * Sets the midtones Exposure value.
  52631. * 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.
  52632. */
  52633. set: function (value) {
  52634. this._midtonesExposure = value;
  52635. this._dirty = true;
  52636. },
  52637. enumerable: true,
  52638. configurable: true
  52639. });
  52640. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52641. /**
  52642. * Gets the shadows Hue value.
  52643. * 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).
  52644. */
  52645. get: function () {
  52646. return this._shadowsHue;
  52647. },
  52648. /**
  52649. * Sets the shadows Hue value.
  52650. * 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).
  52651. */
  52652. set: function (value) {
  52653. this._shadowsHue = value;
  52654. this._dirty = true;
  52655. },
  52656. enumerable: true,
  52657. configurable: true
  52658. });
  52659. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52660. /**
  52661. * Gets the shadows Density value.
  52662. * 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.
  52663. * Values less than zero provide a filter of opposite hue.
  52664. */
  52665. get: function () {
  52666. return this._shadowsDensity;
  52667. },
  52668. /**
  52669. * Sets the shadows Density value.
  52670. * 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.
  52671. * Values less than zero provide a filter of opposite hue.
  52672. */
  52673. set: function (value) {
  52674. this._shadowsDensity = value;
  52675. this._dirty = true;
  52676. },
  52677. enumerable: true,
  52678. configurable: true
  52679. });
  52680. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52681. /**
  52682. * Gets the shadows Saturation value.
  52683. * 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.
  52684. */
  52685. get: function () {
  52686. return this._shadowsSaturation;
  52687. },
  52688. /**
  52689. * Sets the shadows Saturation value.
  52690. * 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.
  52691. */
  52692. set: function (value) {
  52693. this._shadowsSaturation = value;
  52694. this._dirty = true;
  52695. },
  52696. enumerable: true,
  52697. configurable: true
  52698. });
  52699. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52700. /**
  52701. * Gets the shadows Exposure value.
  52702. * 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.
  52703. */
  52704. get: function () {
  52705. return this._shadowsExposure;
  52706. },
  52707. /**
  52708. * Sets the shadows Exposure value.
  52709. * 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.
  52710. */
  52711. set: function (value) {
  52712. this._shadowsExposure = value;
  52713. this._dirty = true;
  52714. },
  52715. enumerable: true,
  52716. configurable: true
  52717. });
  52718. /**
  52719. * Binds the color curves to the shader.
  52720. * @param colorCurves The color curve to bind
  52721. * @param effect The effect to bind to
  52722. */
  52723. ColorCurves.Bind = function (colorCurves, effect) {
  52724. if (colorCurves._dirty) {
  52725. colorCurves._dirty = false;
  52726. // Fill in global info.
  52727. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52728. // Compute highlights info.
  52729. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52730. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52731. // Compute midtones info.
  52732. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52733. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52734. // Compute shadows info.
  52735. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52736. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52737. // Compute deltas (neutral is midtones).
  52738. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52739. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52740. }
  52741. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52742. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52743. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52744. };
  52745. /**
  52746. * Prepare the list of uniforms associated with the ColorCurves effects.
  52747. * @param uniformsList The list of uniforms used in the effect
  52748. */
  52749. ColorCurves.PrepareUniforms = function (uniformsList) {
  52750. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52751. };
  52752. /**
  52753. * Returns color grading data based on a hue, density, saturation and exposure value.
  52754. * @param filterHue The hue of the color filter.
  52755. * @param filterDensity The density of the color filter.
  52756. * @param saturation The saturation.
  52757. * @param exposure The exposure.
  52758. * @param result The result data container.
  52759. */
  52760. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52761. if (hue == null) {
  52762. return;
  52763. }
  52764. hue = ColorCurves.clamp(hue, 0, 360);
  52765. density = ColorCurves.clamp(density, -100, 100);
  52766. saturation = ColorCurves.clamp(saturation, -100, 100);
  52767. exposure = ColorCurves.clamp(exposure, -100, 100);
  52768. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52769. // so that the maximum filter density is only 50% control. This provides fine control
  52770. // for small values and reasonable range.
  52771. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52772. density *= 0.5;
  52773. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52774. if (density < 0) {
  52775. density *= -1;
  52776. hue = (hue + 180) % 360;
  52777. }
  52778. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52779. result.scaleToRef(2, result);
  52780. result.a = 1 + 0.01 * saturation;
  52781. };
  52782. /**
  52783. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52784. * @param value The input slider value in range [-100,100].
  52785. * @returns Adjusted value.
  52786. */
  52787. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52788. value /= 100;
  52789. var x = Math.abs(value);
  52790. x = Math.pow(x, 2);
  52791. if (value < 0) {
  52792. x *= -1;
  52793. }
  52794. x *= 100;
  52795. return x;
  52796. };
  52797. /**
  52798. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52799. * @param hue The hue (H) input.
  52800. * @param saturation The saturation (S) input.
  52801. * @param brightness The brightness (B) input.
  52802. * @result An RGBA color represented as Vector4.
  52803. */
  52804. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52805. var h = ColorCurves.clamp(hue, 0, 360);
  52806. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52807. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52808. if (s === 0) {
  52809. result.r = v;
  52810. result.g = v;
  52811. result.b = v;
  52812. }
  52813. else {
  52814. // sector 0 to 5
  52815. h /= 60;
  52816. var i = Math.floor(h);
  52817. // fractional part of h
  52818. var f = h - i;
  52819. var p = v * (1 - s);
  52820. var q = v * (1 - s * f);
  52821. var t = v * (1 - s * (1 - f));
  52822. switch (i) {
  52823. case 0:
  52824. result.r = v;
  52825. result.g = t;
  52826. result.b = p;
  52827. break;
  52828. case 1:
  52829. result.r = q;
  52830. result.g = v;
  52831. result.b = p;
  52832. break;
  52833. case 2:
  52834. result.r = p;
  52835. result.g = v;
  52836. result.b = t;
  52837. break;
  52838. case 3:
  52839. result.r = p;
  52840. result.g = q;
  52841. result.b = v;
  52842. break;
  52843. case 4:
  52844. result.r = t;
  52845. result.g = p;
  52846. result.b = v;
  52847. break;
  52848. default:
  52849. result.r = v;
  52850. result.g = p;
  52851. result.b = q;
  52852. break;
  52853. }
  52854. }
  52855. result.a = 1;
  52856. };
  52857. /**
  52858. * Returns a value clamped between min and max
  52859. * @param value The value to clamp
  52860. * @param min The minimum of value
  52861. * @param max The maximum of value
  52862. * @returns The clamped value.
  52863. */
  52864. ColorCurves.clamp = function (value, min, max) {
  52865. return Math.min(Math.max(value, min), max);
  52866. };
  52867. /**
  52868. * Clones the current color curve instance.
  52869. * @return The cloned curves
  52870. */
  52871. ColorCurves.prototype.clone = function () {
  52872. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52873. };
  52874. /**
  52875. * Serializes the current color curve instance to a json representation.
  52876. * @return a JSON representation
  52877. */
  52878. ColorCurves.prototype.serialize = function () {
  52879. return BABYLON.SerializationHelper.Serialize(this);
  52880. };
  52881. /**
  52882. * Parses the color curve from a json representation.
  52883. * @param source the JSON source to parse
  52884. * @return The parsed curves
  52885. */
  52886. ColorCurves.Parse = function (source) {
  52887. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52888. };
  52889. return ColorCurves;
  52890. }());
  52891. __decorate([
  52892. BABYLON.serialize()
  52893. ], ColorCurves.prototype, "_globalHue", void 0);
  52894. __decorate([
  52895. BABYLON.serialize()
  52896. ], ColorCurves.prototype, "_globalDensity", void 0);
  52897. __decorate([
  52898. BABYLON.serialize()
  52899. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52900. __decorate([
  52901. BABYLON.serialize()
  52902. ], ColorCurves.prototype, "_globalExposure", void 0);
  52903. __decorate([
  52904. BABYLON.serialize()
  52905. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52906. __decorate([
  52907. BABYLON.serialize()
  52908. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52909. __decorate([
  52910. BABYLON.serialize()
  52911. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52912. __decorate([
  52913. BABYLON.serialize()
  52914. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52915. __decorate([
  52916. BABYLON.serialize()
  52917. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52918. __decorate([
  52919. BABYLON.serialize()
  52920. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52921. __decorate([
  52922. BABYLON.serialize()
  52923. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52924. __decorate([
  52925. BABYLON.serialize()
  52926. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52927. BABYLON.ColorCurves = ColorCurves;
  52928. })(BABYLON || (BABYLON = {}));
  52929. //# sourceMappingURL=babylon.colorCurves.js.map
  52930. var BABYLON;
  52931. (function (BABYLON) {
  52932. var PBRMaterialDefines = (function (_super) {
  52933. __extends(PBRMaterialDefines, _super);
  52934. function PBRMaterialDefines() {
  52935. var _this = _super.call(this) || this;
  52936. _this.ALBEDO = false;
  52937. _this.AMBIENT = false;
  52938. _this.OPACITY = false;
  52939. _this.OPACITYRGB = false;
  52940. _this.REFLECTION = false;
  52941. _this.EMISSIVE = false;
  52942. _this.REFLECTIVITY = false;
  52943. _this.BUMP = false;
  52944. _this.PARALLAX = false;
  52945. _this.PARALLAXOCCLUSION = false;
  52946. _this.SPECULAROVERALPHA = false;
  52947. _this.CLIPPLANE = false;
  52948. _this.ALPHATEST = false;
  52949. _this.ALPHAFROMALBEDO = false;
  52950. _this.POINTSIZE = false;
  52951. _this.FOG = false;
  52952. _this.SPECULARTERM = false;
  52953. _this.OPACITYFRESNEL = false;
  52954. _this.EMISSIVEFRESNEL = false;
  52955. _this.FRESNEL = false;
  52956. _this.NORMAL = false;
  52957. _this.UV1 = false;
  52958. _this.UV2 = false;
  52959. _this.VERTEXCOLOR = false;
  52960. _this.VERTEXALPHA = false;
  52961. _this.NUM_BONE_INFLUENCERS = 0;
  52962. _this.BonesPerMesh = 0;
  52963. _this.INSTANCES = false;
  52964. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52965. _this.MICROSURFACEAUTOMATIC = false;
  52966. _this.EMISSIVEASILLUMINATION = false;
  52967. _this.LINKEMISSIVEWITHALBEDO = false;
  52968. _this.LIGHTMAP = false;
  52969. _this.USELIGHTMAPASSHADOWMAP = false;
  52970. _this.REFLECTIONMAP_3D = false;
  52971. _this.REFLECTIONMAP_SPHERICAL = false;
  52972. _this.REFLECTIONMAP_PLANAR = false;
  52973. _this.REFLECTIONMAP_CUBIC = false;
  52974. _this.REFLECTIONMAP_PROJECTION = false;
  52975. _this.REFLECTIONMAP_SKYBOX = false;
  52976. _this.REFLECTIONMAP_EXPLICIT = false;
  52977. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52978. _this.INVERTCUBICMAP = false;
  52979. _this.LOGARITHMICDEPTH = false;
  52980. _this.CAMERATONEMAP = false;
  52981. _this.CAMERACONTRAST = false;
  52982. _this.CAMERACOLORGRADING = false;
  52983. _this.CAMERACOLORCURVES = false;
  52984. _this.OVERLOADEDVALUES = false;
  52985. _this.OVERLOADEDSHADOWVALUES = false;
  52986. _this.USESPHERICALFROMREFLECTIONMAP = false;
  52987. _this.REFRACTION = false;
  52988. _this.REFRACTIONMAP_3D = false;
  52989. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  52990. _this.REFRACTIONMAPINLINEARSPACE = false;
  52991. _this.LODBASEDMICROSFURACE = false;
  52992. _this.USEPHYSICALLIGHTFALLOFF = false;
  52993. _this.RADIANCEOVERALPHA = false;
  52994. _this.USEPMREMREFLECTION = false;
  52995. _this.USEPMREMREFRACTION = false;
  52996. _this.OPENGLNORMALMAP = false;
  52997. _this.INVERTNORMALMAPX = false;
  52998. _this.INVERTNORMALMAPY = false;
  52999. _this.SHADOWFULLFLOAT = false;
  53000. _this.METALLICWORKFLOW = false;
  53001. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53002. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53003. _this.rebuild();
  53004. return _this;
  53005. }
  53006. return PBRMaterialDefines;
  53007. }(BABYLON.MaterialDefines));
  53008. /**
  53009. * The Physically based material of BJS.
  53010. *
  53011. * This offers the main features of a standard PBR material.
  53012. * For more information, please refer to the documentation :
  53013. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53014. */
  53015. var PBRMaterial = (function (_super) {
  53016. __extends(PBRMaterial, _super);
  53017. /**
  53018. * Instantiates a new PBRMaterial instance.
  53019. *
  53020. * @param name The material name
  53021. * @param scene The scene the material will be use in.
  53022. */
  53023. function PBRMaterial(name, scene) {
  53024. var _this = _super.call(this, name, scene) || this;
  53025. /**
  53026. * Intensity of the direct lights e.g. the four lights available in your scene.
  53027. * This impacts both the direct diffuse and specular highlights.
  53028. */
  53029. _this.directIntensity = 1.0;
  53030. /**
  53031. * Intensity of the emissive part of the material.
  53032. * This helps controlling the emissive effect without modifying the emissive color.
  53033. */
  53034. _this.emissiveIntensity = 1.0;
  53035. /**
  53036. * Intensity of the environment e.g. how much the environment will light the object
  53037. * either through harmonics for rough material or through the refelction for shiny ones.
  53038. */
  53039. _this.environmentIntensity = 1.0;
  53040. /**
  53041. * This is a special control allowing the reduction of the specular highlights coming from the
  53042. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53043. */
  53044. _this.specularIntensity = 1.0;
  53045. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53046. /**
  53047. * Debug Control allowing disabling the bump map on this material.
  53048. */
  53049. _this.disableBumpMap = false;
  53050. /**
  53051. * Debug Control helping enforcing or dropping the darkness of shadows.
  53052. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53053. */
  53054. _this.overloadedShadowIntensity = 1.0;
  53055. /**
  53056. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53057. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53058. */
  53059. _this.overloadedShadeIntensity = 1.0;
  53060. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53061. /**
  53062. * The camera exposure used on this material.
  53063. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53064. * This corresponds to a photographic exposure.
  53065. */
  53066. _this.cameraExposure = 1.0;
  53067. /**
  53068. * The camera contrast used on this material.
  53069. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53070. */
  53071. _this.cameraContrast = 1.0;
  53072. /**
  53073. * Color Grading 2D Lookup Texture.
  53074. * This allows special effects like sepia, black and white to sixties rendering style.
  53075. */
  53076. _this.cameraColorGradingTexture = null;
  53077. /**
  53078. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53079. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53080. * 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;
  53081. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53082. */
  53083. _this.cameraColorCurves = null;
  53084. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53085. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53086. /**
  53087. * Debug Control allowing to overload the ambient color.
  53088. * This as to be use with the overloadedAmbientIntensity parameter.
  53089. */
  53090. _this.overloadedAmbient = BABYLON.Color3.White();
  53091. /**
  53092. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53093. */
  53094. _this.overloadedAmbientIntensity = 0.0;
  53095. /**
  53096. * Debug Control allowing to overload the albedo color.
  53097. * This as to be use with the overloadedAlbedoIntensity parameter.
  53098. */
  53099. _this.overloadedAlbedo = BABYLON.Color3.White();
  53100. /**
  53101. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53102. */
  53103. _this.overloadedAlbedoIntensity = 0.0;
  53104. /**
  53105. * Debug Control allowing to overload the reflectivity color.
  53106. * This as to be use with the overloadedReflectivityIntensity parameter.
  53107. */
  53108. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53109. /**
  53110. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53111. */
  53112. _this.overloadedReflectivityIntensity = 0.0;
  53113. /**
  53114. * Debug Control allowing to overload the emissive color.
  53115. * This as to be use with the overloadedEmissiveIntensity parameter.
  53116. */
  53117. _this.overloadedEmissive = BABYLON.Color3.White();
  53118. /**
  53119. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53120. */
  53121. _this.overloadedEmissiveIntensity = 0.0;
  53122. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53123. /**
  53124. * Debug Control allowing to overload the reflection color.
  53125. * This as to be use with the overloadedReflectionIntensity parameter.
  53126. */
  53127. _this.overloadedReflection = BABYLON.Color3.White();
  53128. /**
  53129. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53130. */
  53131. _this.overloadedReflectionIntensity = 0.0;
  53132. /**
  53133. * Debug Control allowing to overload the microsurface.
  53134. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53135. */
  53136. _this.overloadedMicroSurface = 0.0;
  53137. /**
  53138. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53139. */
  53140. _this.overloadedMicroSurfaceIntensity = 0.0;
  53141. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53142. /**
  53143. * AKA Occlusion Texture Intensity in other nomenclature.
  53144. */
  53145. _this.ambientTextureStrength = 1.0;
  53146. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53147. /**
  53148. * AKA Diffuse Color in other nomenclature.
  53149. */
  53150. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53151. /**
  53152. * AKA Specular Color in other nomenclature.
  53153. */
  53154. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53155. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53156. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53157. /**
  53158. * AKA Glossiness in other nomenclature.
  53159. */
  53160. _this.microSurface = 0.9;
  53161. /**
  53162. * source material index of refraction (IOR)' / 'destination material IOR.
  53163. */
  53164. _this.indexOfRefraction = 0.66;
  53165. /**
  53166. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53167. */
  53168. _this.invertRefractionY = false;
  53169. /**
  53170. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53171. * Materials half opaque for instance using refraction could benefit from this control.
  53172. */
  53173. _this.linkRefractionWithTransparency = false;
  53174. /**
  53175. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53176. */
  53177. _this.linkEmissiveWithAlbedo = false;
  53178. _this.useLightmapAsShadowmap = false;
  53179. /**
  53180. * In this mode, the emissive informtaion will always be added to the lighting once.
  53181. * A light for instance can be thought as emissive.
  53182. */
  53183. _this.useEmissiveAsIllumination = false;
  53184. /**
  53185. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53186. */
  53187. _this.useAlphaFromAlbedoTexture = false;
  53188. /**
  53189. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53190. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53191. */
  53192. _this.useSpecularOverAlpha = true;
  53193. /**
  53194. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53195. */
  53196. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53197. /**
  53198. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53199. */
  53200. _this.useRoughnessFromMetallicTextureAlpha = true;
  53201. /**
  53202. * Specifies if the metallic texture contains the roughness information in its green channel.
  53203. */
  53204. _this.useRoughnessFromMetallicTextureGreen = false;
  53205. /**
  53206. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53207. * The material will try to infer what glossiness each pixel should be.
  53208. */
  53209. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53210. /**
  53211. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53212. * the creation of the material.
  53213. */
  53214. _this.useScalarInLinearSpace = false;
  53215. /**
  53216. * BJS is using an harcoded light falloff based on a manually sets up range.
  53217. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53218. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53219. */
  53220. _this.usePhysicalLightFalloff = true;
  53221. /**
  53222. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53223. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53224. */
  53225. _this.useRadianceOverAlpha = true;
  53226. /**
  53227. * Allows using the bump map in parallax mode.
  53228. */
  53229. _this.useParallax = false;
  53230. /**
  53231. * Allows using the bump map in parallax occlusion mode.
  53232. */
  53233. _this.useParallaxOcclusion = false;
  53234. /**
  53235. * Controls the scale bias of the parallax mode.
  53236. */
  53237. _this.parallaxScaleBias = 0.05;
  53238. /**
  53239. * If sets to true, disables all the lights affecting the material.
  53240. */
  53241. _this.disableLighting = false;
  53242. /**
  53243. * Number of Simultaneous lights allowed on the material.
  53244. */
  53245. _this.maxSimultaneousLights = 4;
  53246. /**
  53247. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53248. */
  53249. _this.invertNormalMapX = false;
  53250. /**
  53251. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53252. */
  53253. _this.invertNormalMapY = false;
  53254. _this._renderTargets = new BABYLON.SmartArray(16);
  53255. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53256. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53257. _this._tempColor = new BABYLON.Color3();
  53258. _this._defines = new PBRMaterialDefines();
  53259. _this._cachedDefines = new PBRMaterialDefines();
  53260. _this._myScene = null;
  53261. _this._myShadowGenerator = null;
  53262. _this._cachedDefines.BonesPerMesh = -1;
  53263. _this.getRenderTargetTextures = function () {
  53264. _this._renderTargets.reset();
  53265. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53266. _this._renderTargets.push(_this.reflectionTexture);
  53267. }
  53268. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53269. _this._renderTargets.push(_this.refractionTexture);
  53270. }
  53271. return _this._renderTargets;
  53272. };
  53273. return _this;
  53274. }
  53275. PBRMaterial.prototype.getClassName = function () {
  53276. return "PBRMaterial";
  53277. };
  53278. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53279. get: function () {
  53280. return this._useLogarithmicDepth;
  53281. },
  53282. set: function (value) {
  53283. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53284. },
  53285. enumerable: true,
  53286. configurable: true
  53287. });
  53288. PBRMaterial.prototype.needAlphaBlending = function () {
  53289. if (this.linkRefractionWithTransparency) {
  53290. return false;
  53291. }
  53292. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53293. };
  53294. PBRMaterial.prototype.needAlphaTesting = function () {
  53295. if (this.linkRefractionWithTransparency) {
  53296. return false;
  53297. }
  53298. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53299. };
  53300. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53301. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53302. };
  53303. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53304. return this.albedoTexture;
  53305. };
  53306. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53307. if (!mesh) {
  53308. return true;
  53309. }
  53310. if (this._defines.INSTANCES !== useInstances) {
  53311. return false;
  53312. }
  53313. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53314. return true;
  53315. }
  53316. return false;
  53317. };
  53318. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53319. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53320. };
  53321. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53322. if (!useScalarInLinear) {
  53323. color.toLinearSpaceToRef(ref);
  53324. }
  53325. else {
  53326. ref.r = color.r;
  53327. ref.g = color.g;
  53328. ref.b = color.b;
  53329. }
  53330. };
  53331. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53332. var lightIndex = 0;
  53333. var depthValuesAlreadySet = false;
  53334. for (var index = 0; index < scene.lights.length; index++) {
  53335. var light = scene.lights[index];
  53336. if (!light.isEnabled()) {
  53337. continue;
  53338. }
  53339. if (!light.canAffectMesh(mesh)) {
  53340. continue;
  53341. }
  53342. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53343. // GAMMA CORRECTION.
  53344. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53345. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53346. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53347. if (defines["SPECULARTERM"]) {
  53348. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53349. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53350. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53351. }
  53352. // Shadows
  53353. if (scene.shadowsEnabled) {
  53354. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53355. }
  53356. lightIndex++;
  53357. if (lightIndex === maxSimultaneousLights)
  53358. break;
  53359. }
  53360. };
  53361. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53362. if (this.checkReadyOnlyOnce) {
  53363. if (this._wasPreviouslyReady) {
  53364. return true;
  53365. }
  53366. }
  53367. var scene = this.getScene();
  53368. var engine = scene.getEngine();
  53369. var needNormals = false;
  53370. var needUVs = false;
  53371. this._defines.reset();
  53372. if (scene.lightsEnabled && !this.disableLighting) {
  53373. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53374. }
  53375. if (!this.checkReadyOnEveryCall) {
  53376. if (this._renderId === scene.getRenderId()) {
  53377. if (this._checkCache(scene, mesh, useInstances)) {
  53378. return true;
  53379. }
  53380. }
  53381. }
  53382. if (scene.texturesEnabled) {
  53383. if (scene.getEngine().getCaps().textureLOD) {
  53384. this._defines.LODBASEDMICROSFURACE = true;
  53385. }
  53386. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53387. if (!this.albedoTexture.isReady()) {
  53388. return false;
  53389. }
  53390. else {
  53391. needUVs = true;
  53392. this._defines.ALBEDO = true;
  53393. }
  53394. }
  53395. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53396. if (!this.ambientTexture.isReady()) {
  53397. return false;
  53398. }
  53399. else {
  53400. needUVs = true;
  53401. this._defines.AMBIENT = true;
  53402. }
  53403. }
  53404. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53405. if (!this.opacityTexture.isReady()) {
  53406. return false;
  53407. }
  53408. else {
  53409. needUVs = true;
  53410. this._defines.OPACITY = true;
  53411. if (this.opacityTexture.getAlphaFromRGB) {
  53412. this._defines.OPACITYRGB = true;
  53413. }
  53414. }
  53415. }
  53416. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53417. if (!this.reflectionTexture.isReady()) {
  53418. return false;
  53419. }
  53420. else {
  53421. needNormals = true;
  53422. this._defines.REFLECTION = true;
  53423. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53424. this._defines.INVERTCUBICMAP = true;
  53425. }
  53426. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53427. switch (this.reflectionTexture.coordinatesMode) {
  53428. case BABYLON.Texture.CUBIC_MODE:
  53429. case BABYLON.Texture.INVCUBIC_MODE:
  53430. this._defines.REFLECTIONMAP_CUBIC = true;
  53431. break;
  53432. case BABYLON.Texture.EXPLICIT_MODE:
  53433. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53434. break;
  53435. case BABYLON.Texture.PLANAR_MODE:
  53436. this._defines.REFLECTIONMAP_PLANAR = true;
  53437. break;
  53438. case BABYLON.Texture.PROJECTION_MODE:
  53439. this._defines.REFLECTIONMAP_PROJECTION = true;
  53440. break;
  53441. case BABYLON.Texture.SKYBOX_MODE:
  53442. this._defines.REFLECTIONMAP_SKYBOX = true;
  53443. break;
  53444. case BABYLON.Texture.SPHERICAL_MODE:
  53445. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53446. break;
  53447. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53448. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53449. break;
  53450. }
  53451. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53452. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53453. needNormals = true;
  53454. if (this.reflectionTexture.isPMREM) {
  53455. this._defines.USEPMREMREFLECTION = true;
  53456. }
  53457. }
  53458. }
  53459. }
  53460. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53461. if (!this.lightmapTexture.isReady()) {
  53462. return false;
  53463. }
  53464. else {
  53465. needUVs = true;
  53466. this._defines.LIGHTMAP = true;
  53467. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53468. }
  53469. }
  53470. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53471. if (!this.emissiveTexture.isReady()) {
  53472. return false;
  53473. }
  53474. else {
  53475. needUVs = true;
  53476. this._defines.EMISSIVE = true;
  53477. }
  53478. }
  53479. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53480. if (this.metallicTexture) {
  53481. if (!this.metallicTexture.isReady()) {
  53482. return false;
  53483. }
  53484. else {
  53485. needUVs = true;
  53486. this._defines.METALLICWORKFLOW = true;
  53487. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53488. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53489. }
  53490. }
  53491. else if (this.reflectivityTexture) {
  53492. if (!this.reflectivityTexture.isReady()) {
  53493. return false;
  53494. }
  53495. else {
  53496. needUVs = true;
  53497. this._defines.REFLECTIVITY = true;
  53498. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53499. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53500. }
  53501. }
  53502. }
  53503. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53504. if (!this.bumpTexture.isReady()) {
  53505. return false;
  53506. }
  53507. else {
  53508. needUVs = true;
  53509. this._defines.BUMP = true;
  53510. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53511. this._defines.PARALLAX = true;
  53512. if (this.useParallaxOcclusion) {
  53513. this._defines.PARALLAXOCCLUSION = true;
  53514. }
  53515. }
  53516. if (this.invertNormalMapX) {
  53517. this._defines.INVERTNORMALMAPX = true;
  53518. }
  53519. if (this.invertNormalMapY) {
  53520. this._defines.INVERTNORMALMAPY = true;
  53521. }
  53522. }
  53523. }
  53524. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53525. if (!this.refractionTexture.isReady()) {
  53526. return false;
  53527. }
  53528. else {
  53529. needUVs = true;
  53530. this._defines.REFRACTION = true;
  53531. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53532. if (this.linkRefractionWithTransparency) {
  53533. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53534. }
  53535. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53536. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53537. if (this.refractionTexture.isPMREM) {
  53538. this._defines.USEPMREMREFRACTION = true;
  53539. }
  53540. }
  53541. }
  53542. }
  53543. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53544. if (!this.cameraColorGradingTexture.isReady()) {
  53545. return false;
  53546. }
  53547. else {
  53548. this._defines.CAMERACOLORGRADING = true;
  53549. }
  53550. }
  53551. }
  53552. // Effect
  53553. if (scene.clipPlane) {
  53554. this._defines.CLIPPLANE = true;
  53555. }
  53556. if (engine.getAlphaTesting()) {
  53557. this._defines.ALPHATEST = true;
  53558. }
  53559. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53560. this._defines.ALPHAFROMALBEDO = true;
  53561. }
  53562. if (this.useEmissiveAsIllumination) {
  53563. this._defines.EMISSIVEASILLUMINATION = true;
  53564. }
  53565. if (this.linkEmissiveWithAlbedo) {
  53566. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53567. }
  53568. if (this.useLogarithmicDepth) {
  53569. this._defines.LOGARITHMICDEPTH = true;
  53570. }
  53571. if (this.cameraContrast != 1) {
  53572. this._defines.CAMERACONTRAST = true;
  53573. }
  53574. if (this.cameraExposure != 1) {
  53575. this._defines.CAMERATONEMAP = true;
  53576. }
  53577. if (this.cameraColorCurves) {
  53578. this._defines.CAMERACOLORCURVES = true;
  53579. }
  53580. if (this.overloadedShadeIntensity != 1 ||
  53581. this.overloadedShadowIntensity != 1) {
  53582. this._defines.OVERLOADEDSHADOWVALUES = true;
  53583. }
  53584. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53585. this.overloadedEmissiveIntensity > 0 ||
  53586. this.overloadedReflectivityIntensity > 0 ||
  53587. this.overloadedAlbedoIntensity > 0 ||
  53588. this.overloadedAmbientIntensity > 0 ||
  53589. this.overloadedReflectionIntensity > 0) {
  53590. this._defines.OVERLOADEDVALUES = true;
  53591. }
  53592. // Point size
  53593. if (this.pointsCloud || scene.forcePointsCloud) {
  53594. this._defines.POINTSIZE = true;
  53595. }
  53596. // Fog
  53597. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53598. this._defines.FOG = true;
  53599. }
  53600. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53601. // Fresnel
  53602. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53603. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53604. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53605. this._defines.OPACITYFRESNEL = true;
  53606. }
  53607. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53608. this._defines.EMISSIVEFRESNEL = true;
  53609. }
  53610. needNormals = true;
  53611. this._defines.FRESNEL = true;
  53612. }
  53613. }
  53614. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53615. this._defines.SPECULAROVERALPHA = true;
  53616. }
  53617. if (this.usePhysicalLightFalloff) {
  53618. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53619. }
  53620. if (this.useRadianceOverAlpha) {
  53621. this._defines.RADIANCEOVERALPHA = true;
  53622. }
  53623. // Attribs
  53624. if (mesh) {
  53625. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53626. this._defines.NORMAL = true;
  53627. }
  53628. if (needUVs) {
  53629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53630. this._defines.UV1 = true;
  53631. }
  53632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53633. this._defines.UV2 = true;
  53634. }
  53635. }
  53636. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53637. this._defines.VERTEXCOLOR = true;
  53638. if (mesh.hasVertexAlpha) {
  53639. this._defines.VERTEXALPHA = true;
  53640. }
  53641. }
  53642. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53643. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53644. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53645. }
  53646. // Instances
  53647. if (useInstances) {
  53648. this._defines.INSTANCES = true;
  53649. }
  53650. }
  53651. // Get correct effect
  53652. if (!this._defines.isEqual(this._cachedDefines)) {
  53653. this._defines.cloneTo(this._cachedDefines);
  53654. scene.resetCachedMaterial();
  53655. // Fallbacks
  53656. var fallbacks = new BABYLON.EffectFallbacks();
  53657. if (this._defines.REFLECTION) {
  53658. fallbacks.addFallback(0, "REFLECTION");
  53659. }
  53660. if (this._defines.REFRACTION) {
  53661. fallbacks.addFallback(0, "REFRACTION");
  53662. }
  53663. if (this._defines.REFLECTIVITY) {
  53664. fallbacks.addFallback(0, "REFLECTIVITY");
  53665. }
  53666. if (this._defines.BUMP) {
  53667. fallbacks.addFallback(0, "BUMP");
  53668. }
  53669. if (this._defines.PARALLAX) {
  53670. fallbacks.addFallback(1, "PARALLAX");
  53671. }
  53672. if (this._defines.PARALLAXOCCLUSION) {
  53673. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53674. }
  53675. if (this._defines.SPECULAROVERALPHA) {
  53676. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53677. }
  53678. if (this._defines.FOG) {
  53679. fallbacks.addFallback(1, "FOG");
  53680. }
  53681. if (this._defines.POINTSIZE) {
  53682. fallbacks.addFallback(0, "POINTSIZE");
  53683. }
  53684. if (this._defines.LOGARITHMICDEPTH) {
  53685. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53686. }
  53687. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53688. if (this._defines.SPECULARTERM) {
  53689. fallbacks.addFallback(0, "SPECULARTERM");
  53690. }
  53691. if (this._defines.OPACITYFRESNEL) {
  53692. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53693. }
  53694. if (this._defines.EMISSIVEFRESNEL) {
  53695. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53696. }
  53697. if (this._defines.FRESNEL) {
  53698. fallbacks.addFallback(3, "FRESNEL");
  53699. }
  53700. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53701. fallbacks.addCPUSkinningFallback(0, mesh);
  53702. }
  53703. //Attributes
  53704. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53705. if (this._defines.NORMAL) {
  53706. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53707. }
  53708. if (this._defines.UV1) {
  53709. attribs.push(BABYLON.VertexBuffer.UVKind);
  53710. }
  53711. if (this._defines.UV2) {
  53712. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53713. }
  53714. if (this._defines.VERTEXCOLOR) {
  53715. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53716. }
  53717. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53718. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53719. // Legacy browser patch
  53720. var join = this._defines.toString();
  53721. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53722. "vFogInfos", "vFogColor", "pointSize",
  53723. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53724. "mBones",
  53725. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53726. "depthValues",
  53727. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53728. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53729. "logarithmicDepthConstant",
  53730. "vSphericalX", "vSphericalY", "vSphericalZ",
  53731. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53732. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53733. "vMicrosurfaceTextureLods",
  53734. "vCameraInfos"
  53735. ];
  53736. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53737. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53738. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53739. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53740. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53741. }
  53742. if (!this._effect.isReady()) {
  53743. return false;
  53744. }
  53745. this._renderId = scene.getRenderId();
  53746. this._wasPreviouslyReady = true;
  53747. if (mesh) {
  53748. if (!mesh._materialDefines) {
  53749. mesh._materialDefines = new PBRMaterialDefines();
  53750. }
  53751. this._defines.cloneTo(mesh._materialDefines);
  53752. }
  53753. return true;
  53754. };
  53755. PBRMaterial.prototype.unbind = function () {
  53756. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53757. this._effect.setTexture("reflection2DSampler", null);
  53758. }
  53759. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53760. this._effect.setTexture("refraction2DSampler", null);
  53761. }
  53762. _super.prototype.unbind.call(this);
  53763. };
  53764. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53765. this._effect.setMatrix("world", world);
  53766. };
  53767. PBRMaterial.prototype.bind = function (world, mesh) {
  53768. this._myScene = this.getScene();
  53769. // Matrices
  53770. this.bindOnlyWorldMatrix(world);
  53771. // Bones
  53772. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53773. if (this._myScene.getCachedMaterial() !== this) {
  53774. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53775. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53776. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53777. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53778. }
  53779. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53780. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53781. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53782. }
  53783. }
  53784. // Textures
  53785. if (this._myScene.texturesEnabled) {
  53786. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53787. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53788. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53789. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53790. }
  53791. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53792. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53793. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53794. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53795. }
  53796. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53797. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53798. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53799. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53800. }
  53801. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53802. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53803. if (this.reflectionTexture.isCube) {
  53804. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53805. }
  53806. else {
  53807. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53808. }
  53809. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53810. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53811. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53812. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53813. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53814. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53815. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53816. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53817. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53818. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53819. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53820. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53821. }
  53822. }
  53823. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53824. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53825. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53826. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53827. }
  53828. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53829. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53830. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53831. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53832. }
  53833. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53834. if (this.metallicTexture) {
  53835. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53836. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53837. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53838. }
  53839. else if (this.reflectivityTexture) {
  53840. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53841. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53842. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53843. }
  53844. }
  53845. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53846. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53847. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53848. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53849. }
  53850. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53851. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53852. var depth = 1.0;
  53853. if (this.refractionTexture.isCube) {
  53854. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53855. }
  53856. else {
  53857. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53858. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53859. if (this.refractionTexture.depth) {
  53860. depth = this.refractionTexture.depth;
  53861. }
  53862. }
  53863. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53864. }
  53865. if ((this.reflectionTexture || this.refractionTexture)) {
  53866. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53867. }
  53868. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53869. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53870. }
  53871. }
  53872. // Clip plane
  53873. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53874. // Point size
  53875. if (this.pointsCloud) {
  53876. this._effect.setFloat("pointSize", this.pointSize);
  53877. }
  53878. // Colors
  53879. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53880. // GAMMA CORRECTION.
  53881. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53882. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53883. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53884. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53885. // GAMMA CORRECTION.
  53886. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53887. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53888. // GAMMA CORRECTION.
  53889. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53890. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53891. }
  53892. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53893. // GAMMA CORRECTION.
  53894. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53895. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53896. // Lights
  53897. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53898. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53899. }
  53900. // View
  53901. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53902. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53903. }
  53904. // Fog
  53905. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53906. this._lightingInfos.x = this.directIntensity;
  53907. this._lightingInfos.y = this.emissiveIntensity;
  53908. this._lightingInfos.z = this.environmentIntensity;
  53909. this._lightingInfos.w = this.specularIntensity;
  53910. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53911. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53912. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53913. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53914. this._cameraInfos.x = this.cameraExposure;
  53915. this._cameraInfos.y = this.cameraContrast;
  53916. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53917. if (this.cameraColorCurves) {
  53918. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53919. }
  53920. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53921. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53922. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53923. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53924. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53925. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53926. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53927. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53928. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53929. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53930. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53931. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53932. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53933. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53934. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53935. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53936. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53937. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53938. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53939. // Log. depth
  53940. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53941. }
  53942. _super.prototype.bind.call(this, world, mesh);
  53943. this._myScene = null;
  53944. };
  53945. PBRMaterial.prototype.getAnimatables = function () {
  53946. var results = [];
  53947. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53948. results.push(this.albedoTexture);
  53949. }
  53950. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53951. results.push(this.ambientTexture);
  53952. }
  53953. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53954. results.push(this.opacityTexture);
  53955. }
  53956. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53957. results.push(this.reflectionTexture);
  53958. }
  53959. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53960. results.push(this.emissiveTexture);
  53961. }
  53962. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  53963. results.push(this.metallicTexture);
  53964. }
  53965. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53966. results.push(this.reflectivityTexture);
  53967. }
  53968. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53969. results.push(this.bumpTexture);
  53970. }
  53971. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53972. results.push(this.lightmapTexture);
  53973. }
  53974. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53975. results.push(this.refractionTexture);
  53976. }
  53977. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53978. results.push(this.cameraColorGradingTexture);
  53979. }
  53980. return results;
  53981. };
  53982. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53983. if (forceDisposeTextures) {
  53984. if (this.albedoTexture) {
  53985. this.albedoTexture.dispose();
  53986. }
  53987. if (this.ambientTexture) {
  53988. this.ambientTexture.dispose();
  53989. }
  53990. if (this.opacityTexture) {
  53991. this.opacityTexture.dispose();
  53992. }
  53993. if (this.reflectionTexture) {
  53994. this.reflectionTexture.dispose();
  53995. }
  53996. if (this.emissiveTexture) {
  53997. this.emissiveTexture.dispose();
  53998. }
  53999. if (this.metallicTexture) {
  54000. this.metallicTexture.dispose();
  54001. }
  54002. if (this.reflectivityTexture) {
  54003. this.reflectivityTexture.dispose();
  54004. }
  54005. if (this.bumpTexture) {
  54006. this.bumpTexture.dispose();
  54007. }
  54008. if (this.lightmapTexture) {
  54009. this.lightmapTexture.dispose();
  54010. }
  54011. if (this.refractionTexture) {
  54012. this.refractionTexture.dispose();
  54013. }
  54014. if (this.cameraColorGradingTexture) {
  54015. this.cameraColorGradingTexture.dispose();
  54016. }
  54017. }
  54018. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54019. };
  54020. PBRMaterial.prototype.clone = function (name) {
  54021. var _this = this;
  54022. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54023. };
  54024. PBRMaterial.prototype.serialize = function () {
  54025. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54026. serializationObject.customType = "BABYLON.PBRMaterial";
  54027. return serializationObject;
  54028. };
  54029. // Statics
  54030. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54031. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54032. };
  54033. return PBRMaterial;
  54034. }(BABYLON.Material));
  54035. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54036. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54037. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54038. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54039. __decorate([
  54040. BABYLON.serialize()
  54041. ], PBRMaterial.prototype, "directIntensity", void 0);
  54042. __decorate([
  54043. BABYLON.serialize()
  54044. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54045. __decorate([
  54046. BABYLON.serialize()
  54047. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54048. __decorate([
  54049. BABYLON.serialize()
  54050. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54051. __decorate([
  54052. BABYLON.serialize()
  54053. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54054. __decorate([
  54055. BABYLON.serialize()
  54056. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54057. __decorate([
  54058. BABYLON.serialize()
  54059. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54060. __decorate([
  54061. BABYLON.serialize()
  54062. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54063. __decorate([
  54064. BABYLON.serialize()
  54065. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54066. __decorate([
  54067. BABYLON.serializeAsTexture()
  54068. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54069. __decorate([
  54070. BABYLON.serializeAsColorCurves()
  54071. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54072. __decorate([
  54073. BABYLON.serializeAsColor3()
  54074. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54075. __decorate([
  54076. BABYLON.serialize()
  54077. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54078. __decorate([
  54079. BABYLON.serializeAsColor3()
  54080. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54081. __decorate([
  54082. BABYLON.serialize()
  54083. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54084. __decorate([
  54085. BABYLON.serializeAsColor3()
  54086. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54087. __decorate([
  54088. BABYLON.serialize()
  54089. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54090. __decorate([
  54091. BABYLON.serializeAsColor3()
  54092. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54093. __decorate([
  54094. BABYLON.serialize()
  54095. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54096. __decorate([
  54097. BABYLON.serializeAsColor3()
  54098. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54099. __decorate([
  54100. BABYLON.serialize()
  54101. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54102. __decorate([
  54103. BABYLON.serialize()
  54104. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54105. __decorate([
  54106. BABYLON.serialize()
  54107. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54108. __decorate([
  54109. BABYLON.serializeAsTexture()
  54110. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54111. __decorate([
  54112. BABYLON.serializeAsTexture()
  54113. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54114. __decorate([
  54115. BABYLON.serialize()
  54116. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54117. __decorate([
  54118. BABYLON.serializeAsTexture()
  54119. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54120. __decorate([
  54121. BABYLON.serializeAsTexture()
  54122. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54123. __decorate([
  54124. BABYLON.serializeAsTexture()
  54125. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54126. __decorate([
  54127. BABYLON.serializeAsTexture()
  54128. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54129. __decorate([
  54130. BABYLON.serializeAsTexture()
  54131. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54132. __decorate([
  54133. BABYLON.serializeAsTexture()
  54134. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54135. __decorate([
  54136. BABYLON.serializeAsTexture()
  54137. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54138. __decorate([
  54139. BABYLON.serializeAsTexture()
  54140. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54141. __decorate([
  54142. BABYLON.serializeAsColor3("ambient")
  54143. ], PBRMaterial.prototype, "ambientColor", void 0);
  54144. __decorate([
  54145. BABYLON.serializeAsColor3("albedo")
  54146. ], PBRMaterial.prototype, "albedoColor", void 0);
  54147. __decorate([
  54148. BABYLON.serializeAsColor3("reflectivity")
  54149. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54150. __decorate([
  54151. BABYLON.serializeAsColor3("reflection")
  54152. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54153. __decorate([
  54154. BABYLON.serializeAsColor3("emissive")
  54155. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54156. __decorate([
  54157. BABYLON.serialize()
  54158. ], PBRMaterial.prototype, "microSurface", void 0);
  54159. __decorate([
  54160. BABYLON.serialize()
  54161. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54162. __decorate([
  54163. BABYLON.serialize()
  54164. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54165. __decorate([
  54166. BABYLON.serializeAsFresnelParameters()
  54167. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54168. __decorate([
  54169. BABYLON.serializeAsFresnelParameters()
  54170. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54171. __decorate([
  54172. BABYLON.serialize()
  54173. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54174. __decorate([
  54175. BABYLON.serialize()
  54176. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54177. __decorate([
  54178. BABYLON.serialize()
  54179. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54180. __decorate([
  54181. BABYLON.serialize()
  54182. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54183. __decorate([
  54184. BABYLON.serialize()
  54185. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54186. __decorate([
  54187. BABYLON.serialize()
  54188. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54189. __decorate([
  54190. BABYLON.serialize()
  54191. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54192. __decorate([
  54193. BABYLON.serialize()
  54194. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54195. __decorate([
  54196. BABYLON.serialize()
  54197. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54198. __decorate([
  54199. BABYLON.serialize()
  54200. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54201. __decorate([
  54202. BABYLON.serialize()
  54203. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54204. __decorate([
  54205. BABYLON.serialize()
  54206. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54207. __decorate([
  54208. BABYLON.serialize()
  54209. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54210. __decorate([
  54211. BABYLON.serialize()
  54212. ], PBRMaterial.prototype, "useParallax", void 0);
  54213. __decorate([
  54214. BABYLON.serialize()
  54215. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54216. __decorate([
  54217. BABYLON.serialize()
  54218. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54219. __decorate([
  54220. BABYLON.serialize()
  54221. ], PBRMaterial.prototype, "disableLighting", void 0);
  54222. __decorate([
  54223. BABYLON.serialize()
  54224. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54225. __decorate([
  54226. BABYLON.serialize()
  54227. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54228. __decorate([
  54229. BABYLON.serialize()
  54230. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54231. __decorate([
  54232. BABYLON.serialize()
  54233. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54234. BABYLON.PBRMaterial = PBRMaterial;
  54235. })(BABYLON || (BABYLON = {}));
  54236. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54237. var BABYLON;
  54238. (function (BABYLON) {
  54239. var DebugLayer = (function () {
  54240. function DebugLayer(scene) {
  54241. this._scene = scene;
  54242. }
  54243. /** Creates the inspector window. */
  54244. DebugLayer.prototype._createInspector = function (popup) {
  54245. if (!this._inspector) {
  54246. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54247. } // else nothing to do,; instance is already existing
  54248. };
  54249. DebugLayer.prototype.isVisible = function () {
  54250. return false;
  54251. };
  54252. DebugLayer.prototype.hide = function () {
  54253. if (this._inspector) {
  54254. this._inspector.dispose();
  54255. this._inspector = null;
  54256. }
  54257. };
  54258. DebugLayer.prototype.show = function (popup) {
  54259. if (typeof INSPECTOR == 'undefined') {
  54260. // Load inspector and add it to the DOM
  54261. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54262. }
  54263. else {
  54264. // Otherwise creates the inspector
  54265. this._createInspector(popup);
  54266. }
  54267. };
  54268. return DebugLayer;
  54269. }());
  54270. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54271. BABYLON.DebugLayer = DebugLayer;
  54272. })(BABYLON || (BABYLON = {}));
  54273. //# sourceMappingURL=babylon.debugLayer.js.map
  54274. var BABYLON;
  54275. (function (BABYLON) {
  54276. var StandardRenderingPipeline = (function (_super) {
  54277. __extends(StandardRenderingPipeline, _super);
  54278. /**
  54279. * @constructor
  54280. * @param {string} name - The rendering pipeline name
  54281. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54282. * @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)
  54283. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54284. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54285. */
  54286. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54287. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54288. var _this = _super.call(this, scene.getEngine(), name) || this;
  54289. _this.downSampleX4PostProcess = null;
  54290. _this.brightPassPostProcess = null;
  54291. _this.gaussianBlurHPostProcesses = [];
  54292. _this.gaussianBlurVPostProcesses = [];
  54293. _this.textureAdderPostProcess = null;
  54294. _this.textureAdderFinalPostProcess = null;
  54295. _this.lensFlarePostProcess = null;
  54296. _this.lensFlareComposePostProcess = null;
  54297. _this.depthOfFieldPostProcess = null;
  54298. // Values
  54299. _this.brightThreshold = 1.0;
  54300. _this.blurWidth = 2.0;
  54301. _this.gaussianCoefficient = 0.25;
  54302. _this.gaussianMean = 1.0;
  54303. _this.gaussianStandardDeviation = 1.0;
  54304. _this.exposure = 1.0;
  54305. _this.lensTexture = null;
  54306. _this.lensColorTexture = null;
  54307. _this.lensFlareStrength = 20.0;
  54308. _this.lensFlareGhostDispersal = 1.4;
  54309. _this.lensFlareHaloWidth = 0.7;
  54310. _this.lensFlareDistortionStrength = 16.0;
  54311. _this.lensStarTexture = null;
  54312. _this.lensFlareDirtTexture = null;
  54313. _this.depthOfFieldDistance = 10.0;
  54314. // IAnimatable
  54315. _this.animations = [];
  54316. _this._depthRenderer = null;
  54317. // Getters and setters
  54318. _this._depthOfFieldEnabled = true;
  54319. _this._lensFlareEnabled = true;
  54320. // Initialize
  54321. _this._scene = scene;
  54322. // Create pass post-processe
  54323. if (!originalPostProcess) {
  54324. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54325. }
  54326. else {
  54327. _this.originalPostProcess = originalPostProcess;
  54328. }
  54329. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54330. // Create down sample X4 post-process
  54331. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  54332. // Create bright pass post-process
  54333. _this._createBrightPassPostProcess(scene, ratio / 2);
  54334. // Create gaussian blur post-processes (down sampling blurs)
  54335. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54336. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54337. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54338. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54339. // Create texture adder post-process
  54340. _this._createTextureAdderPostProcess(scene, ratio);
  54341. // Create depth-of-field source post-process
  54342. _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);
  54343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54344. // Create lens flare post-process
  54345. _this._createLensFlarePostProcess(scene, ratio);
  54346. // Create gaussian blur used by depth-of-field
  54347. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54348. // Create depth-of-field post-process
  54349. _this._createDepthOfFieldPostProcess(scene, ratio);
  54350. // Finish
  54351. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54352. if (cameras !== null) {
  54353. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54354. }
  54355. // Deactivate
  54356. _this.LensFlareEnabled = false;
  54357. _this.DepthOfFieldEnabled = false;
  54358. return _this;
  54359. }
  54360. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54361. get: function () {
  54362. return this._depthOfFieldEnabled;
  54363. },
  54364. set: function (enabled) {
  54365. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54366. if (enabled && !this._depthOfFieldEnabled) {
  54367. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54368. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54369. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54370. this._depthRenderer = this._scene.enableDepthRenderer();
  54371. }
  54372. else if (!enabled && this._depthOfFieldEnabled) {
  54373. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54374. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54375. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54376. }
  54377. this._depthOfFieldEnabled = enabled;
  54378. },
  54379. enumerable: true,
  54380. configurable: true
  54381. });
  54382. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54383. get: function () {
  54384. return this._lensFlareEnabled;
  54385. },
  54386. set: function (enabled) {
  54387. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54388. if (enabled && !this._lensFlareEnabled) {
  54389. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54390. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54391. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54392. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54393. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54394. }
  54395. else if (!enabled && this._lensFlareEnabled) {
  54396. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54397. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54398. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54399. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54400. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54401. }
  54402. this._lensFlareEnabled = enabled;
  54403. },
  54404. enumerable: true,
  54405. configurable: true
  54406. });
  54407. // Down Sample X4 Post-Processs
  54408. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54409. var _this = this;
  54410. var downSampleX4Offsets = new Array(32);
  54411. 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);
  54412. this.downSampleX4PostProcess.onApply = function (effect) {
  54413. var id = 0;
  54414. for (var i = -2; i < 2; i++) {
  54415. for (var j = -2; j < 2; j++) {
  54416. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54417. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54418. id += 2;
  54419. }
  54420. }
  54421. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54422. };
  54423. // Add to pipeline
  54424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54425. };
  54426. // Brightpass Post-Process
  54427. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54428. var _this = this;
  54429. var brightOffsets = new Array(8);
  54430. 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);
  54431. this.brightPassPostProcess.onApply = function (effect) {
  54432. var sU = (1.0 / _this.brightPassPostProcess.width);
  54433. var sV = (1.0 / _this.brightPassPostProcess.height);
  54434. brightOffsets[0] = -0.5 * sU;
  54435. brightOffsets[1] = 0.5 * sV;
  54436. brightOffsets[2] = 0.5 * sU;
  54437. brightOffsets[3] = 0.5 * sV;
  54438. brightOffsets[4] = -0.5 * sU;
  54439. brightOffsets[5] = -0.5 * sV;
  54440. brightOffsets[6] = 0.5 * sU;
  54441. brightOffsets[7] = -0.5 * sV;
  54442. effect.setArray2("dsOffsets", brightOffsets);
  54443. effect.setFloat("brightThreshold", _this.brightThreshold);
  54444. };
  54445. // Add to pipeline
  54446. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54447. };
  54448. // Create gaussian blur H&V post-processes
  54449. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54450. var _this = this;
  54451. var blurOffsets = new Array(9);
  54452. var blurWeights = new Array(9);
  54453. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54454. var callback = function (height) {
  54455. return function (effect) {
  54456. // Weights
  54457. var x = 0.0;
  54458. for (var i = 0; i < 9; i++) {
  54459. x = (i - 4.0) / 4.0;
  54460. blurWeights[i] =
  54461. _this.gaussianCoefficient
  54462. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54463. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54464. }
  54465. var lastOutputDimensions = {
  54466. width: scene.getEngine().getRenderWidth(),
  54467. height: scene.getEngine().getRenderHeight()
  54468. };
  54469. for (var i = 0; i < 9; i++) {
  54470. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54471. blurOffsets[i] = value;
  54472. }
  54473. effect.setArray("blurOffsets", blurOffsets);
  54474. effect.setArray("blurWeights", blurWeights);
  54475. effect.setFloat("blurWidth", _this.blurWidth);
  54476. };
  54477. };
  54478. // Create horizontal gaussian blur post-processes
  54479. 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);
  54480. gaussianBlurHPostProcess.onApply = callback(false);
  54481. // Create vertical gaussian blur post-process
  54482. 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);
  54483. gaussianBlurVPostProcess.onApply = callback(true);
  54484. // Add to pipeline
  54485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54486. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54487. // Finish
  54488. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54489. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54490. };
  54491. // Create texture adder post-process
  54492. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54493. var _this = this;
  54494. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54495. 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);
  54496. this.textureAdderPostProcess.onApply = function (effect) {
  54497. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54498. effect.setTexture("lensSampler", _this.lensTexture);
  54499. effect.setFloat("exposure", _this.exposure);
  54500. };
  54501. // Add to pipeline
  54502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54503. };
  54504. // Create lens flare post-process
  54505. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54506. var _this = this;
  54507. 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);
  54508. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54509. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54510. 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);
  54511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54512. var resolution = new BABYLON.Vector2(0, 0);
  54513. // Lens flare
  54514. this.lensFlarePostProcess.onApply = function (effect) {
  54515. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54516. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54517. effect.setFloat("strength", _this.lensFlareStrength);
  54518. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54519. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54520. // Shift
  54521. resolution.x = _this.lensFlarePostProcess.width;
  54522. resolution.y = _this.lensFlarePostProcess.height;
  54523. effect.setVector2("resolution", resolution);
  54524. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54525. };
  54526. // Compose
  54527. 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);
  54528. 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);
  54529. this.lensFlareComposePostProcess.onApply = function (effect) {
  54530. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54531. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54532. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54533. // Lens start rotation matrix
  54534. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54535. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54536. 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));
  54537. camRot *= 4.0;
  54538. 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);
  54539. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54540. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54541. };
  54542. };
  54543. // Create depth-of-field post-process
  54544. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54545. var _this = this;
  54546. 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);
  54547. this.depthOfFieldPostProcess.onApply = function (effect) {
  54548. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54549. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54550. effect.setFloat("distance", _this.depthOfFieldDistance);
  54551. };
  54552. // Add to pipeline
  54553. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54554. };
  54555. // Dispose
  54556. StandardRenderingPipeline.prototype.dispose = function () {
  54557. for (var i = 0; i < this._scene.cameras.length; i++) {
  54558. var camera = this._scene.cameras[i];
  54559. this.originalPostProcess.dispose(camera);
  54560. this.downSampleX4PostProcess.dispose(camera);
  54561. this.brightPassPostProcess.dispose(camera);
  54562. this.textureAdderPostProcess.dispose(camera);
  54563. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54564. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54565. }
  54566. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54567. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54568. }
  54569. this.textureAdderFinalPostProcess.dispose(camera);
  54570. this.lensFlarePostProcess.dispose(camera);
  54571. this.lensFlareComposePostProcess.dispose(camera);
  54572. this.depthOfFieldPostProcess.dispose(camera);
  54573. }
  54574. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54575. _super.prototype.dispose.call(this);
  54576. };
  54577. return StandardRenderingPipeline;
  54578. }(BABYLON.PostProcessRenderPipeline));
  54579. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54580. })(BABYLON || (BABYLON = {}));
  54581. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54582. 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\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  54583. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  54584. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],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)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],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),b=1/(i*T+r*_+n*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,q=s*y-h*m,D=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*q)*b,t.m[7]=(i*I-n*D+o*V)*b,t.m[11]=-(i*H-r*D+o*N)*b,t.m[15]=(i*q-r*V+n*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var r=new t;return this.multiplyToRef(i,r),r},t.prototype.copyFrom=function(t){\nfor(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.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],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+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*b+m*P,i[r+5]=h*d+a*_+u*F+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*b+f*P,i[r+9]=y*d+c*_+p*F+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*b+w*P,i[r+13]=x*d+l*_+z*F+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},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(r,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 r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(t.FromValuesToRef(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},t.prototype.getRotationMatrix=function(){var i=t.Identity();return this.getRotationMatrixToRef(i),i},t.prototype.getRotationMatrixToRef=function(i){var r=this.m,n=r[0]*r[1]*r[2]*r[3]<0?-1:1,o=r[4]*r[5]*r[6]*r[7]<0?-1:1,e=r[8]*r[9]*r[10]*r[11]<0?-1:1,s=n*Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),h=o*Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),a=e*Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]);t.FromValuesToRef(r[0]/s,r[1]/s,r[2]/s,0,r[4]/h,r[5]/h,r[6]/h,0,r[8]/a,r[9]/a,r[10]/a,0,0,0,0,1,i)},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},t.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},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var 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},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=r,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},t.Compose=function(i,r,n){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.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},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.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},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.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},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.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},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){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.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},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(n+r)/(r-n),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(r-n),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.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]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},t.GetFinalMatrix=function(i,r,n,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return r.multiply(n).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.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},t.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},t.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},t}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  54585. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54586. module.exports = BABYLON;
  54587. };