babylon.max.js 2.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  211. return Color3;
  212. }());
  213. BABYLON.Color3 = Color3;
  214. var Color4 = (function () {
  215. function Color4(r, g, b, a) {
  216. this.r = r;
  217. this.g = g;
  218. this.b = b;
  219. this.a = a;
  220. }
  221. // Operators
  222. Color4.prototype.addInPlace = function (right) {
  223. this.r += right.r;
  224. this.g += right.g;
  225. this.b += right.b;
  226. this.a += right.a;
  227. return this;
  228. };
  229. Color4.prototype.asArray = function () {
  230. var result = [];
  231. this.toArray(result, 0);
  232. return result;
  233. };
  234. Color4.prototype.toArray = function (array, index) {
  235. if (index === undefined) {
  236. index = 0;
  237. }
  238. array[index] = this.r;
  239. array[index + 1] = this.g;
  240. array[index + 2] = this.b;
  241. array[index + 3] = this.a;
  242. return this;
  243. };
  244. Color4.prototype.add = function (right) {
  245. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  246. };
  247. Color4.prototype.subtract = function (right) {
  248. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  249. };
  250. Color4.prototype.subtractToRef = function (right, result) {
  251. result.r = this.r - right.r;
  252. result.g = this.g - right.g;
  253. result.b = this.b - right.b;
  254. result.a = this.a - right.a;
  255. return this;
  256. };
  257. Color4.prototype.scale = function (scale) {
  258. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  259. };
  260. Color4.prototype.scaleToRef = function (scale, result) {
  261. result.r = this.r * scale;
  262. result.g = this.g * scale;
  263. result.b = this.b * scale;
  264. result.a = this.a * scale;
  265. return this;
  266. };
  267. /**
  268. * Multipy an RGBA Color4 value by another and return a new Color4 object
  269. * @param color The Color4 (RGBA) value to multiply by
  270. * @returns A new Color4.
  271. */
  272. Color4.prototype.multiply = function (color) {
  273. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  274. };
  275. /**
  276. * Multipy an RGBA Color4 value by another and push the result in a reference value
  277. * @param color The Color4 (RGBA) value to multiply by
  278. * @param result The Color4 (RGBA) to fill the result in
  279. * @returns the result Color4.
  280. */
  281. Color4.prototype.multiplyToRef = function (color, result) {
  282. result.r = this.r * color.r;
  283. result.g = this.g * color.g;
  284. result.b = this.b * color.b;
  285. result.a = this.a * color.a;
  286. return result;
  287. };
  288. Color4.prototype.toString = function () {
  289. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  290. };
  291. Color4.prototype.getClassName = function () {
  292. return "Color4";
  293. };
  294. Color4.prototype.getHashCode = function () {
  295. var hash = this.r || 0;
  296. hash = (hash * 397) ^ (this.g || 0);
  297. hash = (hash * 397) ^ (this.b || 0);
  298. hash = (hash * 397) ^ (this.a || 0);
  299. return hash;
  300. };
  301. Color4.prototype.clone = function () {
  302. return new Color4(this.r, this.g, this.b, this.a);
  303. };
  304. Color4.prototype.copyFrom = function (source) {
  305. this.r = source.r;
  306. this.g = source.g;
  307. this.b = source.b;
  308. this.a = source.a;
  309. return this;
  310. };
  311. Color4.prototype.toHexString = function () {
  312. var intR = (this.r * 255) | 0;
  313. var intG = (this.g * 255) | 0;
  314. var intB = (this.b * 255) | 0;
  315. var intA = (this.a * 255) | 0;
  316. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  317. };
  318. // Statics
  319. Color4.FromHexString = function (hex) {
  320. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  321. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  322. return new Color4(0, 0, 0, 0);
  323. }
  324. var r = parseInt(hex.substring(1, 3), 16);
  325. var g = parseInt(hex.substring(3, 5), 16);
  326. var b = parseInt(hex.substring(5, 7), 16);
  327. var a = parseInt(hex.substring(7, 9), 16);
  328. return Color4.FromInts(r, g, b, a);
  329. };
  330. Color4.Lerp = function (left, right, amount) {
  331. var result = new Color4(0, 0, 0, 0);
  332. Color4.LerpToRef(left, right, amount, result);
  333. return result;
  334. };
  335. Color4.LerpToRef = function (left, right, amount, result) {
  336. result.r = left.r + (right.r - left.r) * amount;
  337. result.g = left.g + (right.g - left.g) * amount;
  338. result.b = left.b + (right.b - left.b) * amount;
  339. result.a = left.a + (right.a - left.a) * amount;
  340. };
  341. Color4.FromArray = function (array, offset) {
  342. if (offset === void 0) { offset = 0; }
  343. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  344. };
  345. Color4.FromInts = function (r, g, b, a) {
  346. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  347. };
  348. Color4.CheckColors4 = function (colors, count) {
  349. // Check if color3 was used
  350. if (colors.length === count * 3) {
  351. var colors4 = [];
  352. for (var index = 0; index < colors.length; index += 3) {
  353. var newIndex = (index / 3) * 4;
  354. colors4[newIndex] = colors[index];
  355. colors4[newIndex + 1] = colors[index + 1];
  356. colors4[newIndex + 2] = colors[index + 2];
  357. colors4[newIndex + 3] = 1.0;
  358. }
  359. return colors4;
  360. }
  361. return colors;
  362. };
  363. return Color4;
  364. }());
  365. BABYLON.Color4 = Color4;
  366. var Vector2 = (function () {
  367. function Vector2(x, y) {
  368. this.x = x;
  369. this.y = y;
  370. }
  371. Vector2.prototype.toString = function () {
  372. return "{X: " + this.x + " Y:" + this.y + "}";
  373. };
  374. Vector2.prototype.getClassName = function () {
  375. return "Vector2";
  376. };
  377. Vector2.prototype.getHashCode = function () {
  378. var hash = this.x || 0;
  379. hash = (hash * 397) ^ (this.y || 0);
  380. return hash;
  381. };
  382. // Operators
  383. Vector2.prototype.toArray = function (array, index) {
  384. if (index === void 0) { index = 0; }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. return this;
  388. };
  389. Vector2.prototype.asArray = function () {
  390. var result = [];
  391. this.toArray(result, 0);
  392. return result;
  393. };
  394. Vector2.prototype.copyFrom = function (source) {
  395. this.x = source.x;
  396. this.y = source.y;
  397. return this;
  398. };
  399. Vector2.prototype.copyFromFloats = function (x, y) {
  400. this.x = x;
  401. this.y = y;
  402. return this;
  403. };
  404. Vector2.prototype.add = function (otherVector) {
  405. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  406. };
  407. Vector2.prototype.addToRef = function (otherVector, result) {
  408. result.x = this.x + otherVector.x;
  409. result.y = this.y + otherVector.y;
  410. return this;
  411. };
  412. Vector2.prototype.addInPlace = function (otherVector) {
  413. this.x += otherVector.x;
  414. this.y += otherVector.y;
  415. return this;
  416. };
  417. Vector2.prototype.addVector3 = function (otherVector) {
  418. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  419. };
  420. Vector2.prototype.subtract = function (otherVector) {
  421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  422. };
  423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  424. result.x = this.x - otherVector.x;
  425. result.y = this.y - otherVector.y;
  426. return this;
  427. };
  428. Vector2.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. return this;
  432. };
  433. Vector2.prototype.multiplyInPlace = function (otherVector) {
  434. this.x *= otherVector.x;
  435. this.y *= otherVector.y;
  436. return this;
  437. };
  438. Vector2.prototype.multiply = function (otherVector) {
  439. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  440. };
  441. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  442. result.x = this.x * otherVector.x;
  443. result.y = this.y * otherVector.y;
  444. return this;
  445. };
  446. Vector2.prototype.multiplyByFloats = function (x, y) {
  447. return new Vector2(this.x * x, this.y * y);
  448. };
  449. Vector2.prototype.divide = function (otherVector) {
  450. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  451. };
  452. Vector2.prototype.divideToRef = function (otherVector, result) {
  453. result.x = this.x / otherVector.x;
  454. result.y = this.y / otherVector.y;
  455. return this;
  456. };
  457. Vector2.prototype.negate = function () {
  458. return new Vector2(-this.x, -this.y);
  459. };
  460. Vector2.prototype.scaleInPlace = function (scale) {
  461. this.x *= scale;
  462. this.y *= scale;
  463. return this;
  464. };
  465. Vector2.prototype.scale = function (scale) {
  466. return new Vector2(this.x * scale, this.y * scale);
  467. };
  468. Vector2.prototype.equals = function (otherVector) {
  469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  470. };
  471. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  472. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  473. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  474. };
  475. // Properties
  476. Vector2.prototype.length = function () {
  477. return Math.sqrt(this.x * this.x + this.y * this.y);
  478. };
  479. Vector2.prototype.lengthSquared = function () {
  480. return (this.x * this.x + this.y * this.y);
  481. };
  482. // Methods
  483. Vector2.prototype.normalize = function () {
  484. var len = this.length();
  485. if (len === 0)
  486. return this;
  487. var num = 1.0 / len;
  488. this.x *= num;
  489. this.y *= num;
  490. return this;
  491. };
  492. Vector2.prototype.clone = function () {
  493. return new Vector2(this.x, this.y);
  494. };
  495. // Statics
  496. Vector2.Zero = function () {
  497. return new Vector2(0, 0);
  498. };
  499. Vector2.FromArray = function (array, offset) {
  500. if (offset === void 0) { offset = 0; }
  501. return new Vector2(array[offset], array[offset + 1]);
  502. };
  503. Vector2.FromArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. };
  507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  508. var squared = amount * amount;
  509. var cubed = amount * squared;
  510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  516. return new Vector2(x, y);
  517. };
  518. Vector2.Clamp = function (value, min, max) {
  519. var x = value.x;
  520. x = (x > max.x) ? max.x : x;
  521. x = (x < min.x) ? min.x : x;
  522. var y = value.y;
  523. y = (y > max.y) ? max.y : y;
  524. y = (y < min.y) ? min.y : y;
  525. return new Vector2(x, y);
  526. };
  527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  528. var squared = amount * amount;
  529. var cubed = amount * squared;
  530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  532. var part3 = (cubed - (2.0 * squared)) + amount;
  533. var part4 = cubed - squared;
  534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  536. return new Vector2(x, y);
  537. };
  538. Vector2.Lerp = function (start, end, amount) {
  539. var x = start.x + ((end.x - start.x) * amount);
  540. var y = start.y + ((end.y - start.y) * amount);
  541. return new Vector2(x, y);
  542. };
  543. Vector2.Dot = function (left, right) {
  544. return left.x * right.x + left.y * right.y;
  545. };
  546. Vector2.Normalize = function (vector) {
  547. var newVector = vector.clone();
  548. newVector.normalize();
  549. return newVector;
  550. };
  551. Vector2.Minimize = function (left, right) {
  552. var x = (left.x < right.x) ? left.x : right.x;
  553. var y = (left.y < right.y) ? left.y : right.y;
  554. return new Vector2(x, y);
  555. };
  556. Vector2.Maximize = function (left, right) {
  557. var x = (left.x > right.x) ? left.x : right.x;
  558. var y = (left.y > right.y) ? left.y : right.y;
  559. return new Vector2(x, y);
  560. };
  561. Vector2.Transform = function (vector, transformation) {
  562. var r = Vector2.Zero();
  563. Vector2.TransformToRef(vector, transformation, r);
  564. return r;
  565. };
  566. Vector2.TransformToRef = function (vector, transformation, result) {
  567. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  568. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  569. result.x = x;
  570. result.y = y;
  571. };
  572. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  573. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  574. var sign = a < 0 ? -1 : 1;
  575. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  576. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  577. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  578. };
  579. Vector2.Distance = function (value1, value2) {
  580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  581. };
  582. Vector2.DistanceSquared = function (value1, value2) {
  583. var x = value1.x - value2.x;
  584. var y = value1.y - value2.y;
  585. return (x * x) + (y * y);
  586. };
  587. Vector2.Center = function (value1, value2) {
  588. var center = value1.add(value2);
  589. center.scaleInPlace(0.5);
  590. return center;
  591. };
  592. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  593. var l2 = Vector2.DistanceSquared(segA, segB);
  594. if (l2 === 0.0) {
  595. return Vector2.Distance(p, segA);
  596. }
  597. var v = segB.subtract(segA);
  598. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  599. var proj = segA.add(v.multiplyByFloats(t, t));
  600. return Vector2.Distance(p, proj);
  601. };
  602. return Vector2;
  603. }());
  604. BABYLON.Vector2 = Vector2;
  605. var Vector3 = (function () {
  606. function Vector3(x, y, z) {
  607. this.x = x;
  608. this.y = y;
  609. this.z = z;
  610. }
  611. Vector3.prototype.toString = function () {
  612. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  613. };
  614. Vector3.prototype.getClassName = function () {
  615. return "Vector3";
  616. };
  617. Vector3.prototype.getHashCode = function () {
  618. var hash = this.x || 0;
  619. hash = (hash * 397) ^ (this.y || 0);
  620. hash = (hash * 397) ^ (this.z || 0);
  621. return hash;
  622. };
  623. // Operators
  624. Vector3.prototype.asArray = function () {
  625. var result = [];
  626. this.toArray(result, 0);
  627. return result;
  628. };
  629. Vector3.prototype.toArray = function (array, index) {
  630. if (index === void 0) { index = 0; }
  631. array[index] = this.x;
  632. array[index + 1] = this.y;
  633. array[index + 2] = this.z;
  634. return this;
  635. };
  636. Vector3.prototype.toQuaternion = function () {
  637. var result = new Quaternion(0, 0, 0, 1);
  638. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  639. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  640. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  641. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  642. var cosy = Math.cos(this.y * 0.5);
  643. var siny = Math.sin(this.y * 0.5);
  644. result.x = coszMinusx * siny;
  645. result.y = -sinzMinusx * siny;
  646. result.z = sinxPlusz * cosy;
  647. result.w = cosxPlusz * cosy;
  648. return result;
  649. };
  650. Vector3.prototype.addInPlace = function (otherVector) {
  651. this.x += otherVector.x;
  652. this.y += otherVector.y;
  653. this.z += otherVector.z;
  654. return this;
  655. };
  656. Vector3.prototype.add = function (otherVector) {
  657. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  658. };
  659. Vector3.prototype.addToRef = function (otherVector, result) {
  660. result.x = this.x + otherVector.x;
  661. result.y = this.y + otherVector.y;
  662. result.z = this.z + otherVector.z;
  663. return this;
  664. };
  665. Vector3.prototype.subtractInPlace = function (otherVector) {
  666. this.x -= otherVector.x;
  667. this.y -= otherVector.y;
  668. this.z -= otherVector.z;
  669. return this;
  670. };
  671. Vector3.prototype.subtract = function (otherVector) {
  672. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  673. };
  674. Vector3.prototype.subtractToRef = function (otherVector, result) {
  675. result.x = this.x - otherVector.x;
  676. result.y = this.y - otherVector.y;
  677. result.z = this.z - otherVector.z;
  678. return this;
  679. };
  680. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  681. return new Vector3(this.x - x, this.y - y, this.z - z);
  682. };
  683. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  684. result.x = this.x - x;
  685. result.y = this.y - y;
  686. result.z = this.z - z;
  687. return this;
  688. };
  689. Vector3.prototype.negate = function () {
  690. return new Vector3(-this.x, -this.y, -this.z);
  691. };
  692. Vector3.prototype.scaleInPlace = function (scale) {
  693. this.x *= scale;
  694. this.y *= scale;
  695. this.z *= scale;
  696. return this;
  697. };
  698. Vector3.prototype.scale = function (scale) {
  699. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  700. };
  701. Vector3.prototype.scaleToRef = function (scale, result) {
  702. result.x = this.x * scale;
  703. result.y = this.y * scale;
  704. result.z = this.z * scale;
  705. };
  706. Vector3.prototype.equals = function (otherVector) {
  707. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  708. };
  709. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  710. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  711. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  712. };
  713. Vector3.prototype.equalsToFloats = function (x, y, z) {
  714. return this.x === x && this.y === y && this.z === z;
  715. };
  716. Vector3.prototype.multiplyInPlace = function (otherVector) {
  717. this.x *= otherVector.x;
  718. this.y *= otherVector.y;
  719. this.z *= otherVector.z;
  720. return this;
  721. };
  722. Vector3.prototype.multiply = function (otherVector) {
  723. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  724. };
  725. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  726. result.x = this.x * otherVector.x;
  727. result.y = this.y * otherVector.y;
  728. result.z = this.z * otherVector.z;
  729. return this;
  730. };
  731. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  732. return new Vector3(this.x * x, this.y * y, this.z * z);
  733. };
  734. Vector3.prototype.divide = function (otherVector) {
  735. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  736. };
  737. Vector3.prototype.divideToRef = function (otherVector, result) {
  738. result.x = this.x / otherVector.x;
  739. result.y = this.y / otherVector.y;
  740. result.z = this.z / otherVector.z;
  741. return this;
  742. };
  743. Vector3.prototype.MinimizeInPlace = function (other) {
  744. if (other.x < this.x)
  745. this.x = other.x;
  746. if (other.y < this.y)
  747. this.y = other.y;
  748. if (other.z < this.z)
  749. this.z = other.z;
  750. return this;
  751. };
  752. Vector3.prototype.MaximizeInPlace = function (other) {
  753. if (other.x > this.x)
  754. this.x = other.x;
  755. if (other.y > this.y)
  756. this.y = other.y;
  757. if (other.z > this.z)
  758. this.z = other.z;
  759. return this;
  760. };
  761. // Properties
  762. Vector3.prototype.length = function () {
  763. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  764. };
  765. Vector3.prototype.lengthSquared = function () {
  766. return (this.x * this.x + this.y * this.y + this.z * this.z);
  767. };
  768. // Methods
  769. Vector3.prototype.normalize = function () {
  770. var len = this.length();
  771. if (len === 0 || len === 1.0)
  772. return this;
  773. var num = 1.0 / len;
  774. this.x *= num;
  775. this.y *= num;
  776. this.z *= num;
  777. return this;
  778. };
  779. Vector3.prototype.clone = function () {
  780. return new Vector3(this.x, this.y, this.z);
  781. };
  782. Vector3.prototype.copyFrom = function (source) {
  783. this.x = source.x;
  784. this.y = source.y;
  785. this.z = source.z;
  786. return this;
  787. };
  788. Vector3.prototype.copyFromFloats = function (x, y, z) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. return this;
  793. };
  794. // Statics
  795. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  796. var d0 = Vector3.Dot(vector0, axis) - size;
  797. var d1 = Vector3.Dot(vector1, axis) - size;
  798. var s = d0 / (d0 - d1);
  799. return s;
  800. };
  801. Vector3.FromArray = function (array, offset) {
  802. if (!offset) {
  803. offset = 0;
  804. }
  805. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  806. };
  807. Vector3.FromFloatArray = function (array, offset) {
  808. if (!offset) {
  809. offset = 0;
  810. }
  811. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  812. };
  813. Vector3.FromArrayToRef = function (array, offset, result) {
  814. result.x = array[offset];
  815. result.y = array[offset + 1];
  816. result.z = array[offset + 2];
  817. };
  818. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  819. result.x = array[offset];
  820. result.y = array[offset + 1];
  821. result.z = array[offset + 2];
  822. };
  823. Vector3.FromFloatsToRef = function (x, y, z, result) {
  824. result.x = x;
  825. result.y = y;
  826. result.z = z;
  827. };
  828. Vector3.Zero = function () {
  829. return new Vector3(0, 0, 0);
  830. };
  831. Vector3.Up = function () {
  832. return new Vector3(0, 1.0, 0);
  833. };
  834. Vector3.Forward = function () {
  835. return new Vector3(0, 0, 1.0);
  836. };
  837. Vector3.Right = function () {
  838. return new Vector3(1.0, 0, 0);
  839. };
  840. Vector3.Left = function () {
  841. return new Vector3(-1.0, 0, 0);
  842. };
  843. Vector3.TransformCoordinates = function (vector, transformation) {
  844. var result = Vector3.Zero();
  845. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  846. return result;
  847. };
  848. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  849. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  850. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  851. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  852. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  853. result.x = x / w;
  854. result.y = y / w;
  855. result.z = z / w;
  856. };
  857. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  858. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  859. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  860. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  861. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  862. result.x = rx / rw;
  863. result.y = ry / rw;
  864. result.z = rz / rw;
  865. };
  866. Vector3.TransformNormal = function (vector, transformation) {
  867. var result = Vector3.Zero();
  868. Vector3.TransformNormalToRef(vector, transformation, result);
  869. return result;
  870. };
  871. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  872. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  873. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  874. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  875. result.x = x;
  876. result.y = y;
  877. result.z = z;
  878. };
  879. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  880. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  881. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  882. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  883. };
  884. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  885. var squared = amount * amount;
  886. var cubed = amount * squared;
  887. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  888. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  889. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  890. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  891. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  892. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  893. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  894. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  895. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  896. return new Vector3(x, y, z);
  897. };
  898. Vector3.Clamp = function (value, min, max) {
  899. var x = value.x;
  900. x = (x > max.x) ? max.x : x;
  901. x = (x < min.x) ? min.x : x;
  902. var y = value.y;
  903. y = (y > max.y) ? max.y : y;
  904. y = (y < min.y) ? min.y : y;
  905. var z = value.z;
  906. z = (z > max.z) ? max.z : z;
  907. z = (z < min.z) ? min.z : z;
  908. return new Vector3(x, y, z);
  909. };
  910. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  911. var squared = amount * amount;
  912. var cubed = amount * squared;
  913. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  914. var part2 = (-2.0 * cubed) + (3.0 * squared);
  915. var part3 = (cubed - (2.0 * squared)) + amount;
  916. var part4 = cubed - squared;
  917. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  918. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  919. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  920. return new Vector3(x, y, z);
  921. };
  922. Vector3.Lerp = function (start, end, amount) {
  923. var result = new Vector3(0, 0, 0);
  924. Vector3.LerpToRef(start, end, amount, result);
  925. return result;
  926. };
  927. Vector3.LerpToRef = function (start, end, amount, result) {
  928. result.x = start.x + ((end.x - start.x) * amount);
  929. result.y = start.y + ((end.y - start.y) * amount);
  930. result.z = start.z + ((end.z - start.z) * amount);
  931. };
  932. Vector3.Dot = function (left, right) {
  933. return (left.x * right.x + left.y * right.y + left.z * right.z);
  934. };
  935. Vector3.Cross = function (left, right) {
  936. var result = Vector3.Zero();
  937. Vector3.CrossToRef(left, right, result);
  938. return result;
  939. };
  940. Vector3.CrossToRef = function (left, right, result) {
  941. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  942. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  943. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  944. result.copyFrom(Tmp.Vector3[0]);
  945. };
  946. Vector3.Normalize = function (vector) {
  947. var result = Vector3.Zero();
  948. Vector3.NormalizeToRef(vector, result);
  949. return result;
  950. };
  951. Vector3.NormalizeToRef = function (vector, result) {
  952. result.copyFrom(vector);
  953. result.normalize();
  954. };
  955. Vector3.Project = function (vector, world, transform, viewport) {
  956. var cw = viewport.width;
  957. var ch = viewport.height;
  958. var cx = viewport.x;
  959. var cy = viewport.y;
  960. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  961. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  962. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  963. world.multiplyToRef(transform, matrix);
  964. matrix.multiplyToRef(viewportMatrix, matrix);
  965. return Vector3.TransformCoordinates(vector, matrix);
  966. };
  967. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  968. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  969. world.multiplyToRef(transform, matrix);
  970. matrix.invert();
  971. source.x = source.x / viewportWidth * 2 - 1;
  972. source.y = -(source.y / viewportHeight * 2 - 1);
  973. var vector = Vector3.TransformCoordinates(source, matrix);
  974. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  975. if (MathTools.WithinEpsilon(num, 1.0)) {
  976. vector = vector.scale(1.0 / num);
  977. }
  978. return vector;
  979. };
  980. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  981. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  982. world.multiplyToRef(view, matrix);
  983. matrix.multiplyToRef(projection, matrix);
  984. matrix.invert();
  985. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  986. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  987. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  988. if (MathTools.WithinEpsilon(num, 1.0)) {
  989. vector = vector.scale(1.0 / num);
  990. }
  991. return vector;
  992. };
  993. Vector3.Minimize = function (left, right) {
  994. var min = left.clone();
  995. min.MinimizeInPlace(right);
  996. return min;
  997. };
  998. Vector3.Maximize = function (left, right) {
  999. var max = left.clone();
  1000. max.MaximizeInPlace(right);
  1001. return max;
  1002. };
  1003. Vector3.Distance = function (value1, value2) {
  1004. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1005. };
  1006. Vector3.DistanceSquared = function (value1, value2) {
  1007. var x = value1.x - value2.x;
  1008. var y = value1.y - value2.y;
  1009. var z = value1.z - value2.z;
  1010. return (x * x) + (y * y) + (z * z);
  1011. };
  1012. Vector3.Center = function (value1, value2) {
  1013. var center = value1.add(value2);
  1014. center.scaleInPlace(0.5);
  1015. return center;
  1016. };
  1017. /**
  1018. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1019. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1020. * to something in order to rotate it from its local system to the given target system.
  1021. */
  1022. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1023. var rotation = Vector3.Zero();
  1024. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1025. return rotation;
  1026. };
  1027. /**
  1028. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1029. */
  1030. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1031. var u = axis1.normalize();
  1032. var w = axis3.normalize();
  1033. // world axis
  1034. var X = Axis.X;
  1035. var Y = Axis.Y;
  1036. // equation unknowns and vars
  1037. var yaw = 0.0;
  1038. var pitch = 0.0;
  1039. var roll = 0.0;
  1040. var x = 0.0;
  1041. var y = 0.0;
  1042. var z = 0.0;
  1043. var t = 0.0;
  1044. var sign = -1.0;
  1045. var nbRevert = 0;
  1046. var cross = Tmp.Vector3[0];
  1047. var dot = 0.0;
  1048. // step 1 : rotation around w
  1049. // Rv3(u) = u1, and u1 belongs to plane xOz
  1050. // Rv3(w) = w1 = w invariant
  1051. var u1 = Tmp.Vector3[1];
  1052. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1053. z = 1.0;
  1054. }
  1055. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = w.z / w.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. u1.x = x;
  1064. u1.y = y;
  1065. u1.z = z;
  1066. u1.normalize();
  1067. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1068. cross.normalize();
  1069. if (Vector3.Dot(w, cross) < 0) {
  1070. sign = 1.0;
  1071. }
  1072. dot = Vector3.Dot(u, u1);
  1073. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1074. roll = Math.acos(dot) * sign;
  1075. if (Vector3.Dot(u1, X) < 0) {
  1076. roll = Math.PI + roll;
  1077. u1 = u1.scaleInPlace(-1);
  1078. nbRevert++;
  1079. }
  1080. // step 2 : rotate around u1
  1081. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1082. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1083. var w2 = Tmp.Vector3[2];
  1084. var v2 = Tmp.Vector3[3];
  1085. x = 0.0;
  1086. y = 0.0;
  1087. z = 0.0;
  1088. sign = -1.0;
  1089. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1090. x = 1.0;
  1091. }
  1092. else {
  1093. t = u1.z / u1.x;
  1094. x = -t * Math.sqrt(1 / (1 + t * t));
  1095. z = Math.sqrt(1 / (1 + t * t));
  1096. }
  1097. w2.x = x;
  1098. w2.y = y;
  1099. w2.z = z;
  1100. w2.normalize();
  1101. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1102. v2.normalize();
  1103. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1104. cross.normalize();
  1105. if (Vector3.Dot(u1, cross) < 0) {
  1106. sign = 1.0;
  1107. }
  1108. dot = Vector3.Dot(w, w2);
  1109. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1110. pitch = Math.acos(dot) * sign;
  1111. if (Vector3.Dot(v2, Y) < 0) {
  1112. pitch = Math.PI + pitch;
  1113. nbRevert++;
  1114. }
  1115. // step 3 : rotate around v2
  1116. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1117. sign = -1.0;
  1118. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1119. cross.normalize();
  1120. if (Vector3.Dot(cross, Y) < 0) {
  1121. sign = 1.0;
  1122. }
  1123. dot = Vector3.Dot(u1, X);
  1124. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1125. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1126. if (dot < 0 && nbRevert < 2) {
  1127. yaw = Math.PI + yaw;
  1128. }
  1129. ref.x = pitch;
  1130. ref.y = yaw;
  1131. ref.z = roll;
  1132. };
  1133. return Vector3;
  1134. }());
  1135. BABYLON.Vector3 = Vector3;
  1136. //Vector4 class created for EulerAngle class conversion to Quaternion
  1137. var Vector4 = (function () {
  1138. function Vector4(x, y, z, w) {
  1139. this.x = x;
  1140. this.y = y;
  1141. this.z = z;
  1142. this.w = w;
  1143. }
  1144. Vector4.prototype.toString = function () {
  1145. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1146. };
  1147. Vector4.prototype.getClassName = function () {
  1148. return "Vector4";
  1149. };
  1150. Vector4.prototype.getHashCode = function () {
  1151. var hash = this.x || 0;
  1152. hash = (hash * 397) ^ (this.y || 0);
  1153. hash = (hash * 397) ^ (this.z || 0);
  1154. hash = (hash * 397) ^ (this.w || 0);
  1155. return hash;
  1156. };
  1157. // Operators
  1158. Vector4.prototype.asArray = function () {
  1159. var result = [];
  1160. this.toArray(result, 0);
  1161. return result;
  1162. };
  1163. Vector4.prototype.toArray = function (array, index) {
  1164. if (index === undefined) {
  1165. index = 0;
  1166. }
  1167. array[index] = this.x;
  1168. array[index + 1] = this.y;
  1169. array[index + 2] = this.z;
  1170. array[index + 3] = this.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.addInPlace = function (otherVector) {
  1174. this.x += otherVector.x;
  1175. this.y += otherVector.y;
  1176. this.z += otherVector.z;
  1177. this.w += otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.add = function (otherVector) {
  1181. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1182. };
  1183. Vector4.prototype.addToRef = function (otherVector, result) {
  1184. result.x = this.x + otherVector.x;
  1185. result.y = this.y + otherVector.y;
  1186. result.z = this.z + otherVector.z;
  1187. result.w = this.w + otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractInPlace = function (otherVector) {
  1191. this.x -= otherVector.x;
  1192. this.y -= otherVector.y;
  1193. this.z -= otherVector.z;
  1194. this.w -= otherVector.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.subtract = function (otherVector) {
  1198. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1199. };
  1200. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1201. result.x = this.x - otherVector.x;
  1202. result.y = this.y - otherVector.y;
  1203. result.z = this.z - otherVector.z;
  1204. result.w = this.w - otherVector.w;
  1205. return this;
  1206. };
  1207. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1208. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1209. };
  1210. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1211. result.x = this.x - x;
  1212. result.y = this.y - y;
  1213. result.z = this.z - z;
  1214. result.w = this.w - w;
  1215. return this;
  1216. };
  1217. Vector4.prototype.negate = function () {
  1218. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1219. };
  1220. Vector4.prototype.scaleInPlace = function (scale) {
  1221. this.x *= scale;
  1222. this.y *= scale;
  1223. this.z *= scale;
  1224. this.w *= scale;
  1225. return this;
  1226. };
  1227. Vector4.prototype.scale = function (scale) {
  1228. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1229. };
  1230. Vector4.prototype.scaleToRef = function (scale, result) {
  1231. result.x = this.x * scale;
  1232. result.y = this.y * scale;
  1233. result.z = this.z * scale;
  1234. result.w = this.w * scale;
  1235. };
  1236. Vector4.prototype.equals = function (otherVector) {
  1237. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1238. };
  1239. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1240. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1241. return otherVector
  1242. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1243. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1244. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1245. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1246. };
  1247. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1248. return this.x === x && this.y === y && this.z === z && this.w === w;
  1249. };
  1250. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1251. this.x *= otherVector.x;
  1252. this.y *= otherVector.y;
  1253. this.z *= otherVector.z;
  1254. this.w *= otherVector.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.multiply = function (otherVector) {
  1258. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1259. };
  1260. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1261. result.x = this.x * otherVector.x;
  1262. result.y = this.y * otherVector.y;
  1263. result.z = this.z * otherVector.z;
  1264. result.w = this.w * otherVector.w;
  1265. return this;
  1266. };
  1267. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1268. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1269. };
  1270. Vector4.prototype.divide = function (otherVector) {
  1271. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1272. };
  1273. Vector4.prototype.divideToRef = function (otherVector, result) {
  1274. result.x = this.x / otherVector.x;
  1275. result.y = this.y / otherVector.y;
  1276. result.z = this.z / otherVector.z;
  1277. result.w = this.w / otherVector.w;
  1278. return this;
  1279. };
  1280. Vector4.prototype.MinimizeInPlace = function (other) {
  1281. if (other.x < this.x)
  1282. this.x = other.x;
  1283. if (other.y < this.y)
  1284. this.y = other.y;
  1285. if (other.z < this.z)
  1286. this.z = other.z;
  1287. if (other.w < this.w)
  1288. this.w = other.w;
  1289. return this;
  1290. };
  1291. Vector4.prototype.MaximizeInPlace = function (other) {
  1292. if (other.x > this.x)
  1293. this.x = other.x;
  1294. if (other.y > this.y)
  1295. this.y = other.y;
  1296. if (other.z > this.z)
  1297. this.z = other.z;
  1298. if (other.w > this.w)
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. // Properties
  1303. Vector4.prototype.length = function () {
  1304. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1305. };
  1306. Vector4.prototype.lengthSquared = function () {
  1307. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1308. };
  1309. // Methods
  1310. Vector4.prototype.normalize = function () {
  1311. var len = this.length();
  1312. if (len === 0)
  1313. return this;
  1314. var num = 1.0 / len;
  1315. this.x *= num;
  1316. this.y *= num;
  1317. this.z *= num;
  1318. this.w *= num;
  1319. return this;
  1320. };
  1321. Vector4.prototype.toVector3 = function () {
  1322. return new Vector3(this.x, this.y, this.z);
  1323. };
  1324. Vector4.prototype.clone = function () {
  1325. return new Vector4(this.x, this.y, this.z, this.w);
  1326. };
  1327. Vector4.prototype.copyFrom = function (source) {
  1328. this.x = source.x;
  1329. this.y = source.y;
  1330. this.z = source.z;
  1331. this.w = source.w;
  1332. return this;
  1333. };
  1334. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1335. this.x = x;
  1336. this.y = y;
  1337. this.z = z;
  1338. this.w = w;
  1339. return this;
  1340. };
  1341. // Statics
  1342. Vector4.FromArray = function (array, offset) {
  1343. if (!offset) {
  1344. offset = 0;
  1345. }
  1346. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1347. };
  1348. Vector4.FromArrayToRef = function (array, offset, result) {
  1349. result.x = array[offset];
  1350. result.y = array[offset + 1];
  1351. result.z = array[offset + 2];
  1352. result.w = array[offset + 3];
  1353. };
  1354. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. result.w = array[offset + 3];
  1359. };
  1360. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1361. result.x = x;
  1362. result.y = y;
  1363. result.z = z;
  1364. result.w = w;
  1365. };
  1366. Vector4.Zero = function () {
  1367. return new Vector4(0, 0, 0, 0);
  1368. };
  1369. Vector4.Normalize = function (vector) {
  1370. var result = Vector4.Zero();
  1371. Vector4.NormalizeToRef(vector, result);
  1372. return result;
  1373. };
  1374. Vector4.NormalizeToRef = function (vector, result) {
  1375. result.copyFrom(vector);
  1376. result.normalize();
  1377. };
  1378. Vector4.Minimize = function (left, right) {
  1379. var min = left.clone();
  1380. min.MinimizeInPlace(right);
  1381. return min;
  1382. };
  1383. Vector4.Maximize = function (left, right) {
  1384. var max = left.clone();
  1385. max.MaximizeInPlace(right);
  1386. return max;
  1387. };
  1388. Vector4.Distance = function (value1, value2) {
  1389. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1390. };
  1391. Vector4.DistanceSquared = function (value1, value2) {
  1392. var x = value1.x - value2.x;
  1393. var y = value1.y - value2.y;
  1394. var z = value1.z - value2.z;
  1395. var w = value1.w - value2.w;
  1396. return (x * x) + (y * y) + (z * z) + (w * w);
  1397. };
  1398. Vector4.Center = function (value1, value2) {
  1399. var center = value1.add(value2);
  1400. center.scaleInPlace(0.5);
  1401. return center;
  1402. };
  1403. return Vector4;
  1404. }());
  1405. BABYLON.Vector4 = Vector4;
  1406. var Size = (function () {
  1407. function Size(width, height) {
  1408. this.width = width;
  1409. this.height = height;
  1410. }
  1411. Size.prototype.toString = function () {
  1412. return "{W: " + this.width + ", H: " + this.height + "}";
  1413. };
  1414. Size.prototype.getClassName = function () {
  1415. return "Size";
  1416. };
  1417. Size.prototype.getHashCode = function () {
  1418. var hash = this.width || 0;
  1419. hash = (hash * 397) ^ (this.height || 0);
  1420. return hash;
  1421. };
  1422. Size.prototype.copyFrom = function (src) {
  1423. this.width = src.width;
  1424. this.height = src.height;
  1425. };
  1426. Size.prototype.copyFromFloats = function (width, height) {
  1427. this.width = width;
  1428. this.height = height;
  1429. };
  1430. Size.prototype.multiplyByFloats = function (w, h) {
  1431. return new Size(this.width * w, this.height * h);
  1432. };
  1433. Size.prototype.clone = function () {
  1434. return new Size(this.width, this.height);
  1435. };
  1436. Size.prototype.equals = function (other) {
  1437. if (!other) {
  1438. return false;
  1439. }
  1440. return (this.width === other.width) && (this.height === other.height);
  1441. };
  1442. Object.defineProperty(Size.prototype, "surface", {
  1443. get: function () {
  1444. return this.width * this.height;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Size.Zero = function () {
  1450. return new Size(0, 0);
  1451. };
  1452. Size.prototype.add = function (otherSize) {
  1453. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1454. return r;
  1455. };
  1456. Size.prototype.subtract = function (otherSize) {
  1457. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1458. return r;
  1459. };
  1460. Size.Lerp = function (start, end, amount) {
  1461. var w = start.width + ((end.width - start.width) * amount);
  1462. var h = start.height + ((end.height - start.height) * amount);
  1463. return new Size(w, h);
  1464. };
  1465. return Size;
  1466. }());
  1467. BABYLON.Size = Size;
  1468. var Quaternion = (function () {
  1469. function Quaternion(x, y, z, w) {
  1470. if (x === void 0) { x = 0; }
  1471. if (y === void 0) { y = 0; }
  1472. if (z === void 0) { z = 0; }
  1473. if (w === void 0) { w = 1; }
  1474. this.x = x;
  1475. this.y = y;
  1476. this.z = z;
  1477. this.w = w;
  1478. }
  1479. Quaternion.prototype.toString = function () {
  1480. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1481. };
  1482. Quaternion.prototype.getClassName = function () {
  1483. return "Quaternion";
  1484. };
  1485. Quaternion.prototype.getHashCode = function () {
  1486. var hash = this.x || 0;
  1487. hash = (hash * 397) ^ (this.y || 0);
  1488. hash = (hash * 397) ^ (this.z || 0);
  1489. hash = (hash * 397) ^ (this.w || 0);
  1490. return hash;
  1491. };
  1492. Quaternion.prototype.asArray = function () {
  1493. return [this.x, this.y, this.z, this.w];
  1494. };
  1495. Quaternion.prototype.equals = function (otherQuaternion) {
  1496. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1497. };
  1498. Quaternion.prototype.clone = function () {
  1499. return new Quaternion(this.x, this.y, this.z, this.w);
  1500. };
  1501. Quaternion.prototype.copyFrom = function (other) {
  1502. this.x = other.x;
  1503. this.y = other.y;
  1504. this.z = other.z;
  1505. this.w = other.w;
  1506. return this;
  1507. };
  1508. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1509. this.x = x;
  1510. this.y = y;
  1511. this.z = z;
  1512. this.w = w;
  1513. return this;
  1514. };
  1515. Quaternion.prototype.add = function (other) {
  1516. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1517. };
  1518. Quaternion.prototype.subtract = function (other) {
  1519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1520. };
  1521. Quaternion.prototype.scale = function (value) {
  1522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1523. };
  1524. Quaternion.prototype.multiply = function (q1) {
  1525. var result = new Quaternion(0, 0, 0, 1.0);
  1526. this.multiplyToRef(q1, result);
  1527. return result;
  1528. };
  1529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1534. result.copyFromFloats(x, y, z, w);
  1535. return this;
  1536. };
  1537. Quaternion.prototype.multiplyInPlace = function (q1) {
  1538. this.multiplyToRef(q1, this);
  1539. return this;
  1540. };
  1541. Quaternion.prototype.conjugateToRef = function (ref) {
  1542. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1543. return this;
  1544. };
  1545. Quaternion.prototype.conjugateInPlace = function () {
  1546. this.x *= -1;
  1547. this.y *= -1;
  1548. this.z *= -1;
  1549. return this;
  1550. };
  1551. Quaternion.prototype.conjugate = function () {
  1552. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.length = function () {
  1556. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1557. };
  1558. Quaternion.prototype.normalize = function () {
  1559. var length = 1.0 / this.length();
  1560. this.x *= length;
  1561. this.y *= length;
  1562. this.z *= length;
  1563. this.w *= length;
  1564. return this;
  1565. };
  1566. Quaternion.prototype.toEulerAngles = function (order) {
  1567. if (order === void 0) { order = "YZX"; }
  1568. var result = Vector3.Zero();
  1569. this.toEulerAnglesToRef(result, order);
  1570. return result;
  1571. };
  1572. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1573. if (order === void 0) { order = "YZX"; }
  1574. var qz = this.z;
  1575. var qx = this.x;
  1576. var qy = this.y;
  1577. var qw = this.w;
  1578. var sqw = qw * qw;
  1579. var sqz = qz * qz;
  1580. var sqx = qx * qx;
  1581. var sqy = qy * qy;
  1582. var zAxisY = qy * qz - qx * qw;
  1583. var limit = .4999999;
  1584. if (zAxisY < -limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else if (zAxisY > limit) {
  1590. result.y = 2 * Math.atan2(qy, qw);
  1591. result.x = -Math.PI / 2;
  1592. result.z = 0;
  1593. }
  1594. else {
  1595. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1596. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1597. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1598. }
  1599. return this;
  1600. };
  1601. Quaternion.prototype.toRotationMatrix = function (result) {
  1602. var xx = this.x * this.x;
  1603. var yy = this.y * this.y;
  1604. var zz = this.z * this.z;
  1605. var xy = this.x * this.y;
  1606. var zw = this.z * this.w;
  1607. var zx = this.z * this.x;
  1608. var yw = this.y * this.w;
  1609. var yz = this.y * this.z;
  1610. var xw = this.x * this.w;
  1611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1612. result.m[1] = 2.0 * (xy + zw);
  1613. result.m[2] = 2.0 * (zx - yw);
  1614. result.m[3] = 0;
  1615. result.m[4] = 2.0 * (xy - zw);
  1616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1617. result.m[6] = 2.0 * (yz + xw);
  1618. result.m[7] = 0;
  1619. result.m[8] = 2.0 * (zx + yw);
  1620. result.m[9] = 2.0 * (yz - xw);
  1621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1622. result.m[11] = 0;
  1623. result.m[12] = 0;
  1624. result.m[13] = 0;
  1625. result.m[14] = 0;
  1626. result.m[15] = 1.0;
  1627. return this;
  1628. };
  1629. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1630. Quaternion.FromRotationMatrixToRef(matrix, this);
  1631. return this;
  1632. };
  1633. // Statics
  1634. Quaternion.FromRotationMatrix = function (matrix) {
  1635. var result = new Quaternion();
  1636. Quaternion.FromRotationMatrixToRef(matrix, result);
  1637. return result;
  1638. };
  1639. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1640. var data = matrix.m;
  1641. var m11 = data[0], m12 = data[4], m13 = data[8];
  1642. var m21 = data[1], m22 = data[5], m23 = data[9];
  1643. var m31 = data[2], m32 = data[6], m33 = data[10];
  1644. var trace = m11 + m22 + m33;
  1645. var s;
  1646. if (trace > 0) {
  1647. s = 0.5 / Math.sqrt(trace + 1.0);
  1648. result.w = 0.25 / s;
  1649. result.x = (m32 - m23) * s;
  1650. result.y = (m13 - m31) * s;
  1651. result.z = (m21 - m12) * s;
  1652. }
  1653. else if (m11 > m22 && m11 > m33) {
  1654. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1655. result.w = (m32 - m23) / s;
  1656. result.x = 0.25 * s;
  1657. result.y = (m12 + m21) / s;
  1658. result.z = (m13 + m31) / s;
  1659. }
  1660. else if (m22 > m33) {
  1661. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1662. result.w = (m13 - m31) / s;
  1663. result.x = (m12 + m21) / s;
  1664. result.y = 0.25 * s;
  1665. result.z = (m23 + m32) / s;
  1666. }
  1667. else {
  1668. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1669. result.w = (m21 - m12) / s;
  1670. result.x = (m13 + m31) / s;
  1671. result.y = (m23 + m32) / s;
  1672. result.z = 0.25 * s;
  1673. }
  1674. };
  1675. Quaternion.Inverse = function (q) {
  1676. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1677. };
  1678. Quaternion.Identity = function () {
  1679. return new Quaternion(0, 0, 0, 1);
  1680. };
  1681. Quaternion.RotationAxis = function (axis, angle) {
  1682. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1683. };
  1684. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1685. var sin = Math.sin(angle / 2);
  1686. axis.normalize();
  1687. result.w = Math.cos(angle / 2);
  1688. result.x = axis.x * sin;
  1689. result.y = axis.y * sin;
  1690. result.z = axis.z * sin;
  1691. return result;
  1692. };
  1693. Quaternion.FromArray = function (array, offset) {
  1694. if (!offset) {
  1695. offset = 0;
  1696. }
  1697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1698. };
  1699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1700. var q = new Quaternion();
  1701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1702. return q;
  1703. };
  1704. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1705. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1706. var halfRoll = roll * 0.5;
  1707. var halfPitch = pitch * 0.5;
  1708. var halfYaw = yaw * 0.5;
  1709. var sinRoll = Math.sin(halfRoll);
  1710. var cosRoll = Math.cos(halfRoll);
  1711. var sinPitch = Math.sin(halfPitch);
  1712. var cosPitch = Math.cos(halfPitch);
  1713. var sinYaw = Math.sin(halfYaw);
  1714. var cosYaw = Math.cos(halfYaw);
  1715. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1716. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1717. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1718. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1719. };
  1720. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1721. var result = new Quaternion();
  1722. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1723. return result;
  1724. };
  1725. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1726. // Produces a quaternion from Euler angles in the z-x-z orientation
  1727. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1728. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1729. var halfBeta = beta * 0.5;
  1730. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1732. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1734. };
  1735. Quaternion.Slerp = function (left, right, amount) {
  1736. var result = Quaternion.Identity();
  1737. Quaternion.SlerpToRef(left, right, amount, result);
  1738. return result;
  1739. };
  1740. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1741. var num2;
  1742. var num3;
  1743. var num = amount;
  1744. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1745. var flag = false;
  1746. if (num4 < 0) {
  1747. flag = true;
  1748. num4 = -num4;
  1749. }
  1750. if (num4 > 0.999999) {
  1751. num3 = 1 - num;
  1752. num2 = flag ? -num : num;
  1753. }
  1754. else {
  1755. var num5 = Math.acos(num4);
  1756. var num6 = (1.0 / Math.sin(num5));
  1757. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1758. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1759. }
  1760. result.x = (num3 * left.x) + (num2 * right.x);
  1761. result.y = (num3 * left.y) + (num2 * right.y);
  1762. result.z = (num3 * left.z) + (num2 * right.z);
  1763. result.w = (num3 * left.w) + (num2 * right.w);
  1764. };
  1765. return Quaternion;
  1766. }());
  1767. BABYLON.Quaternion = Quaternion;
  1768. var Matrix = (function () {
  1769. function Matrix() {
  1770. this.m = new Float32Array(16);
  1771. }
  1772. // Properties
  1773. Matrix.prototype.isIdentity = function () {
  1774. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1775. return false;
  1776. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1780. return false;
  1781. return true;
  1782. };
  1783. Matrix.prototype.determinant = function () {
  1784. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1785. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1786. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1787. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1788. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1789. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1790. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1791. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1792. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1793. };
  1794. // Methods
  1795. Matrix.prototype.toArray = function () {
  1796. return this.m;
  1797. };
  1798. Matrix.prototype.asArray = function () {
  1799. return this.toArray();
  1800. };
  1801. Matrix.prototype.invert = function () {
  1802. this.invertToRef(this);
  1803. return this;
  1804. };
  1805. Matrix.prototype.reset = function () {
  1806. for (var index = 0; index < 16; index++) {
  1807. this.m[index] = 0;
  1808. }
  1809. return this;
  1810. };
  1811. Matrix.prototype.add = function (other) {
  1812. var result = new Matrix();
  1813. this.addToRef(other, result);
  1814. return result;
  1815. };
  1816. Matrix.prototype.addToRef = function (other, result) {
  1817. for (var index = 0; index < 16; index++) {
  1818. result.m[index] = this.m[index] + other.m[index];
  1819. }
  1820. return this;
  1821. };
  1822. Matrix.prototype.addToSelf = function (other) {
  1823. for (var index = 0; index < 16; index++) {
  1824. this.m[index] += other.m[index];
  1825. }
  1826. return this;
  1827. };
  1828. Matrix.prototype.invertToRef = function (other) {
  1829. var l1 = this.m[0];
  1830. var l2 = this.m[1];
  1831. var l3 = this.m[2];
  1832. var l4 = this.m[3];
  1833. var l5 = this.m[4];
  1834. var l6 = this.m[5];
  1835. var l7 = this.m[6];
  1836. var l8 = this.m[7];
  1837. var l9 = this.m[8];
  1838. var l10 = this.m[9];
  1839. var l11 = this.m[10];
  1840. var l12 = this.m[11];
  1841. var l13 = this.m[12];
  1842. var l14 = this.m[13];
  1843. var l15 = this.m[14];
  1844. var l16 = this.m[15];
  1845. var l17 = (l11 * l16) - (l12 * l15);
  1846. var l18 = (l10 * l16) - (l12 * l14);
  1847. var l19 = (l10 * l15) - (l11 * l14);
  1848. var l20 = (l9 * l16) - (l12 * l13);
  1849. var l21 = (l9 * l15) - (l11 * l13);
  1850. var l22 = (l9 * l14) - (l10 * l13);
  1851. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1852. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1853. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1854. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1855. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1856. var l28 = (l7 * l16) - (l8 * l15);
  1857. var l29 = (l6 * l16) - (l8 * l14);
  1858. var l30 = (l6 * l15) - (l7 * l14);
  1859. var l31 = (l5 * l16) - (l8 * l13);
  1860. var l32 = (l5 * l15) - (l7 * l13);
  1861. var l33 = (l5 * l14) - (l6 * l13);
  1862. var l34 = (l7 * l12) - (l8 * l11);
  1863. var l35 = (l6 * l12) - (l8 * l10);
  1864. var l36 = (l6 * l11) - (l7 * l10);
  1865. var l37 = (l5 * l12) - (l8 * l9);
  1866. var l38 = (l5 * l11) - (l7 * l9);
  1867. var l39 = (l5 * l10) - (l6 * l9);
  1868. other.m[0] = l23 * l27;
  1869. other.m[4] = l24 * l27;
  1870. other.m[8] = l25 * l27;
  1871. other.m[12] = l26 * l27;
  1872. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1873. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1874. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1875. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1876. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1877. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1878. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1879. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1880. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1881. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1882. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1883. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1884. return this;
  1885. };
  1886. Matrix.prototype.setTranslation = function (vector3) {
  1887. this.m[12] = vector3.x;
  1888. this.m[13] = vector3.y;
  1889. this.m[14] = vector3.z;
  1890. return this;
  1891. };
  1892. Matrix.prototype.getTranslation = function () {
  1893. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1894. };
  1895. Matrix.prototype.multiply = function (other) {
  1896. var result = new Matrix();
  1897. this.multiplyToRef(other, result);
  1898. return result;
  1899. };
  1900. Matrix.prototype.copyFrom = function (other) {
  1901. for (var index = 0; index < 16; index++) {
  1902. this.m[index] = other.m[index];
  1903. }
  1904. return this;
  1905. };
  1906. Matrix.prototype.copyToArray = function (array, offset) {
  1907. if (offset === void 0) { offset = 0; }
  1908. for (var index = 0; index < 16; index++) {
  1909. array[offset + index] = this.m[index];
  1910. }
  1911. return this;
  1912. };
  1913. Matrix.prototype.multiplyToRef = function (other, result) {
  1914. this.multiplyToArray(other, result.m, 0);
  1915. return this;
  1916. };
  1917. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1918. var tm0 = this.m[0];
  1919. var tm1 = this.m[1];
  1920. var tm2 = this.m[2];
  1921. var tm3 = this.m[3];
  1922. var tm4 = this.m[4];
  1923. var tm5 = this.m[5];
  1924. var tm6 = this.m[6];
  1925. var tm7 = this.m[7];
  1926. var tm8 = this.m[8];
  1927. var tm9 = this.m[9];
  1928. var tm10 = this.m[10];
  1929. var tm11 = this.m[11];
  1930. var tm12 = this.m[12];
  1931. var tm13 = this.m[13];
  1932. var tm14 = this.m[14];
  1933. var tm15 = this.m[15];
  1934. var om0 = other.m[0];
  1935. var om1 = other.m[1];
  1936. var om2 = other.m[2];
  1937. var om3 = other.m[3];
  1938. var om4 = other.m[4];
  1939. var om5 = other.m[5];
  1940. var om6 = other.m[6];
  1941. var om7 = other.m[7];
  1942. var om8 = other.m[8];
  1943. var om9 = other.m[9];
  1944. var om10 = other.m[10];
  1945. var om11 = other.m[11];
  1946. var om12 = other.m[12];
  1947. var om13 = other.m[13];
  1948. var om14 = other.m[14];
  1949. var om15 = other.m[15];
  1950. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1951. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1952. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1953. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1954. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1955. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1956. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1957. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1958. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1959. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1960. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1961. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1962. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1963. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1964. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1965. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1966. return this;
  1967. };
  1968. Matrix.prototype.equals = function (value) {
  1969. return value &&
  1970. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1971. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1972. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1973. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1974. };
  1975. Matrix.prototype.clone = function () {
  1976. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1977. };
  1978. Matrix.prototype.getClassName = function () {
  1979. return "Matrix";
  1980. };
  1981. Matrix.prototype.getHashCode = function () {
  1982. var hash = this.m[0] || 0;
  1983. for (var i = 1; i < 16; i++) {
  1984. hash = (hash * 397) ^ (this.m[i] || 0);
  1985. }
  1986. return hash;
  1987. };
  1988. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1989. translation.x = this.m[12];
  1990. translation.y = this.m[13];
  1991. translation.z = this.m[14];
  1992. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1993. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1994. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1995. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1996. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1997. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1998. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1999. rotation.x = 0;
  2000. rotation.y = 0;
  2001. rotation.z = 0;
  2002. rotation.w = 1;
  2003. return false;
  2004. }
  2005. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, Tmp.Matrix[0]);
  2006. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2007. return true;
  2008. };
  2009. Matrix.prototype.getRotationMatrix = function () {
  2010. var result = Matrix.Identity();
  2011. this.getRotationMatrixToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2015. var m = this.m;
  2016. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2017. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2018. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2019. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2020. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2021. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2022. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  2023. };
  2024. // Statics
  2025. Matrix.FromArray = function (array, offset) {
  2026. var result = new Matrix();
  2027. if (!offset) {
  2028. offset = 0;
  2029. }
  2030. Matrix.FromArrayToRef(array, offset, result);
  2031. return result;
  2032. };
  2033. Matrix.FromArrayToRef = function (array, offset, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset];
  2036. }
  2037. };
  2038. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2039. for (var index = 0; index < 16; index++) {
  2040. result.m[index] = array[index + offset] * scale;
  2041. }
  2042. };
  2043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. };
  2061. Matrix.prototype.getRow = function (index) {
  2062. if (index < 0 || index > 3) {
  2063. return null;
  2064. }
  2065. var i = index * 4;
  2066. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2067. };
  2068. Matrix.prototype.setRow = function (index, row) {
  2069. if (index < 0 || index > 3) {
  2070. return this;
  2071. }
  2072. var i = index * 4;
  2073. this.m[i + 0] = row.x;
  2074. this.m[i + 1] = row.y;
  2075. this.m[i + 2] = row.z;
  2076. this.m[i + 3] = row.w;
  2077. return this;
  2078. };
  2079. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2080. var result = new Matrix();
  2081. result.m[0] = initialM11;
  2082. result.m[1] = initialM12;
  2083. result.m[2] = initialM13;
  2084. result.m[3] = initialM14;
  2085. result.m[4] = initialM21;
  2086. result.m[5] = initialM22;
  2087. result.m[6] = initialM23;
  2088. result.m[7] = initialM24;
  2089. result.m[8] = initialM31;
  2090. result.m[9] = initialM32;
  2091. result.m[10] = initialM33;
  2092. result.m[11] = initialM34;
  2093. result.m[12] = initialM41;
  2094. result.m[13] = initialM42;
  2095. result.m[14] = initialM43;
  2096. result.m[15] = initialM44;
  2097. return result;
  2098. };
  2099. Matrix.Compose = function (scale, rotation, translation) {
  2100. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2101. var rotationMatrix = Matrix.Identity();
  2102. rotation.toRotationMatrix(rotationMatrix);
  2103. result = result.multiply(rotationMatrix);
  2104. result.setTranslation(translation);
  2105. return result;
  2106. };
  2107. Matrix.Identity = function () {
  2108. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2109. };
  2110. Matrix.IdentityToRef = function (result) {
  2111. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2112. };
  2113. Matrix.Zero = function () {
  2114. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2115. };
  2116. Matrix.RotationX = function (angle) {
  2117. var result = new Matrix();
  2118. Matrix.RotationXToRef(angle, result);
  2119. return result;
  2120. };
  2121. Matrix.Invert = function (source) {
  2122. var result = new Matrix();
  2123. source.invertToRef(result);
  2124. return result;
  2125. };
  2126. Matrix.RotationXToRef = function (angle, result) {
  2127. var s = Math.sin(angle);
  2128. var c = Math.cos(angle);
  2129. result.m[0] = 1.0;
  2130. result.m[15] = 1.0;
  2131. result.m[5] = c;
  2132. result.m[10] = c;
  2133. result.m[9] = -s;
  2134. result.m[6] = s;
  2135. result.m[1] = 0;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[4] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[11] = 0;
  2142. result.m[12] = 0;
  2143. result.m[13] = 0;
  2144. result.m[14] = 0;
  2145. };
  2146. Matrix.RotationY = function (angle) {
  2147. var result = new Matrix();
  2148. Matrix.RotationYToRef(angle, result);
  2149. return result;
  2150. };
  2151. Matrix.RotationYToRef = function (angle, result) {
  2152. var s = Math.sin(angle);
  2153. var c = Math.cos(angle);
  2154. result.m[5] = 1.0;
  2155. result.m[15] = 1.0;
  2156. result.m[0] = c;
  2157. result.m[2] = -s;
  2158. result.m[8] = s;
  2159. result.m[10] = c;
  2160. result.m[1] = 0;
  2161. result.m[3] = 0;
  2162. result.m[4] = 0;
  2163. result.m[6] = 0;
  2164. result.m[7] = 0;
  2165. result.m[9] = 0;
  2166. result.m[11] = 0;
  2167. result.m[12] = 0;
  2168. result.m[13] = 0;
  2169. result.m[14] = 0;
  2170. };
  2171. Matrix.RotationZ = function (angle) {
  2172. var result = new Matrix();
  2173. Matrix.RotationZToRef(angle, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationZToRef = function (angle, result) {
  2177. var s = Math.sin(angle);
  2178. var c = Math.cos(angle);
  2179. result.m[10] = 1.0;
  2180. result.m[15] = 1.0;
  2181. result.m[0] = c;
  2182. result.m[1] = s;
  2183. result.m[4] = -s;
  2184. result.m[5] = c;
  2185. result.m[2] = 0;
  2186. result.m[3] = 0;
  2187. result.m[6] = 0;
  2188. result.m[7] = 0;
  2189. result.m[8] = 0;
  2190. result.m[9] = 0;
  2191. result.m[11] = 0;
  2192. result.m[12] = 0;
  2193. result.m[13] = 0;
  2194. result.m[14] = 0;
  2195. };
  2196. Matrix.RotationAxis = function (axis, angle) {
  2197. var result = Matrix.Zero();
  2198. Matrix.RotationAxisToRef(axis, angle, result);
  2199. return result;
  2200. };
  2201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2202. var s = Math.sin(-angle);
  2203. var c = Math.cos(-angle);
  2204. var c1 = 1 - c;
  2205. axis.normalize();
  2206. result.m[0] = (axis.x * axis.x) * c1 + c;
  2207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2209. result.m[3] = 0.0;
  2210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2211. result.m[5] = (axis.y * axis.y) * c1 + c;
  2212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2213. result.m[7] = 0.0;
  2214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2216. result.m[10] = (axis.z * axis.z) * c1 + c;
  2217. result.m[11] = 0.0;
  2218. result.m[15] = 1.0;
  2219. };
  2220. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2221. var result = new Matrix();
  2222. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2223. return result;
  2224. };
  2225. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2226. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2227. this._tempQuaternion.toRotationMatrix(result);
  2228. };
  2229. Matrix.Scaling = function (x, y, z) {
  2230. var result = Matrix.Zero();
  2231. Matrix.ScalingToRef(x, y, z, result);
  2232. return result;
  2233. };
  2234. Matrix.ScalingToRef = function (x, y, z, result) {
  2235. result.m[0] = x;
  2236. result.m[1] = 0;
  2237. result.m[2] = 0;
  2238. result.m[3] = 0;
  2239. result.m[4] = 0;
  2240. result.m[5] = y;
  2241. result.m[6] = 0;
  2242. result.m[7] = 0;
  2243. result.m[8] = 0;
  2244. result.m[9] = 0;
  2245. result.m[10] = z;
  2246. result.m[11] = 0;
  2247. result.m[12] = 0;
  2248. result.m[13] = 0;
  2249. result.m[14] = 0;
  2250. result.m[15] = 1.0;
  2251. };
  2252. Matrix.Translation = function (x, y, z) {
  2253. var result = Matrix.Identity();
  2254. Matrix.TranslationToRef(x, y, z, result);
  2255. return result;
  2256. };
  2257. Matrix.TranslationToRef = function (x, y, z, result) {
  2258. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2259. };
  2260. Matrix.Lerp = function (startValue, endValue, gradient) {
  2261. var result = Matrix.Zero();
  2262. for (var index = 0; index < 16; index++) {
  2263. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2264. }
  2265. return result;
  2266. };
  2267. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2268. var startScale = new Vector3(0, 0, 0);
  2269. var startRotation = new Quaternion();
  2270. var startTranslation = new Vector3(0, 0, 0);
  2271. startValue.decompose(startScale, startRotation, startTranslation);
  2272. var endScale = new Vector3(0, 0, 0);
  2273. var endRotation = new Quaternion();
  2274. var endTranslation = new Vector3(0, 0, 0);
  2275. endValue.decompose(endScale, endRotation, endTranslation);
  2276. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2277. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2278. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2279. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2280. };
  2281. Matrix.LookAtLH = function (eye, target, up) {
  2282. var result = Matrix.Zero();
  2283. Matrix.LookAtLHToRef(eye, target, up, result);
  2284. return result;
  2285. };
  2286. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2287. // Z axis
  2288. target.subtractToRef(eye, this._zAxis);
  2289. this._zAxis.normalize();
  2290. // X axis
  2291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2292. if (this._xAxis.lengthSquared() === 0) {
  2293. this._xAxis.x = 1.0;
  2294. }
  2295. else {
  2296. this._xAxis.normalize();
  2297. }
  2298. // Y axis
  2299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2300. this._yAxis.normalize();
  2301. // Eye angles
  2302. var ex = -Vector3.Dot(this._xAxis, eye);
  2303. var ey = -Vector3.Dot(this._yAxis, eye);
  2304. var ez = -Vector3.Dot(this._zAxis, eye);
  2305. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2306. };
  2307. Matrix.LookAtRH = function (eye, target, up) {
  2308. var result = Matrix.Zero();
  2309. Matrix.LookAtRHToRef(eye, target, up, result);
  2310. return result;
  2311. };
  2312. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2313. // Z axis
  2314. eye.subtractToRef(target, this._zAxis);
  2315. this._zAxis.normalize();
  2316. // X axis
  2317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2318. if (this._xAxis.lengthSquared() === 0) {
  2319. this._xAxis.x = 1.0;
  2320. }
  2321. else {
  2322. this._xAxis.normalize();
  2323. }
  2324. // Y axis
  2325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2326. this._yAxis.normalize();
  2327. // Eye angles
  2328. var ex = -Vector3.Dot(this._xAxis, eye);
  2329. var ey = -Vector3.Dot(this._yAxis, eye);
  2330. var ez = -Vector3.Dot(this._zAxis, eye);
  2331. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2332. };
  2333. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2334. var matrix = Matrix.Zero();
  2335. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2336. return matrix;
  2337. };
  2338. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2339. var n = znear;
  2340. var f = zfar;
  2341. var a = 2.0 / width;
  2342. var b = 2.0 / height;
  2343. var c = 2.0 / (f - n);
  2344. var d = -(f + n) / (f - n);
  2345. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
  2346. };
  2347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2353. var n = znear;
  2354. var f = zfar;
  2355. var a = 2.0 / (right - left);
  2356. var b = 2.0 / (top - bottom);
  2357. var c = 2.0 / (f - n);
  2358. var d = -(f + n) / (f - n);
  2359. var i0 = (left + right) / (left - right);
  2360. var i1 = (top + bottom) / (bottom - top);
  2361. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
  2362. };
  2363. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2369. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2370. result.m[10] *= -1.0;
  2371. };
  2372. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2373. var matrix = Matrix.Zero();
  2374. var n = znear;
  2375. var f = zfar;
  2376. var a = 2.0 * n / width;
  2377. var b = 2.0 * n / height;
  2378. var c = (f + n) / (f - n);
  2379. var d = -2.0 * f * n / (f - n);
  2380. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var n = znear;
  2391. var f = zfar;
  2392. var t = 1.0 / (Math.tan(fov * 0.5));
  2393. var a = isVerticalFovFixed ? (t / aspect) : t;
  2394. var b = isVerticalFovFixed ? t : (t * aspect);
  2395. var c = (f + n) / (f - n);
  2396. var d = -2.0 * f * n / (f - n);
  2397. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
  2398. };
  2399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2400. var matrix = Matrix.Zero();
  2401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2402. return matrix;
  2403. };
  2404. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2405. //alternatively this could be expressed as:
  2406. // m = PerspectiveFovLHToRef
  2407. // m[10] *= -1.0;
  2408. // m[11] *= -1.0;
  2409. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2410. var n = znear;
  2411. var f = zfar;
  2412. var t = 1.0 / (Math.tan(fov * 0.5));
  2413. var a = isVerticalFovFixed ? (t / aspect) : t;
  2414. var b = isVerticalFovFixed ? t : (t * aspect);
  2415. var c = -(f + n) / (f - n);
  2416. var d = -2 * f * n / (f - n);
  2417. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
  2418. };
  2419. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2420. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2421. //left handed
  2422. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2423. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2424. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2425. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2426. var xScale = 2.0 / (leftTan + rightTan);
  2427. var yScale = 2.0 / (upTan + downTan);
  2428. result.m[0] = xScale;
  2429. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2430. result.m[5] = yScale;
  2431. result.m[6] = result.m[7] = 0.0;
  2432. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2433. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2434. result.m[10] = -(znear + zfar) / (zfar - znear);
  2435. // result.m[10] = -zfar / (znear - zfar);
  2436. result.m[11] = 1.0;
  2437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2439. // result.m[14] = (znear * zfar) / (znear - zfar);
  2440. };
  2441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2442. var cw = viewport.width;
  2443. var ch = viewport.height;
  2444. var cx = viewport.x;
  2445. var cy = viewport.y;
  2446. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2448. };
  2449. Matrix.GetAsMatrix2x2 = function (matrix) {
  2450. return new Float32Array([
  2451. matrix.m[0], matrix.m[1],
  2452. matrix.m[4], matrix.m[5]
  2453. ]);
  2454. };
  2455. Matrix.GetAsMatrix3x3 = function (matrix) {
  2456. return new Float32Array([
  2457. matrix.m[0], matrix.m[1], matrix.m[2],
  2458. matrix.m[4], matrix.m[5], matrix.m[6],
  2459. matrix.m[8], matrix.m[9], matrix.m[10]
  2460. ]);
  2461. };
  2462. Matrix.Transpose = function (matrix) {
  2463. var result = new Matrix();
  2464. result.m[0] = matrix.m[0];
  2465. result.m[1] = matrix.m[4];
  2466. result.m[2] = matrix.m[8];
  2467. result.m[3] = matrix.m[12];
  2468. result.m[4] = matrix.m[1];
  2469. result.m[5] = matrix.m[5];
  2470. result.m[6] = matrix.m[9];
  2471. result.m[7] = matrix.m[13];
  2472. result.m[8] = matrix.m[2];
  2473. result.m[9] = matrix.m[6];
  2474. result.m[10] = matrix.m[10];
  2475. result.m[11] = matrix.m[14];
  2476. result.m[12] = matrix.m[3];
  2477. result.m[13] = matrix.m[7];
  2478. result.m[14] = matrix.m[11];
  2479. result.m[15] = matrix.m[15];
  2480. return result;
  2481. };
  2482. Matrix.Reflection = function (plane) {
  2483. var matrix = new Matrix();
  2484. Matrix.ReflectionToRef(plane, matrix);
  2485. return matrix;
  2486. };
  2487. Matrix.ReflectionToRef = function (plane, result) {
  2488. plane.normalize();
  2489. var x = plane.normal.x;
  2490. var y = plane.normal.y;
  2491. var z = plane.normal.z;
  2492. var temp = -2 * x;
  2493. var temp2 = -2 * y;
  2494. var temp3 = -2 * z;
  2495. result.m[0] = (temp * x) + 1;
  2496. result.m[1] = temp2 * x;
  2497. result.m[2] = temp3 * x;
  2498. result.m[3] = 0.0;
  2499. result.m[4] = temp * y;
  2500. result.m[5] = (temp2 * y) + 1;
  2501. result.m[6] = temp3 * y;
  2502. result.m[7] = 0.0;
  2503. result.m[8] = temp * z;
  2504. result.m[9] = temp2 * z;
  2505. result.m[10] = (temp3 * z) + 1;
  2506. result.m[11] = 0.0;
  2507. result.m[12] = temp * plane.d;
  2508. result.m[13] = temp2 * plane.d;
  2509. result.m[14] = temp3 * plane.d;
  2510. result.m[15] = 1.0;
  2511. };
  2512. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2513. mat.m[0] = xaxis.x;
  2514. mat.m[1] = xaxis.y;
  2515. mat.m[2] = xaxis.z;
  2516. mat.m[3] = 0;
  2517. mat.m[4] = yaxis.x;
  2518. mat.m[5] = yaxis.y;
  2519. mat.m[6] = yaxis.z;
  2520. mat.m[7] = 0;
  2521. mat.m[8] = zaxis.x;
  2522. mat.m[9] = zaxis.y;
  2523. mat.m[10] = zaxis.z;
  2524. mat.m[11] = 0;
  2525. mat.m[12] = 0;
  2526. mat.m[13] = 0;
  2527. mat.m[14] = 0;
  2528. mat.m[15] = 1;
  2529. };
  2530. Matrix.FromQuaternionToRef = function (quat, result) {
  2531. var xx = quat.x * quat.x;
  2532. var yy = quat.y * quat.y;
  2533. var zz = quat.z * quat.z;
  2534. var xy = quat.x * quat.y;
  2535. var zw = quat.z * quat.w;
  2536. var zx = quat.z * quat.x;
  2537. var yw = quat.y * quat.w;
  2538. var yz = quat.y * quat.z;
  2539. var xw = quat.x * quat.w;
  2540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2541. result.m[1] = 2.0 * (xy + zw);
  2542. result.m[2] = 2.0 * (zx - yw);
  2543. result.m[3] = 0;
  2544. result.m[4] = 2.0 * (xy - zw);
  2545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2546. result.m[6] = 2.0 * (yz + xw);
  2547. result.m[7] = 0;
  2548. result.m[8] = 2.0 * (zx + yw);
  2549. result.m[9] = 2.0 * (yz - xw);
  2550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2551. result.m[11] = 0;
  2552. result.m[12] = 0;
  2553. result.m[13] = 0;
  2554. result.m[14] = 0;
  2555. result.m[15] = 1.0;
  2556. };
  2557. return Matrix;
  2558. }());
  2559. Matrix._tempQuaternion = new Quaternion();
  2560. Matrix._xAxis = Vector3.Zero();
  2561. Matrix._yAxis = Vector3.Zero();
  2562. Matrix._zAxis = Vector3.Zero();
  2563. BABYLON.Matrix = Matrix;
  2564. var Plane = (function () {
  2565. function Plane(a, b, c, d) {
  2566. this.normal = new Vector3(a, b, c);
  2567. this.d = d;
  2568. }
  2569. Plane.prototype.asArray = function () {
  2570. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2571. };
  2572. // Methods
  2573. Plane.prototype.clone = function () {
  2574. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2575. };
  2576. Plane.prototype.getClassName = function () {
  2577. return "Plane";
  2578. };
  2579. Plane.prototype.getHashCode = function () {
  2580. var hash = this.normal.getHashCode();
  2581. hash = (hash * 397) ^ (this.d || 0);
  2582. return hash;
  2583. };
  2584. Plane.prototype.normalize = function () {
  2585. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2586. var magnitude = 0;
  2587. if (norm !== 0) {
  2588. magnitude = 1.0 / norm;
  2589. }
  2590. this.normal.x *= magnitude;
  2591. this.normal.y *= magnitude;
  2592. this.normal.z *= magnitude;
  2593. this.d *= magnitude;
  2594. return this;
  2595. };
  2596. Plane.prototype.transform = function (transformation) {
  2597. var transposedMatrix = Matrix.Transpose(transformation);
  2598. var x = this.normal.x;
  2599. var y = this.normal.y;
  2600. var z = this.normal.z;
  2601. var d = this.d;
  2602. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2603. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2604. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2605. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2606. return new Plane(normalX, normalY, normalZ, finalD);
  2607. };
  2608. Plane.prototype.dotCoordinate = function (point) {
  2609. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2610. };
  2611. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2612. var x1 = point2.x - point1.x;
  2613. var y1 = point2.y - point1.y;
  2614. var z1 = point2.z - point1.z;
  2615. var x2 = point3.x - point1.x;
  2616. var y2 = point3.y - point1.y;
  2617. var z2 = point3.z - point1.z;
  2618. var yz = (y1 * z2) - (z1 * y2);
  2619. var xz = (z1 * x2) - (x1 * z2);
  2620. var xy = (x1 * y2) - (y1 * x2);
  2621. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2622. var invPyth;
  2623. if (pyth !== 0) {
  2624. invPyth = 1.0 / pyth;
  2625. }
  2626. else {
  2627. invPyth = 0;
  2628. }
  2629. this.normal.x = yz * invPyth;
  2630. this.normal.y = xz * invPyth;
  2631. this.normal.z = xy * invPyth;
  2632. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2633. return this;
  2634. };
  2635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2636. var dot = Vector3.Dot(this.normal, direction);
  2637. return (dot <= epsilon);
  2638. };
  2639. Plane.prototype.signedDistanceTo = function (point) {
  2640. return Vector3.Dot(point, this.normal) + this.d;
  2641. };
  2642. // Statics
  2643. Plane.FromArray = function (array) {
  2644. return new Plane(array[0], array[1], array[2], array[3]);
  2645. };
  2646. Plane.FromPoints = function (point1, point2, point3) {
  2647. var result = new Plane(0, 0, 0, 0);
  2648. result.copyFromPoints(point1, point2, point3);
  2649. return result;
  2650. };
  2651. Plane.FromPositionAndNormal = function (origin, normal) {
  2652. var result = new Plane(0, 0, 0, 0);
  2653. normal.normalize();
  2654. result.normal = normal;
  2655. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2656. return result;
  2657. };
  2658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2660. return Vector3.Dot(point, normal) + d;
  2661. };
  2662. return Plane;
  2663. }());
  2664. BABYLON.Plane = Plane;
  2665. var Viewport = (function () {
  2666. function Viewport(x, y, width, height) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.width = width;
  2670. this.height = height;
  2671. }
  2672. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2673. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2674. };
  2675. return Viewport;
  2676. }());
  2677. BABYLON.Viewport = Viewport;
  2678. var Frustum = (function () {
  2679. function Frustum() {
  2680. }
  2681. Frustum.GetPlanes = function (transform) {
  2682. var frustumPlanes = [];
  2683. for (var index = 0; index < 6; index++) {
  2684. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2685. }
  2686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2687. return frustumPlanes;
  2688. };
  2689. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2690. // Near
  2691. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2692. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2693. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2694. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2695. frustumPlanes[0].normalize();
  2696. // Far
  2697. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2698. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2699. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2700. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2701. frustumPlanes[1].normalize();
  2702. // Left
  2703. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2704. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2705. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2706. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2707. frustumPlanes[2].normalize();
  2708. // Right
  2709. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2710. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2711. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2712. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2713. frustumPlanes[3].normalize();
  2714. // Top
  2715. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2716. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2717. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2718. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2719. frustumPlanes[4].normalize();
  2720. // Bottom
  2721. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2722. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2723. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2724. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2725. frustumPlanes[5].normalize();
  2726. };
  2727. return Frustum;
  2728. }());
  2729. BABYLON.Frustum = Frustum;
  2730. var Space;
  2731. (function (Space) {
  2732. Space[Space["LOCAL"] = 0] = "LOCAL";
  2733. Space[Space["WORLD"] = 1] = "WORLD";
  2734. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2735. var Axis = (function () {
  2736. function Axis() {
  2737. }
  2738. return Axis;
  2739. }());
  2740. Axis.X = new Vector3(1, 0, 0);
  2741. Axis.Y = new Vector3(0, 1, 0);
  2742. Axis.Z = new Vector3(0, 0, 1);
  2743. BABYLON.Axis = Axis;
  2744. ;
  2745. var BezierCurve = (function () {
  2746. function BezierCurve() {
  2747. }
  2748. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2749. // Extract X (which is equal to time here)
  2750. var f0 = 1 - 3 * x2 + 3 * x1;
  2751. var f1 = 3 * x2 - 6 * x1;
  2752. var f2 = 3 * x1;
  2753. var refinedT = t;
  2754. for (var i = 0; i < 5; i++) {
  2755. var refinedT2 = refinedT * refinedT;
  2756. var refinedT3 = refinedT2 * refinedT;
  2757. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2758. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2759. refinedT -= (x - t) * slope;
  2760. refinedT = Math.min(1, Math.max(0, refinedT));
  2761. }
  2762. // Resolve cubic bezier for the given x
  2763. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2764. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2765. Math.pow(refinedT, 3);
  2766. };
  2767. return BezierCurve;
  2768. }());
  2769. BABYLON.BezierCurve = BezierCurve;
  2770. var Orientation;
  2771. (function (Orientation) {
  2772. Orientation[Orientation["CW"] = 0] = "CW";
  2773. Orientation[Orientation["CCW"] = 1] = "CCW";
  2774. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2775. var Angle = (function () {
  2776. function Angle(radians) {
  2777. var _this = this;
  2778. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2779. this.radians = function () { return _this._radians; };
  2780. this._radians = radians;
  2781. if (this._radians < 0)
  2782. this._radians += (2 * Math.PI);
  2783. }
  2784. Angle.BetweenTwoPoints = function (a, b) {
  2785. var delta = b.subtract(a);
  2786. var theta = Math.atan2(delta.y, delta.x);
  2787. return new Angle(theta);
  2788. };
  2789. Angle.FromRadians = function (radians) {
  2790. return new Angle(radians);
  2791. };
  2792. Angle.FromDegrees = function (degrees) {
  2793. return new Angle(degrees * Math.PI / 180);
  2794. };
  2795. return Angle;
  2796. }());
  2797. BABYLON.Angle = Angle;
  2798. var Arc2 = (function () {
  2799. function Arc2(startPoint, midPoint, endPoint) {
  2800. this.startPoint = startPoint;
  2801. this.midPoint = midPoint;
  2802. this.endPoint = endPoint;
  2803. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2804. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2805. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2806. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2807. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2808. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2809. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2810. var a1 = this.startAngle.degrees();
  2811. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2812. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2813. // angles correction
  2814. if (a2 - a1 > +180.0)
  2815. a2 -= 360.0;
  2816. if (a2 - a1 < -180.0)
  2817. a2 += 360.0;
  2818. if (a3 - a2 > +180.0)
  2819. a3 -= 360.0;
  2820. if (a3 - a2 < -180.0)
  2821. a3 += 360.0;
  2822. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2823. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2824. }
  2825. return Arc2;
  2826. }());
  2827. BABYLON.Arc2 = Arc2;
  2828. var Path2 = (function () {
  2829. function Path2(x, y) {
  2830. this._points = new Array();
  2831. this._length = 0;
  2832. this.closed = false;
  2833. this._points.push(new Vector2(x, y));
  2834. }
  2835. Path2.prototype.addLineTo = function (x, y) {
  2836. if (closed) {
  2837. //Tools.Error("cannot add lines to closed paths");
  2838. return this;
  2839. }
  2840. var newPoint = new Vector2(x, y);
  2841. var previousPoint = this._points[this._points.length - 1];
  2842. this._points.push(newPoint);
  2843. this._length += newPoint.subtract(previousPoint).length();
  2844. return this;
  2845. };
  2846. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2847. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2848. if (closed) {
  2849. //Tools.Error("cannot add arcs to closed paths");
  2850. return this;
  2851. }
  2852. var startPoint = this._points[this._points.length - 1];
  2853. var midPoint = new Vector2(midX, midY);
  2854. var endPoint = new Vector2(endX, endY);
  2855. var arc = new Arc2(startPoint, midPoint, endPoint);
  2856. var increment = arc.angle.radians() / numberOfSegments;
  2857. if (arc.orientation === Orientation.CW)
  2858. increment *= -1;
  2859. var currentAngle = arc.startAngle.radians() + increment;
  2860. for (var i = 0; i < numberOfSegments; i++) {
  2861. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2862. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2863. this.addLineTo(x, y);
  2864. currentAngle += increment;
  2865. }
  2866. return this;
  2867. };
  2868. Path2.prototype.close = function () {
  2869. this.closed = true;
  2870. return this;
  2871. };
  2872. Path2.prototype.length = function () {
  2873. var result = this._length;
  2874. if (!this.closed) {
  2875. var lastPoint = this._points[this._points.length - 1];
  2876. var firstPoint = this._points[0];
  2877. result += (firstPoint.subtract(lastPoint).length());
  2878. }
  2879. return result;
  2880. };
  2881. Path2.prototype.getPoints = function () {
  2882. return this._points;
  2883. };
  2884. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2885. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2886. //Tools.Error("normalized length position should be between 0 and 1.");
  2887. return Vector2.Zero();
  2888. }
  2889. var lengthPosition = normalizedLengthPosition * this.length();
  2890. var previousOffset = 0;
  2891. for (var i = 0; i < this._points.length; i++) {
  2892. var j = (i + 1) % this._points.length;
  2893. var a = this._points[i];
  2894. var b = this._points[j];
  2895. var bToA = b.subtract(a);
  2896. var nextOffset = (bToA.length() + previousOffset);
  2897. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2898. var dir = bToA.normalize();
  2899. var localOffset = lengthPosition - previousOffset;
  2900. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2901. }
  2902. previousOffset = nextOffset;
  2903. }
  2904. //Tools.Error("internal error");
  2905. return Vector2.Zero();
  2906. };
  2907. Path2.StartingAt = function (x, y) {
  2908. return new Path2(x, y);
  2909. };
  2910. return Path2;
  2911. }());
  2912. BABYLON.Path2 = Path2;
  2913. var Path3D = (function () {
  2914. /**
  2915. * new Path3D(path, normal, raw)
  2916. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2917. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2918. * path : an array of Vector3, the curve axis of the Path3D
  2919. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2920. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2921. */
  2922. function Path3D(path, firstNormal, raw) {
  2923. this.path = path;
  2924. this._curve = new Array();
  2925. this._distances = new Array();
  2926. this._tangents = new Array();
  2927. this._normals = new Array();
  2928. this._binormals = new Array();
  2929. for (var p = 0; p < path.length; p++) {
  2930. this._curve[p] = path[p].clone(); // hard copy
  2931. }
  2932. this._raw = raw || false;
  2933. this._compute(firstNormal);
  2934. }
  2935. /**
  2936. * Returns the Path3D array of successive Vector3 designing its curve.
  2937. */
  2938. Path3D.prototype.getCurve = function () {
  2939. return this._curve;
  2940. };
  2941. /**
  2942. * Returns an array populated with tangent vectors on each Path3D curve point.
  2943. */
  2944. Path3D.prototype.getTangents = function () {
  2945. return this._tangents;
  2946. };
  2947. /**
  2948. * Returns an array populated with normal vectors on each Path3D curve point.
  2949. */
  2950. Path3D.prototype.getNormals = function () {
  2951. return this._normals;
  2952. };
  2953. /**
  2954. * Returns an array populated with binormal vectors on each Path3D curve point.
  2955. */
  2956. Path3D.prototype.getBinormals = function () {
  2957. return this._binormals;
  2958. };
  2959. /**
  2960. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2961. */
  2962. Path3D.prototype.getDistances = function () {
  2963. return this._distances;
  2964. };
  2965. /**
  2966. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2967. * Returns the same object updated.
  2968. */
  2969. Path3D.prototype.update = function (path, firstNormal) {
  2970. for (var p = 0; p < path.length; p++) {
  2971. this._curve[p].x = path[p].x;
  2972. this._curve[p].y = path[p].y;
  2973. this._curve[p].z = path[p].z;
  2974. }
  2975. this._compute(firstNormal);
  2976. return this;
  2977. };
  2978. // private function compute() : computes tangents, normals and binormals
  2979. Path3D.prototype._compute = function (firstNormal) {
  2980. var l = this._curve.length;
  2981. // first and last tangents
  2982. this._tangents[0] = this._getFirstNonNullVector(0);
  2983. if (!this._raw) {
  2984. this._tangents[0].normalize();
  2985. }
  2986. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2987. if (!this._raw) {
  2988. this._tangents[l - 1].normalize();
  2989. }
  2990. // normals and binormals at first point : arbitrary vector with _normalVector()
  2991. var tg0 = this._tangents[0];
  2992. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2993. this._normals[0] = pp0;
  2994. if (!this._raw) {
  2995. this._normals[0].normalize();
  2996. }
  2997. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2998. if (!this._raw) {
  2999. this._binormals[0].normalize();
  3000. }
  3001. this._distances[0] = 0.0;
  3002. // normals and binormals : next points
  3003. var prev; // previous vector (segment)
  3004. var cur; // current vector (segment)
  3005. var curTang; // current tangent
  3006. // previous normal
  3007. var prevBinor; // previous binormal
  3008. for (var i = 1; i < l; i++) {
  3009. // tangents
  3010. prev = this._getLastNonNullVector(i);
  3011. if (i < l - 1) {
  3012. cur = this._getFirstNonNullVector(i);
  3013. this._tangents[i] = prev.add(cur);
  3014. this._tangents[i].normalize();
  3015. }
  3016. this._distances[i] = this._distances[i - 1] + prev.length();
  3017. // normals and binormals
  3018. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3019. curTang = this._tangents[i];
  3020. prevBinor = this._binormals[i - 1];
  3021. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3022. if (!this._raw) {
  3023. this._normals[i].normalize();
  3024. }
  3025. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3026. if (!this._raw) {
  3027. this._binormals[i].normalize();
  3028. }
  3029. }
  3030. };
  3031. // private function getFirstNonNullVector(index)
  3032. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3033. Path3D.prototype._getFirstNonNullVector = function (index) {
  3034. var i = 1;
  3035. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3036. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3037. i++;
  3038. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3039. }
  3040. return nNVector;
  3041. };
  3042. // private function getLastNonNullVector(index)
  3043. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3044. Path3D.prototype._getLastNonNullVector = function (index) {
  3045. var i = 1;
  3046. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3047. while (nLVector.length() === 0 && index > i + 1) {
  3048. i++;
  3049. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3050. }
  3051. return nLVector;
  3052. };
  3053. // private function normalVector(v0, vt, va) :
  3054. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3055. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3056. Path3D.prototype._normalVector = function (v0, vt, va) {
  3057. var normal0;
  3058. var tgl = vt.length();
  3059. if (tgl === 0.0) {
  3060. tgl = 1.0;
  3061. }
  3062. if (va === undefined || va === null) {
  3063. var point;
  3064. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3065. point = new Vector3(0.0, -1.0, 0.0);
  3066. }
  3067. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3068. point = new Vector3(1.0, 0.0, 0.0);
  3069. }
  3070. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3071. point = new Vector3(0.0, 0.0, 1.0);
  3072. }
  3073. normal0 = Vector3.Cross(vt, point);
  3074. }
  3075. else {
  3076. normal0 = Vector3.Cross(vt, va);
  3077. Vector3.CrossToRef(normal0, vt, normal0);
  3078. }
  3079. normal0.normalize();
  3080. return normal0;
  3081. };
  3082. return Path3D;
  3083. }());
  3084. BABYLON.Path3D = Path3D;
  3085. var Curve3 = (function () {
  3086. /**
  3087. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3088. * A Curve3 is designed from a series of successive Vector3.
  3089. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3090. */
  3091. function Curve3(points) {
  3092. this._length = 0.0;
  3093. this._points = points;
  3094. this._length = this._computeLength(points);
  3095. }
  3096. /**
  3097. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3098. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3099. * @param v1 (Vector3) the control point
  3100. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3101. * @param nbPoints (integer) the wanted number of points in the curve
  3102. */
  3103. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3104. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3105. var bez = new Array();
  3106. var equation = function (t, val0, val1, val2) {
  3107. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3108. return res;
  3109. };
  3110. for (var i = 0; i <= nbPoints; i++) {
  3111. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3112. }
  3113. return new Curve3(bez);
  3114. };
  3115. /**
  3116. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3118. * @param v1 (Vector3) the first control point
  3119. * @param v2 (Vector3) the second control point
  3120. * @param v3 (Vector3) the end point of the Cubic Bezier
  3121. * @param nbPoints (integer) the wanted number of points in the curve
  3122. */
  3123. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3124. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3125. var bez = new Array();
  3126. var equation = function (t, val0, val1, val2, val3) {
  3127. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3128. return res;
  3129. };
  3130. for (var i = 0; i <= nbPoints; i++) {
  3131. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3132. }
  3133. return new Curve3(bez);
  3134. };
  3135. /**
  3136. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3137. * @param p1 (Vector3) the origin point of the Hermite Spline
  3138. * @param t1 (Vector3) the tangent vector at the origin point
  3139. * @param p2 (Vector3) the end point of the Hermite Spline
  3140. * @param t2 (Vector3) the tangent vector at the end point
  3141. * @param nbPoints (integer) the wanted number of points in the curve
  3142. */
  3143. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3144. var hermite = new Array();
  3145. var step = 1.0 / nbPoints;
  3146. for (var i = 0; i <= nbPoints; i++) {
  3147. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3148. }
  3149. return new Curve3(hermite);
  3150. };
  3151. /**
  3152. * Returns the Curve3 stored array of successive Vector3
  3153. */
  3154. Curve3.prototype.getPoints = function () {
  3155. return this._points;
  3156. };
  3157. /**
  3158. * Returns the computed length (float) of the curve.
  3159. */
  3160. Curve3.prototype.length = function () {
  3161. return this._length;
  3162. };
  3163. /**
  3164. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3165. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3166. * curveA and curveB keep unchanged.
  3167. */
  3168. Curve3.prototype.continue = function (curve) {
  3169. var lastPoint = this._points[this._points.length - 1];
  3170. var continuedPoints = this._points.slice();
  3171. var curvePoints = curve.getPoints();
  3172. for (var i = 1; i < curvePoints.length; i++) {
  3173. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3174. }
  3175. var continuedCurve = new Curve3(continuedPoints);
  3176. return continuedCurve;
  3177. };
  3178. Curve3.prototype._computeLength = function (path) {
  3179. var l = 0;
  3180. for (var i = 1; i < path.length; i++) {
  3181. l += (path[i].subtract(path[i - 1])).length();
  3182. }
  3183. return l;
  3184. };
  3185. return Curve3;
  3186. }());
  3187. BABYLON.Curve3 = Curve3;
  3188. // SphericalHarmonics
  3189. var SphericalHarmonics = (function () {
  3190. function SphericalHarmonics() {
  3191. this.L00 = Vector3.Zero();
  3192. this.L1_1 = Vector3.Zero();
  3193. this.L10 = Vector3.Zero();
  3194. this.L11 = Vector3.Zero();
  3195. this.L2_2 = Vector3.Zero();
  3196. this.L2_1 = Vector3.Zero();
  3197. this.L20 = Vector3.Zero();
  3198. this.L21 = Vector3.Zero();
  3199. this.L22 = Vector3.Zero();
  3200. }
  3201. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3202. var colorVector = new Vector3(color.r, color.g, color.b);
  3203. var c = colorVector.scale(deltaSolidAngle);
  3204. this.L00 = this.L00.add(c.scale(0.282095));
  3205. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3206. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3207. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3208. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3209. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3210. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3211. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3212. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3213. };
  3214. SphericalHarmonics.prototype.scale = function (scale) {
  3215. this.L00 = this.L00.scale(scale);
  3216. this.L1_1 = this.L1_1.scale(scale);
  3217. this.L10 = this.L10.scale(scale);
  3218. this.L11 = this.L11.scale(scale);
  3219. this.L2_2 = this.L2_2.scale(scale);
  3220. this.L2_1 = this.L2_1.scale(scale);
  3221. this.L20 = this.L20.scale(scale);
  3222. this.L21 = this.L21.scale(scale);
  3223. this.L22 = this.L22.scale(scale);
  3224. };
  3225. return SphericalHarmonics;
  3226. }());
  3227. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3228. // SphericalPolynomial
  3229. var SphericalPolynomial = (function () {
  3230. function SphericalPolynomial() {
  3231. this.x = Vector3.Zero();
  3232. this.y = Vector3.Zero();
  3233. this.z = Vector3.Zero();
  3234. this.xx = Vector3.Zero();
  3235. this.yy = Vector3.Zero();
  3236. this.zz = Vector3.Zero();
  3237. this.xy = Vector3.Zero();
  3238. this.yz = Vector3.Zero();
  3239. this.zx = Vector3.Zero();
  3240. }
  3241. SphericalPolynomial.prototype.addAmbient = function (color) {
  3242. var colorVector = new Vector3(color.r, color.g, color.b);
  3243. this.xx = this.xx.add(colorVector);
  3244. this.yy = this.yy.add(colorVector);
  3245. this.zz = this.zz.add(colorVector);
  3246. };
  3247. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3248. var result = new SphericalPolynomial();
  3249. result.x = harmonics.L11.scale(1.02333);
  3250. result.y = harmonics.L1_1.scale(1.02333);
  3251. result.z = harmonics.L10.scale(1.02333);
  3252. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3253. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3254. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3255. result.yz = harmonics.L2_1.scale(0.858086);
  3256. result.zx = harmonics.L21.scale(0.858086);
  3257. result.xy = harmonics.L2_2.scale(0.858086);
  3258. return result;
  3259. };
  3260. return SphericalPolynomial;
  3261. }());
  3262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3263. // Vertex formats
  3264. var PositionNormalVertex = (function () {
  3265. function PositionNormalVertex(position, normal) {
  3266. if (position === void 0) { position = Vector3.Zero(); }
  3267. if (normal === void 0) { normal = Vector3.Up(); }
  3268. this.position = position;
  3269. this.normal = normal;
  3270. }
  3271. PositionNormalVertex.prototype.clone = function () {
  3272. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3273. };
  3274. return PositionNormalVertex;
  3275. }());
  3276. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3277. var PositionNormalTextureVertex = (function () {
  3278. function PositionNormalTextureVertex(position, normal, uv) {
  3279. if (position === void 0) { position = Vector3.Zero(); }
  3280. if (normal === void 0) { normal = Vector3.Up(); }
  3281. if (uv === void 0) { uv = Vector2.Zero(); }
  3282. this.position = position;
  3283. this.normal = normal;
  3284. this.uv = uv;
  3285. }
  3286. PositionNormalTextureVertex.prototype.clone = function () {
  3287. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3288. };
  3289. return PositionNormalTextureVertex;
  3290. }());
  3291. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3292. // Temporary pre-allocated objects for engine internal use
  3293. // usage in any internal function :
  3294. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3295. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3296. var Tmp = (function () {
  3297. function Tmp() {
  3298. }
  3299. return Tmp;
  3300. }());
  3301. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3302. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3303. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3304. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3305. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3306. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3307. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3308. Matrix.Zero(), Matrix.Zero(),
  3309. Matrix.Zero(), Matrix.Zero(),
  3310. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3311. BABYLON.Tmp = Tmp;
  3312. })(BABYLON || (BABYLON = {}));
  3313. //# sourceMappingURL=babylon.math.js.map
  3314. //# sourceMappingURL=babylon.mixins.js.map
  3315. var BABYLON;
  3316. (function (BABYLON) {
  3317. function generateSerializableMember(type, sourceName) {
  3318. return function (target, propertyKey) {
  3319. if (!target.__serializableMembers) {
  3320. target.__serializableMembers = {};
  3321. }
  3322. if (!target.__serializableMembers[propertyKey]) {
  3323. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3324. }
  3325. };
  3326. }
  3327. function serialize(sourceName) {
  3328. return generateSerializableMember(0, sourceName); // value member
  3329. }
  3330. BABYLON.serialize = serialize;
  3331. function serializeAsTexture(sourceName) {
  3332. return generateSerializableMember(1, sourceName); // texture member
  3333. }
  3334. BABYLON.serializeAsTexture = serializeAsTexture;
  3335. function serializeAsColor3(sourceName) {
  3336. return generateSerializableMember(2, sourceName); // color3 member
  3337. }
  3338. BABYLON.serializeAsColor3 = serializeAsColor3;
  3339. function serializeAsFresnelParameters(sourceName) {
  3340. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3341. }
  3342. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3343. function serializeAsVector2(sourceName) {
  3344. return generateSerializableMember(4, sourceName); // vector2 member
  3345. }
  3346. BABYLON.serializeAsVector2 = serializeAsVector2;
  3347. function serializeAsVector3(sourceName) {
  3348. return generateSerializableMember(5, sourceName); // vector3 member
  3349. }
  3350. BABYLON.serializeAsVector3 = serializeAsVector3;
  3351. function serializeAsMeshReference(sourceName) {
  3352. return generateSerializableMember(6, sourceName); // mesh reference member
  3353. }
  3354. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3355. function serializeAsColorCurves(sourceName) {
  3356. return generateSerializableMember(7, sourceName); // color curves
  3357. }
  3358. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3359. var SerializationHelper = (function () {
  3360. function SerializationHelper() {
  3361. }
  3362. SerializationHelper.Serialize = function (entity, serializationObject) {
  3363. if (!serializationObject) {
  3364. serializationObject = {};
  3365. }
  3366. // Tags
  3367. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3368. // Properties
  3369. for (var property in entity.__serializableMembers) {
  3370. var propertyDescriptor = entity.__serializableMembers[property];
  3371. var targetPropertyName = propertyDescriptor.sourceName || property;
  3372. var propertyType = propertyDescriptor.type;
  3373. var sourceProperty = entity[property];
  3374. if (sourceProperty !== undefined && sourceProperty !== null) {
  3375. switch (propertyType) {
  3376. case 0:
  3377. serializationObject[targetPropertyName] = sourceProperty;
  3378. break;
  3379. case 1:
  3380. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3381. break;
  3382. case 2:
  3383. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3384. break;
  3385. case 3:
  3386. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3387. break;
  3388. case 4:
  3389. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3390. break;
  3391. case 5:
  3392. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3393. break;
  3394. case 6:
  3395. serializationObject[targetPropertyName] = sourceProperty.id;
  3396. break;
  3397. case 7:
  3398. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3399. break;
  3400. }
  3401. }
  3402. }
  3403. return serializationObject;
  3404. };
  3405. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3406. var destination = creationFunction();
  3407. // Tags
  3408. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3409. // Properties
  3410. for (var property in destination.__serializableMembers) {
  3411. var propertyDescriptor = destination.__serializableMembers[property];
  3412. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3413. var propertyType = propertyDescriptor.type;
  3414. if (sourceProperty !== undefined && sourceProperty !== null) {
  3415. switch (propertyType) {
  3416. case 0:
  3417. destination[property] = sourceProperty;
  3418. break;
  3419. case 1:
  3420. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3421. break;
  3422. case 2:
  3423. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3424. break;
  3425. case 3:
  3426. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3427. break;
  3428. case 4:
  3429. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3430. break;
  3431. case 5:
  3432. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3433. break;
  3434. case 6:
  3435. destination[property] = scene.getLastMeshByID(sourceProperty);
  3436. break;
  3437. case 7:
  3438. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. return destination;
  3444. };
  3445. SerializationHelper.Clone = function (creationFunction, source) {
  3446. var destination = creationFunction();
  3447. // Tags
  3448. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3449. // Properties
  3450. for (var property in destination.__serializableMembers) {
  3451. var propertyDescriptor = destination.__serializableMembers[property];
  3452. var sourceProperty = source[property];
  3453. var propertyType = propertyDescriptor.type;
  3454. if (sourceProperty !== undefined && sourceProperty !== null) {
  3455. switch (propertyType) {
  3456. case 0: // Value
  3457. case 6:
  3458. destination[property] = sourceProperty;
  3459. break;
  3460. case 1: // Texture
  3461. case 2: // Color3
  3462. case 3: // FresnelParameters
  3463. case 4: // Vector2
  3464. case 5: // Vector3
  3465. case 7:
  3466. destination[property] = sourceProperty.clone();
  3467. break;
  3468. }
  3469. }
  3470. }
  3471. return destination;
  3472. };
  3473. return SerializationHelper;
  3474. }());
  3475. BABYLON.SerializationHelper = SerializationHelper;
  3476. })(BABYLON || (BABYLON = {}));
  3477. //# sourceMappingURL=babylon.decorators.js.map
  3478. var BABYLON;
  3479. (function (BABYLON) {
  3480. /**
  3481. * A class serves as a medium between the observable and its observers
  3482. */
  3483. var EventState = (function () {
  3484. /**
  3485. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3486. */
  3487. function EventState(mask, skipNextObservers) {
  3488. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3489. this.initalize(mask, skipNextObservers);
  3490. }
  3491. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3492. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3493. this.mask = mask;
  3494. this.skipNextObservers = skipNextObservers;
  3495. return this;
  3496. };
  3497. return EventState;
  3498. }());
  3499. BABYLON.EventState = EventState;
  3500. /**
  3501. * Represent an Observer registered to a given Observable object.
  3502. */
  3503. var Observer = (function () {
  3504. function Observer(callback, mask) {
  3505. this.callback = callback;
  3506. this.mask = mask;
  3507. }
  3508. return Observer;
  3509. }());
  3510. BABYLON.Observer = Observer;
  3511. /**
  3512. * The Observable class is a simple implementation of the Observable pattern.
  3513. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3514. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3515. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3516. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3517. */
  3518. var Observable = (function () {
  3519. function Observable() {
  3520. this._observers = new Array();
  3521. this._eventState = new EventState(0);
  3522. }
  3523. /**
  3524. * Create a new Observer with the specified callback
  3525. * @param callback the callback that will be executed for that Observer
  3526. * @param mask the mask used to filter observers
  3527. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3528. */
  3529. Observable.prototype.add = function (callback, mask, insertFirst) {
  3530. if (mask === void 0) { mask = -1; }
  3531. if (insertFirst === void 0) { insertFirst = false; }
  3532. if (!callback) {
  3533. return null;
  3534. }
  3535. var observer = new Observer(callback, mask);
  3536. if (insertFirst) {
  3537. this._observers.unshift(observer);
  3538. }
  3539. else {
  3540. this._observers.push(observer);
  3541. }
  3542. return observer;
  3543. };
  3544. /**
  3545. * Remove an Observer from the Observable object
  3546. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3547. */
  3548. Observable.prototype.remove = function (observer) {
  3549. var index = this._observers.indexOf(observer);
  3550. if (index !== -1) {
  3551. this._observers.splice(index, 1);
  3552. return true;
  3553. }
  3554. return false;
  3555. };
  3556. /**
  3557. * Remove a callback from the Observable object
  3558. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3559. */
  3560. Observable.prototype.removeCallback = function (callback) {
  3561. for (var index = 0; index < this._observers.length; index++) {
  3562. if (this._observers[index].callback === callback) {
  3563. this._observers.splice(index, 1);
  3564. return true;
  3565. }
  3566. }
  3567. return false;
  3568. };
  3569. /**
  3570. * Notify all Observers by calling their respective callback with the given data
  3571. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3572. * @param eventData
  3573. * @param mask
  3574. */
  3575. Observable.prototype.notifyObservers = function (eventData, mask) {
  3576. if (mask === void 0) { mask = -1; }
  3577. var state = this._eventState;
  3578. state.mask = mask;
  3579. state.skipNextObservers = false;
  3580. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3581. var obs = _a[_i];
  3582. if (obs.mask & mask) {
  3583. obs.callback(eventData, state);
  3584. }
  3585. if (state.skipNextObservers) {
  3586. return false;
  3587. }
  3588. }
  3589. return true;
  3590. };
  3591. /**
  3592. * return true is the Observable has at least one Observer registered
  3593. */
  3594. Observable.prototype.hasObservers = function () {
  3595. return this._observers.length > 0;
  3596. };
  3597. /**
  3598. * Clear the list of observers
  3599. */
  3600. Observable.prototype.clear = function () {
  3601. this._observers = new Array();
  3602. };
  3603. /**
  3604. * Clone the current observable
  3605. */
  3606. Observable.prototype.clone = function () {
  3607. var result = new Observable();
  3608. result._observers = this._observers.slice(0);
  3609. return result;
  3610. };
  3611. return Observable;
  3612. }());
  3613. BABYLON.Observable = Observable;
  3614. })(BABYLON || (BABYLON = {}));
  3615. //# sourceMappingURL=babylon.observable.js.map
  3616. var BABYLON;
  3617. (function (BABYLON) {
  3618. var Database = (function () {
  3619. function Database(urlToScene, callbackManifestChecked) {
  3620. // Handling various flavors of prefixed version of IndexedDB
  3621. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3622. this.callbackManifestChecked = callbackManifestChecked;
  3623. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3624. this.db = null;
  3625. this.enableSceneOffline = false;
  3626. this.enableTexturesOffline = false;
  3627. this.manifestVersionFound = 0;
  3628. this.mustUpdateRessources = false;
  3629. this.hasReachedQuota = false;
  3630. if (!Database.IDBStorageEnabled) {
  3631. this.callbackManifestChecked(true);
  3632. }
  3633. else {
  3634. this.checkManifestFile();
  3635. }
  3636. }
  3637. Database.prototype.checkManifestFile = function () {
  3638. var _this = this;
  3639. function noManifestFile() {
  3640. that.enableSceneOffline = false;
  3641. that.enableTexturesOffline = false;
  3642. that.callbackManifestChecked(false);
  3643. }
  3644. var that = this;
  3645. var timeStampUsed = false;
  3646. var manifestURL = this.currentSceneUrl + ".manifest";
  3647. var xhr = new XMLHttpRequest();
  3648. if (navigator.onLine) {
  3649. // Adding a timestamp to by-pass browsers' cache
  3650. timeStampUsed = true;
  3651. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3652. }
  3653. xhr.open("GET", manifestURL, true);
  3654. xhr.addEventListener("load", function () {
  3655. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3656. try {
  3657. var manifestFile = JSON.parse(xhr.response);
  3658. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3659. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3660. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3661. _this.manifestVersionFound = manifestFile.version;
  3662. }
  3663. if (_this.callbackManifestChecked) {
  3664. _this.callbackManifestChecked(true);
  3665. }
  3666. }
  3667. catch (ex) {
  3668. noManifestFile();
  3669. }
  3670. }
  3671. else {
  3672. noManifestFile();
  3673. }
  3674. }, false);
  3675. xhr.addEventListener("error", function (event) {
  3676. if (timeStampUsed) {
  3677. timeStampUsed = false;
  3678. // Let's retry without the timeStamp
  3679. // It could fail when coupled with HTML5 Offline API
  3680. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3681. xhr.open("GET", retryManifestURL, true);
  3682. xhr.send();
  3683. }
  3684. else {
  3685. noManifestFile();
  3686. }
  3687. }, false);
  3688. try {
  3689. xhr.send();
  3690. }
  3691. catch (ex) {
  3692. BABYLON.Tools.Error("Error on XHR send request.");
  3693. that.callbackManifestChecked(false);
  3694. }
  3695. };
  3696. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3697. var _this = this;
  3698. function handleError() {
  3699. that.isSupported = false;
  3700. if (errorCallback)
  3701. errorCallback();
  3702. }
  3703. var that = this;
  3704. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3705. // Your browser doesn't support IndexedDB
  3706. this.isSupported = false;
  3707. if (errorCallback)
  3708. errorCallback();
  3709. }
  3710. else {
  3711. // If the DB hasn't been opened or created yet
  3712. if (!this.db) {
  3713. this.hasReachedQuota = false;
  3714. this.isSupported = true;
  3715. var request = this.idbFactory.open("babylonjs", 1);
  3716. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3717. request.onerror = function (event) {
  3718. handleError();
  3719. };
  3720. // executes when a version change transaction cannot complete due to other active transactions
  3721. request.onblocked = function (event) {
  3722. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3723. handleError();
  3724. };
  3725. // DB has been opened successfully
  3726. request.onsuccess = function (event) {
  3727. _this.db = request.result;
  3728. successCallback();
  3729. };
  3730. // Initialization of the DB. Creating Scenes & Textures stores
  3731. request.onupgradeneeded = function (event) {
  3732. _this.db = (event.target).result;
  3733. try {
  3734. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3735. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3736. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3737. }
  3738. catch (ex) {
  3739. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3740. handleError();
  3741. }
  3742. };
  3743. }
  3744. else {
  3745. if (successCallback)
  3746. successCallback();
  3747. }
  3748. }
  3749. };
  3750. Database.prototype.loadImageFromDB = function (url, image) {
  3751. var _this = this;
  3752. var completeURL = Database.ReturnFullUrlLocation(url);
  3753. var saveAndLoadImage = function () {
  3754. if (!_this.hasReachedQuota && _this.db !== null) {
  3755. // the texture is not yet in the DB, let's try to save it
  3756. _this._saveImageIntoDBAsync(completeURL, image);
  3757. }
  3758. else {
  3759. image.src = url;
  3760. }
  3761. };
  3762. if (!this.mustUpdateRessources) {
  3763. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3764. }
  3765. else {
  3766. saveAndLoadImage();
  3767. }
  3768. };
  3769. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3770. if (this.isSupported && this.db !== null) {
  3771. var texture;
  3772. var transaction = this.db.transaction(["textures"]);
  3773. transaction.onabort = function (event) {
  3774. image.src = url;
  3775. };
  3776. transaction.oncomplete = function (event) {
  3777. var blobTextureURL;
  3778. if (texture) {
  3779. var URL = window.URL || window.webkitURL;
  3780. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3781. image.onerror = function () {
  3782. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3783. image.src = url;
  3784. };
  3785. image.src = blobTextureURL;
  3786. }
  3787. else {
  3788. notInDBCallback();
  3789. }
  3790. };
  3791. var getRequest = transaction.objectStore("textures").get(url);
  3792. getRequest.onsuccess = function (event) {
  3793. texture = (event.target).result;
  3794. };
  3795. getRequest.onerror = function (event) {
  3796. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3797. image.src = url;
  3798. };
  3799. }
  3800. else {
  3801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3802. image.src = url;
  3803. }
  3804. };
  3805. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3806. var _this = this;
  3807. if (this.isSupported) {
  3808. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3809. var generateBlobUrl = function () {
  3810. var blobTextureURL;
  3811. if (blob) {
  3812. var URL = window.URL || window.webkitURL;
  3813. try {
  3814. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3815. }
  3816. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3817. catch (ex) {
  3818. blobTextureURL = URL.createObjectURL(blob);
  3819. }
  3820. }
  3821. image.src = blobTextureURL;
  3822. };
  3823. if (Database.IsUASupportingBlobStorage) {
  3824. var xhr = new XMLHttpRequest(), blob;
  3825. xhr.open("GET", url, true);
  3826. xhr.responseType = "blob";
  3827. xhr.addEventListener("load", function () {
  3828. if (xhr.status === 200) {
  3829. // Blob as response (XHR2)
  3830. blob = xhr.response;
  3831. var transaction = _this.db.transaction(["textures"], "readwrite");
  3832. // the transaction could abort because of a QuotaExceededError error
  3833. transaction.onabort = function (event) {
  3834. try {
  3835. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3836. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3837. _this.hasReachedQuota = true;
  3838. }
  3839. }
  3840. catch (ex) { }
  3841. generateBlobUrl();
  3842. };
  3843. transaction.oncomplete = function (event) {
  3844. generateBlobUrl();
  3845. };
  3846. var newTexture = { textureUrl: url, data: blob };
  3847. try {
  3848. // Put the blob into the dabase
  3849. var addRequest = transaction.objectStore("textures").put(newTexture);
  3850. addRequest.onsuccess = function (event) {
  3851. };
  3852. addRequest.onerror = function (event) {
  3853. generateBlobUrl();
  3854. };
  3855. }
  3856. catch (ex) {
  3857. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3858. if (ex.code === 25) {
  3859. Database.IsUASupportingBlobStorage = false;
  3860. }
  3861. image.src = url;
  3862. }
  3863. }
  3864. else {
  3865. image.src = url;
  3866. }
  3867. }, false);
  3868. xhr.addEventListener("error", function (event) {
  3869. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3870. image.src = url;
  3871. }, false);
  3872. xhr.send();
  3873. }
  3874. else {
  3875. image.src = url;
  3876. }
  3877. }
  3878. else {
  3879. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3880. image.src = url;
  3881. }
  3882. };
  3883. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3884. var _this = this;
  3885. var updateVersion = function (event) {
  3886. // the version is not yet in the DB or we need to update it
  3887. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3888. };
  3889. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3890. };
  3891. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3892. var _this = this;
  3893. if (this.isSupported) {
  3894. var version;
  3895. try {
  3896. var transaction = this.db.transaction(["versions"]);
  3897. transaction.oncomplete = function (event) {
  3898. if (version) {
  3899. // If the version in the JSON file is > than the version in DB
  3900. if (_this.manifestVersionFound > version.data) {
  3901. _this.mustUpdateRessources = true;
  3902. updateInDBCallback();
  3903. }
  3904. else {
  3905. callback(version.data);
  3906. }
  3907. }
  3908. else {
  3909. _this.mustUpdateRessources = true;
  3910. updateInDBCallback();
  3911. }
  3912. };
  3913. transaction.onabort = function (event) {
  3914. callback(-1);
  3915. };
  3916. var getRequest = transaction.objectStore("versions").get(url);
  3917. getRequest.onsuccess = function (event) {
  3918. version = (event.target).result;
  3919. };
  3920. getRequest.onerror = function (event) {
  3921. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3922. callback(-1);
  3923. };
  3924. }
  3925. catch (ex) {
  3926. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3927. callback(-1);
  3928. }
  3929. }
  3930. else {
  3931. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3932. callback(-1);
  3933. }
  3934. };
  3935. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3936. var _this = this;
  3937. if (this.isSupported && !this.hasReachedQuota) {
  3938. try {
  3939. // Open a transaction to the database
  3940. var transaction = this.db.transaction(["versions"], "readwrite");
  3941. // the transaction could abort because of a QuotaExceededError error
  3942. transaction.onabort = function (event) {
  3943. try {
  3944. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3945. _this.hasReachedQuota = true;
  3946. }
  3947. }
  3948. catch (ex) { }
  3949. callback(-1);
  3950. };
  3951. transaction.oncomplete = function (event) {
  3952. callback(_this.manifestVersionFound);
  3953. };
  3954. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3955. // Put the scene into the database
  3956. var addRequest = transaction.objectStore("versions").put(newVersion);
  3957. addRequest.onsuccess = function (event) {
  3958. };
  3959. addRequest.onerror = function (event) {
  3960. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3961. };
  3962. }
  3963. catch (ex) {
  3964. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3965. callback(-1);
  3966. }
  3967. }
  3968. else {
  3969. callback(-1);
  3970. }
  3971. };
  3972. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3973. var _this = this;
  3974. var completeUrl = Database.ReturnFullUrlLocation(url);
  3975. var saveAndLoadFile = function (event) {
  3976. // the scene is not yet in the DB, let's try to save it
  3977. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3978. };
  3979. this._checkVersionFromDB(completeUrl, function (version) {
  3980. if (version !== -1) {
  3981. if (!_this.mustUpdateRessources) {
  3982. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3983. }
  3984. else {
  3985. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3986. }
  3987. }
  3988. else {
  3989. errorCallback();
  3990. }
  3991. });
  3992. };
  3993. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3994. if (this.isSupported) {
  3995. var targetStore;
  3996. if (url.indexOf(".babylon") !== -1) {
  3997. targetStore = "scenes";
  3998. }
  3999. else {
  4000. targetStore = "textures";
  4001. }
  4002. var file;
  4003. var transaction = this.db.transaction([targetStore]);
  4004. transaction.oncomplete = function (event) {
  4005. if (file) {
  4006. callback(file.data);
  4007. }
  4008. else {
  4009. notInDBCallback();
  4010. }
  4011. };
  4012. transaction.onabort = function (event) {
  4013. notInDBCallback();
  4014. };
  4015. var getRequest = transaction.objectStore(targetStore).get(url);
  4016. getRequest.onsuccess = function (event) {
  4017. file = (event.target).result;
  4018. };
  4019. getRequest.onerror = function (event) {
  4020. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4021. notInDBCallback();
  4022. };
  4023. }
  4024. else {
  4025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4026. callback();
  4027. }
  4028. };
  4029. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4030. var _this = this;
  4031. if (this.isSupported) {
  4032. var targetStore;
  4033. if (url.indexOf(".babylon") !== -1) {
  4034. targetStore = "scenes";
  4035. }
  4036. else {
  4037. targetStore = "textures";
  4038. }
  4039. // Create XHR
  4040. var xhr = new XMLHttpRequest(), fileData;
  4041. xhr.open("GET", url, true);
  4042. if (useArrayBuffer) {
  4043. xhr.responseType = "arraybuffer";
  4044. }
  4045. xhr.onprogress = progressCallback;
  4046. xhr.addEventListener("load", function () {
  4047. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4048. // Blob as response (XHR2)
  4049. //fileData = xhr.responseText;
  4050. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4051. if (!_this.hasReachedQuota) {
  4052. // Open a transaction to the database
  4053. var transaction = _this.db.transaction([targetStore], "readwrite");
  4054. // the transaction could abort because of a QuotaExceededError error
  4055. transaction.onabort = function (event) {
  4056. try {
  4057. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4058. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4059. _this.hasReachedQuota = true;
  4060. }
  4061. }
  4062. catch (ex) { }
  4063. callback(fileData);
  4064. };
  4065. transaction.oncomplete = function (event) {
  4066. callback(fileData);
  4067. };
  4068. var newFile;
  4069. if (targetStore === "scenes") {
  4070. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4071. }
  4072. else {
  4073. newFile = { textureUrl: url, data: fileData };
  4074. }
  4075. try {
  4076. // Put the scene into the database
  4077. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4078. addRequest.onsuccess = function (event) {
  4079. };
  4080. addRequest.onerror = function (event) {
  4081. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4082. };
  4083. }
  4084. catch (ex) {
  4085. callback(fileData);
  4086. }
  4087. }
  4088. else {
  4089. callback(fileData);
  4090. }
  4091. }
  4092. else {
  4093. callback();
  4094. }
  4095. }, false);
  4096. xhr.addEventListener("error", function (event) {
  4097. BABYLON.Tools.Error("error on XHR request.");
  4098. callback();
  4099. }, false);
  4100. xhr.send();
  4101. }
  4102. else {
  4103. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4104. callback();
  4105. }
  4106. };
  4107. return Database;
  4108. }());
  4109. Database.IsUASupportingBlobStorage = true;
  4110. Database.IDBStorageEnabled = true;
  4111. Database.parseURL = function (url) {
  4112. var a = document.createElement('a');
  4113. a.href = url;
  4114. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4115. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4116. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4117. return absLocation;
  4118. };
  4119. Database.ReturnFullUrlLocation = function (url) {
  4120. if (url.indexOf("http:/") === -1) {
  4121. return (Database.parseURL(window.location.href) + url);
  4122. }
  4123. else {
  4124. return url;
  4125. }
  4126. };
  4127. BABYLON.Database = Database;
  4128. })(BABYLON || (BABYLON = {}));
  4129. //# sourceMappingURL=babylon.database.js.map
  4130. var BABYLON;
  4131. (function (BABYLON) {
  4132. var Internals;
  4133. (function (Internals) {
  4134. /*
  4135. * Based on jsTGALoader - Javascript loader for TGA file
  4136. * By Vincent Thibault
  4137. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4138. */
  4139. var TGATools = (function () {
  4140. function TGATools() {
  4141. }
  4142. TGATools.GetTGAHeader = function (data) {
  4143. var offset = 0;
  4144. var header = {
  4145. id_length: data[offset++],
  4146. colormap_type: data[offset++],
  4147. image_type: data[offset++],
  4148. colormap_index: data[offset++] | data[offset++] << 8,
  4149. colormap_length: data[offset++] | data[offset++] << 8,
  4150. colormap_size: data[offset++],
  4151. origin: [
  4152. data[offset++] | data[offset++] << 8,
  4153. data[offset++] | data[offset++] << 8
  4154. ],
  4155. width: data[offset++] | data[offset++] << 8,
  4156. height: data[offset++] | data[offset++] << 8,
  4157. pixel_size: data[offset++],
  4158. flags: data[offset++]
  4159. };
  4160. return header;
  4161. };
  4162. TGATools.UploadContent = function (gl, data) {
  4163. // Not enough data to contain header ?
  4164. if (data.length < 19) {
  4165. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4166. return;
  4167. }
  4168. // Read Header
  4169. var offset = 18;
  4170. var header = TGATools.GetTGAHeader(data);
  4171. // Assume it's a valid Targa file.
  4172. if (header.id_length + offset > data.length) {
  4173. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4174. return;
  4175. }
  4176. // Skip not needed data
  4177. offset += header.id_length;
  4178. var use_rle = false;
  4179. var use_pal = false;
  4180. var use_rgb = false;
  4181. var use_grey = false;
  4182. // Get some informations.
  4183. switch (header.image_type) {
  4184. case TGATools._TYPE_RLE_INDEXED:
  4185. use_rle = true;
  4186. case TGATools._TYPE_INDEXED:
  4187. use_pal = true;
  4188. break;
  4189. case TGATools._TYPE_RLE_RGB:
  4190. use_rle = true;
  4191. case TGATools._TYPE_RGB:
  4192. use_rgb = true;
  4193. break;
  4194. case TGATools._TYPE_RLE_GREY:
  4195. use_rle = true;
  4196. case TGATools._TYPE_GREY:
  4197. use_grey = true;
  4198. break;
  4199. }
  4200. var pixel_data;
  4201. var numAlphaBits = header.flags & 0xf;
  4202. var pixel_size = header.pixel_size >> 3;
  4203. var pixel_total = header.width * header.height * pixel_size;
  4204. // Read palettes
  4205. var palettes;
  4206. if (use_pal) {
  4207. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4208. }
  4209. // Read LRE
  4210. if (use_rle) {
  4211. pixel_data = new Uint8Array(pixel_total);
  4212. var c, count, i;
  4213. var localOffset = 0;
  4214. var pixels = new Uint8Array(pixel_size);
  4215. while (offset < pixel_total && localOffset < pixel_total) {
  4216. c = data[offset++];
  4217. count = (c & 0x7f) + 1;
  4218. // RLE pixels
  4219. if (c & 0x80) {
  4220. // Bind pixel tmp array
  4221. for (i = 0; i < pixel_size; ++i) {
  4222. pixels[i] = data[offset++];
  4223. }
  4224. // Copy pixel array
  4225. for (i = 0; i < count; ++i) {
  4226. pixel_data.set(pixels, localOffset + i * pixel_size);
  4227. }
  4228. localOffset += pixel_size * count;
  4229. }
  4230. else {
  4231. count *= pixel_size;
  4232. for (i = 0; i < count; ++i) {
  4233. pixel_data[localOffset + i] = data[offset++];
  4234. }
  4235. localOffset += count;
  4236. }
  4237. }
  4238. }
  4239. else {
  4240. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4241. }
  4242. // Load to texture
  4243. var x_start, y_start, x_step, y_step, y_end, x_end;
  4244. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4245. default:
  4246. case TGATools._ORIGIN_UL:
  4247. x_start = 0;
  4248. x_step = 1;
  4249. x_end = header.width;
  4250. y_start = 0;
  4251. y_step = 1;
  4252. y_end = header.height;
  4253. break;
  4254. case TGATools._ORIGIN_BL:
  4255. x_start = 0;
  4256. x_step = 1;
  4257. x_end = header.width;
  4258. y_start = header.height - 1;
  4259. y_step = -1;
  4260. y_end = -1;
  4261. break;
  4262. case TGATools._ORIGIN_UR:
  4263. x_start = header.width - 1;
  4264. x_step = -1;
  4265. x_end = -1;
  4266. y_start = 0;
  4267. y_step = 1;
  4268. y_end = header.height;
  4269. break;
  4270. case TGATools._ORIGIN_BR:
  4271. x_start = header.width - 1;
  4272. x_step = -1;
  4273. x_end = -1;
  4274. y_start = header.height - 1;
  4275. y_step = -1;
  4276. y_end = -1;
  4277. break;
  4278. }
  4279. // Load the specify method
  4280. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4281. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4282. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4283. };
  4284. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4285. var image = pixel_data, colormap = palettes;
  4286. var width = header.width, height = header.height;
  4287. var color, i = 0, x, y;
  4288. var imageData = new Uint8Array(width * height * 4);
  4289. for (y = y_start; y !== y_end; y += y_step) {
  4290. for (x = x_start; x !== x_end; x += x_step, i++) {
  4291. color = image[i];
  4292. imageData[(x + width * y) * 4 + 3] = 255;
  4293. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4294. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4295. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4296. }
  4297. }
  4298. return imageData;
  4299. };
  4300. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4301. var image = pixel_data;
  4302. var width = header.width, height = header.height;
  4303. var color, i = 0, x, y;
  4304. var imageData = new Uint8Array(width * height * 4);
  4305. for (y = y_start; y !== y_end; y += y_step) {
  4306. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4307. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4308. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4309. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4310. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4311. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4312. }
  4313. }
  4314. return imageData;
  4315. };
  4316. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4317. var image = pixel_data;
  4318. var width = header.width, height = header.height;
  4319. var i = 0, x, y;
  4320. var imageData = new Uint8Array(width * height * 4);
  4321. for (y = y_start; y !== y_end; y += y_step) {
  4322. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4323. imageData[(x + width * y) * 4 + 3] = 255;
  4324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4327. }
  4328. }
  4329. return imageData;
  4330. };
  4331. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4332. var image = pixel_data;
  4333. var width = header.width, height = header.height;
  4334. var i = 0, x, y;
  4335. var imageData = new Uint8Array(width * height * 4);
  4336. for (y = y_start; y !== y_end; y += y_step) {
  4337. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4338. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4339. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4340. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4341. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4342. }
  4343. }
  4344. return imageData;
  4345. };
  4346. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4347. var image = pixel_data;
  4348. var width = header.width, height = header.height;
  4349. var color, i = 0, x, y;
  4350. var imageData = new Uint8Array(width * height * 4);
  4351. for (y = y_start; y !== y_end; y += y_step) {
  4352. for (x = x_start; x !== x_end; x += x_step, i++) {
  4353. color = image[i];
  4354. imageData[(x + width * y) * 4 + 0] = color;
  4355. imageData[(x + width * y) * 4 + 1] = color;
  4356. imageData[(x + width * y) * 4 + 2] = color;
  4357. imageData[(x + width * y) * 4 + 3] = 255;
  4358. }
  4359. }
  4360. return imageData;
  4361. };
  4362. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4363. var image = pixel_data;
  4364. var width = header.width, height = header.height;
  4365. var i = 0, x, y;
  4366. var imageData = new Uint8Array(width * height * 4);
  4367. for (y = y_start; y !== y_end; y += y_step) {
  4368. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4369. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4370. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4372. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4373. }
  4374. }
  4375. return imageData;
  4376. };
  4377. return TGATools;
  4378. }());
  4379. TGATools._TYPE_NO_DATA = 0;
  4380. TGATools._TYPE_INDEXED = 1;
  4381. TGATools._TYPE_RGB = 2;
  4382. TGATools._TYPE_GREY = 3;
  4383. TGATools._TYPE_RLE_INDEXED = 9;
  4384. TGATools._TYPE_RLE_RGB = 10;
  4385. TGATools._TYPE_RLE_GREY = 11;
  4386. TGATools._ORIGIN_MASK = 0x30;
  4387. TGATools._ORIGIN_SHIFT = 0x04;
  4388. TGATools._ORIGIN_BL = 0x00;
  4389. TGATools._ORIGIN_BR = 0x01;
  4390. TGATools._ORIGIN_UL = 0x02;
  4391. TGATools._ORIGIN_UR = 0x03;
  4392. Internals.TGATools = TGATools;
  4393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4394. })(BABYLON || (BABYLON = {}));
  4395. //# sourceMappingURL=babylon.tools.tga.js.map
  4396. var BABYLON;
  4397. (function (BABYLON) {
  4398. var SmartArray = (function () {
  4399. function SmartArray(capacity) {
  4400. this.length = 0;
  4401. this._duplicateId = 0;
  4402. this.data = new Array(capacity);
  4403. this._id = SmartArray._GlobalId++;
  4404. }
  4405. SmartArray.prototype.push = function (value) {
  4406. this.data[this.length++] = value;
  4407. if (this.length > this.data.length) {
  4408. this.data.length *= 2;
  4409. }
  4410. if (!value.__smartArrayFlags) {
  4411. value.__smartArrayFlags = {};
  4412. }
  4413. value.__smartArrayFlags[this._id] = this._duplicateId;
  4414. };
  4415. SmartArray.prototype.pushNoDuplicate = function (value) {
  4416. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4417. return false;
  4418. }
  4419. this.push(value);
  4420. return true;
  4421. };
  4422. SmartArray.prototype.sort = function (compareFn) {
  4423. this.data.sort(compareFn);
  4424. };
  4425. SmartArray.prototype.reset = function () {
  4426. this.length = 0;
  4427. this._duplicateId++;
  4428. };
  4429. SmartArray.prototype.concat = function (array) {
  4430. if (array.length === 0) {
  4431. return;
  4432. }
  4433. if (this.length + array.length > this.data.length) {
  4434. this.data.length = (this.length + array.length) * 2;
  4435. }
  4436. for (var index = 0; index < array.length; index++) {
  4437. this.data[this.length++] = (array.data || array)[index];
  4438. }
  4439. };
  4440. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4441. if (array.length === 0) {
  4442. return;
  4443. }
  4444. if (this.length + array.length > this.data.length) {
  4445. this.data.length = (this.length + array.length) * 2;
  4446. }
  4447. for (var index = 0; index < array.length; index++) {
  4448. var item = (array.data || array)[index];
  4449. this.pushNoDuplicate(item);
  4450. }
  4451. };
  4452. SmartArray.prototype.indexOf = function (value) {
  4453. var position = this.data.indexOf(value);
  4454. if (position >= this.length) {
  4455. return -1;
  4456. }
  4457. return position;
  4458. };
  4459. return SmartArray;
  4460. }());
  4461. // Statics
  4462. SmartArray._GlobalId = 0;
  4463. BABYLON.SmartArray = SmartArray;
  4464. })(BABYLON || (BABYLON = {}));
  4465. //# sourceMappingURL=babylon.smartArray.js.map
  4466. var BABYLON;
  4467. (function (BABYLON) {
  4468. /**
  4469. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4470. * The underlying implementation relies on an associative array to ensure the best performances.
  4471. * The value can be anything including 'null' but except 'undefined'
  4472. */
  4473. var StringDictionary = (function () {
  4474. function StringDictionary() {
  4475. this._count = 0;
  4476. this._data = {};
  4477. }
  4478. /**
  4479. * This will clear this dictionary and copy the content from the 'source' one.
  4480. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4481. * @param source the dictionary to take the content from and copy to this dictionary
  4482. */
  4483. StringDictionary.prototype.copyFrom = function (source) {
  4484. var _this = this;
  4485. this.clear();
  4486. source.forEach(function (t, v) { return _this.add(t, v); });
  4487. };
  4488. /**
  4489. * Get a value based from its key
  4490. * @param key the given key to get the matching value from
  4491. * @return the value if found, otherwise undefined is returned
  4492. */
  4493. StringDictionary.prototype.get = function (key) {
  4494. var val = this._data[key];
  4495. if (val !== undefined) {
  4496. return val;
  4497. }
  4498. return undefined;
  4499. };
  4500. /**
  4501. * Get a value from its key or add it if it doesn't exist.
  4502. * This method will ensure you that a given key/data will be present in the dictionary.
  4503. * @param key the given key to get the matching value from
  4504. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4505. * The factory will only be invoked if there's no data for the given key.
  4506. * @return the value corresponding to the key.
  4507. */
  4508. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4509. var val = this.get(key);
  4510. if (val !== undefined) {
  4511. return val;
  4512. }
  4513. val = factory(key);
  4514. if (val) {
  4515. this.add(key, val);
  4516. }
  4517. return val;
  4518. };
  4519. /**
  4520. * Get a value from its key if present in the dictionary otherwise add it
  4521. * @param key the key to get the value from
  4522. * @param val if there's no such key/value pair in the dictionary add it with this value
  4523. * @return the value corresponding to the key
  4524. */
  4525. StringDictionary.prototype.getOrAdd = function (key, val) {
  4526. var curVal = this.get(key);
  4527. if (curVal !== undefined) {
  4528. return curVal;
  4529. }
  4530. this.add(key, val);
  4531. return val;
  4532. };
  4533. /**
  4534. * Check if there's a given key in the dictionary
  4535. * @param key the key to check for
  4536. * @return true if the key is present, false otherwise
  4537. */
  4538. StringDictionary.prototype.contains = function (key) {
  4539. return this._data[key] !== undefined;
  4540. };
  4541. /**
  4542. * Add a new key and its corresponding value
  4543. * @param key the key to add
  4544. * @param value the value corresponding to the key
  4545. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4546. */
  4547. StringDictionary.prototype.add = function (key, value) {
  4548. if (this._data[key] !== undefined) {
  4549. return false;
  4550. }
  4551. this._data[key] = value;
  4552. ++this._count;
  4553. return true;
  4554. };
  4555. StringDictionary.prototype.set = function (key, value) {
  4556. if (this._data[key] === undefined) {
  4557. return false;
  4558. }
  4559. this._data[key] = value;
  4560. return true;
  4561. };
  4562. /**
  4563. * Get the element of the given key and remove it from the dictionary
  4564. * @param key
  4565. */
  4566. StringDictionary.prototype.getAndRemove = function (key) {
  4567. var val = this.get(key);
  4568. if (val !== undefined) {
  4569. delete this._data[key];
  4570. --this._count;
  4571. return val;
  4572. }
  4573. return null;
  4574. };
  4575. /**
  4576. * Remove a key/value from the dictionary.
  4577. * @param key the key to remove
  4578. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4579. */
  4580. StringDictionary.prototype.remove = function (key) {
  4581. if (this.contains(key)) {
  4582. delete this._data[key];
  4583. --this._count;
  4584. return true;
  4585. }
  4586. return false;
  4587. };
  4588. /**
  4589. * Clear the whole content of the dictionary
  4590. */
  4591. StringDictionary.prototype.clear = function () {
  4592. this._data = {};
  4593. this._count = 0;
  4594. };
  4595. Object.defineProperty(StringDictionary.prototype, "count", {
  4596. get: function () {
  4597. return this._count;
  4598. },
  4599. enumerable: true,
  4600. configurable: true
  4601. });
  4602. /**
  4603. * Execute a callback on each key/val of the dictionary.
  4604. * Note that you can remove any element in this dictionary in the callback implementation
  4605. * @param callback the callback to execute on a given key/value pair
  4606. */
  4607. StringDictionary.prototype.forEach = function (callback) {
  4608. for (var cur in this._data) {
  4609. var val = this._data[cur];
  4610. callback(cur, val);
  4611. }
  4612. };
  4613. /**
  4614. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4615. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4616. * Note that you can remove any element in this dictionary in the callback implementation
  4617. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4618. */
  4619. StringDictionary.prototype.first = function (callback) {
  4620. for (var cur in this._data) {
  4621. var val = this._data[cur];
  4622. var res = callback(cur, val);
  4623. if (res) {
  4624. return res;
  4625. }
  4626. }
  4627. return null;
  4628. };
  4629. return StringDictionary;
  4630. }());
  4631. BABYLON.StringDictionary = StringDictionary;
  4632. })(BABYLON || (BABYLON = {}));
  4633. //# sourceMappingURL=babylon.stringDictionary.js.map
  4634. var BABYLON;
  4635. (function (BABYLON) {
  4636. // Screenshots
  4637. var screenshotCanvas;
  4638. var cloneValue = function (source, destinationObject) {
  4639. if (!source)
  4640. return null;
  4641. if (source instanceof BABYLON.Mesh) {
  4642. return null;
  4643. }
  4644. if (source instanceof BABYLON.SubMesh) {
  4645. return source.clone(destinationObject);
  4646. }
  4647. else if (source.clone) {
  4648. return source.clone();
  4649. }
  4650. return null;
  4651. };
  4652. var Tools = (function () {
  4653. function Tools() {
  4654. }
  4655. ;
  4656. Tools.Instantiate = function (className) {
  4657. var arr = className.split(".");
  4658. var fn = (window || this);
  4659. for (var i = 0, len = arr.length; i < len; i++) {
  4660. fn = fn[arr[i]];
  4661. }
  4662. if (typeof fn !== "function") {
  4663. return null;
  4664. }
  4665. return fn;
  4666. };
  4667. Tools.SetImmediate = function (action) {
  4668. if (window.setImmediate) {
  4669. window.setImmediate(action);
  4670. }
  4671. else {
  4672. setTimeout(action, 1);
  4673. }
  4674. };
  4675. Tools.IsExponentOfTwo = function (value) {
  4676. var count = 1;
  4677. do {
  4678. count *= 2;
  4679. } while (count < value);
  4680. return count === value;
  4681. };
  4682. Tools.GetExponentOfTwo = function (value, max) {
  4683. var count = 1;
  4684. do {
  4685. count *= 2;
  4686. } while (count < value);
  4687. if (count > max)
  4688. count = max;
  4689. return count;
  4690. };
  4691. Tools.GetFilename = function (path) {
  4692. var index = path.lastIndexOf("/");
  4693. if (index < 0)
  4694. return path;
  4695. return path.substring(index + 1);
  4696. };
  4697. Tools.GetDOMTextContent = function (element) {
  4698. var result = "";
  4699. var child = element.firstChild;
  4700. while (child) {
  4701. if (child.nodeType === 3) {
  4702. result += child.textContent;
  4703. }
  4704. child = child.nextSibling;
  4705. }
  4706. return result;
  4707. };
  4708. Tools.ToDegrees = function (angle) {
  4709. return angle * 180 / Math.PI;
  4710. };
  4711. Tools.ToRadians = function (angle) {
  4712. return angle * Math.PI / 180;
  4713. };
  4714. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4715. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4716. var output = "";
  4717. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4718. var i = 0;
  4719. var bytes = new Uint8Array(buffer);
  4720. while (i < bytes.length) {
  4721. chr1 = bytes[i++];
  4722. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4723. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4724. enc1 = chr1 >> 2;
  4725. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4726. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4727. enc4 = chr3 & 63;
  4728. if (isNaN(chr2)) {
  4729. enc3 = enc4 = 64;
  4730. }
  4731. else if (isNaN(chr3)) {
  4732. enc4 = 64;
  4733. }
  4734. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4735. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4736. }
  4737. return "data:image/png;base64," + output;
  4738. };
  4739. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4740. if (bias === void 0) { bias = null; }
  4741. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4742. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4743. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4744. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4745. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4746. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4747. }
  4748. if (bias) {
  4749. minimum.x -= minimum.x * bias.x + bias.y;
  4750. minimum.y -= minimum.y * bias.x + bias.y;
  4751. minimum.z -= minimum.z * bias.x + bias.y;
  4752. maximum.x += maximum.x * bias.x + bias.y;
  4753. maximum.y += maximum.y * bias.x + bias.y;
  4754. maximum.z += maximum.z * bias.x + bias.y;
  4755. }
  4756. return {
  4757. minimum: minimum,
  4758. maximum: maximum
  4759. };
  4760. };
  4761. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4762. if (bias === void 0) { bias = null; }
  4763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4765. if (!stride) {
  4766. stride = 3;
  4767. }
  4768. for (var index = start; index < start + count; index++) {
  4769. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4770. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4771. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4772. }
  4773. if (bias) {
  4774. minimum.x -= minimum.x * bias.x + bias.y;
  4775. minimum.y -= minimum.y * bias.x + bias.y;
  4776. minimum.z -= minimum.z * bias.x + bias.y;
  4777. maximum.x += maximum.x * bias.x + bias.y;
  4778. maximum.y += maximum.y * bias.x + bias.y;
  4779. maximum.z += maximum.z * bias.x + bias.y;
  4780. }
  4781. return {
  4782. minimum: minimum,
  4783. maximum: maximum
  4784. };
  4785. };
  4786. Tools.Vector2ArrayFeeder = function (array) {
  4787. return function (index) {
  4788. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4789. var length = isFloatArray ? array.length / 2 : array.length;
  4790. if (index >= length) {
  4791. return null;
  4792. }
  4793. if (isFloatArray) {
  4794. var fa = array;
  4795. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4796. }
  4797. var a = array;
  4798. return a[index];
  4799. };
  4800. };
  4801. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4802. if (bias === void 0) { bias = null; }
  4803. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4804. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4805. var i = 0;
  4806. var cur = feeder(i++);
  4807. while (cur) {
  4808. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4809. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4810. cur = feeder(i++);
  4811. }
  4812. if (bias) {
  4813. minimum.x -= minimum.x * bias.x + bias.y;
  4814. minimum.y -= minimum.y * bias.x + bias.y;
  4815. maximum.x += maximum.x * bias.x + bias.y;
  4816. maximum.y += maximum.y * bias.x + bias.y;
  4817. }
  4818. return {
  4819. minimum: minimum,
  4820. maximum: maximum
  4821. };
  4822. };
  4823. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4824. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4825. return undefined;
  4826. return Array.isArray(obj) ? obj : [obj];
  4827. };
  4828. // Misc.
  4829. Tools.GetPointerPrefix = function () {
  4830. var eventPrefix = "pointer";
  4831. // Check if pointer events are supported
  4832. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4833. eventPrefix = "mouse";
  4834. }
  4835. return eventPrefix;
  4836. };
  4837. /**
  4838. * @param func - the function to be called
  4839. * @param requester - the object that will request the next frame. Falls back to window.
  4840. */
  4841. Tools.QueueNewFrame = function (func, requester) {
  4842. if (requester === void 0) { requester = window; }
  4843. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4844. /*if(requester.isPresenting) {
  4845. return;
  4846. } else*/ if (requester.requestAnimationFrame)
  4847. requester.requestAnimationFrame(func);
  4848. else if (requester.msRequestAnimationFrame)
  4849. requester.msRequestAnimationFrame(func);
  4850. else if (requester.webkitRequestAnimationFrame)
  4851. requester.webkitRequestAnimationFrame(func);
  4852. else if (requester.mozRequestAnimationFrame)
  4853. requester.mozRequestAnimationFrame(func);
  4854. else if (requester.oRequestAnimationFrame)
  4855. requester.oRequestAnimationFrame(func);
  4856. else {
  4857. window.setTimeout(func, 16);
  4858. }
  4859. };
  4860. Tools.RequestFullscreen = function (element) {
  4861. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4862. if (!requestFunction)
  4863. return;
  4864. requestFunction.call(element);
  4865. };
  4866. Tools.ExitFullscreen = function () {
  4867. if (document.exitFullscreen) {
  4868. document.exitFullscreen();
  4869. }
  4870. else if (document.mozCancelFullScreen) {
  4871. document.mozCancelFullScreen();
  4872. }
  4873. else if (document.webkitCancelFullScreen) {
  4874. document.webkitCancelFullScreen();
  4875. }
  4876. else if (document.msCancelFullScreen) {
  4877. document.msCancelFullScreen();
  4878. }
  4879. };
  4880. Tools.SetCorsBehavior = function (url, img) {
  4881. if (Tools.CorsBehavior) {
  4882. switch (typeof (Tools.CorsBehavior)) {
  4883. case "function":
  4884. var result = Tools.CorsBehavior(url);
  4885. if (result) {
  4886. return result;
  4887. }
  4888. break;
  4889. case "string":
  4890. default:
  4891. img.crossOrigin = Tools.CorsBehavior;
  4892. break;
  4893. }
  4894. }
  4895. };
  4896. // External files
  4897. Tools.CleanUrl = function (url) {
  4898. url = url.replace(/#/mg, "%23");
  4899. return url;
  4900. };
  4901. Tools.LoadImage = function (url, onload, onerror, database) {
  4902. if (url instanceof ArrayBuffer) {
  4903. url = Tools.EncodeArrayBufferTobase64(url);
  4904. }
  4905. url = Tools.CleanUrl(url);
  4906. var img = new Image();
  4907. if (url.substr(0, 5) !== "data:") {
  4908. Tools.SetCorsBehavior(url, img);
  4909. }
  4910. img.onload = function () {
  4911. onload(img);
  4912. };
  4913. img.onerror = function (err) {
  4914. Tools.Error("Error while trying to load image: " + url);
  4915. if (Tools.UseFallbackTexture) {
  4916. img.src = Tools.fallbackTexture;
  4917. onload(img);
  4918. }
  4919. else {
  4920. onerror();
  4921. }
  4922. };
  4923. var noIndexedDB = function () {
  4924. img.src = url;
  4925. };
  4926. var loadFromIndexedDB = function () {
  4927. database.loadImageFromDB(url, img);
  4928. };
  4929. //ANY database to do!
  4930. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4931. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4932. }
  4933. else {
  4934. if (url.indexOf("file:") === -1) {
  4935. noIndexedDB();
  4936. }
  4937. else {
  4938. var textureName = url.substring(5).toLowerCase();
  4939. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  4940. try {
  4941. var blobURL;
  4942. try {
  4943. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4944. }
  4945. catch (ex) {
  4946. // Chrome doesn't support oneTimeOnly parameter
  4947. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4948. }
  4949. img.src = blobURL;
  4950. }
  4951. catch (e) {
  4952. img.src = null;
  4953. }
  4954. }
  4955. else {
  4956. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  4957. img.src = Tools.fallbackTexture;
  4958. }
  4959. }
  4960. }
  4961. return img;
  4962. };
  4963. //ANY
  4964. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4965. url = Tools.CleanUrl(url);
  4966. var noIndexedDB = function () {
  4967. var request = new XMLHttpRequest();
  4968. var loadUrl = Tools.BaseUrl + url;
  4969. request.open('GET', loadUrl, true);
  4970. if (useArrayBuffer) {
  4971. request.responseType = "arraybuffer";
  4972. }
  4973. request.onprogress = progressCallBack;
  4974. request.onreadystatechange = function () {
  4975. if (request.readyState === 4) {
  4976. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4977. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4978. callback(!useArrayBuffer ? request.responseText : request.response);
  4979. }
  4980. else {
  4981. if (onError) {
  4982. onError();
  4983. }
  4984. else {
  4985. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4986. }
  4987. }
  4988. }
  4989. };
  4990. request.send(null);
  4991. };
  4992. var loadFromIndexedDB = function () {
  4993. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4994. };
  4995. if (url.indexOf("file:") !== -1) {
  4996. var fileName = url.substring(5).toLowerCase();
  4997. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  4998. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4999. }
  5000. else {
  5001. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5002. }
  5003. }
  5004. else {
  5005. // Caching all files
  5006. if (database && database.enableSceneOffline) {
  5007. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5008. }
  5009. else {
  5010. noIndexedDB();
  5011. }
  5012. }
  5013. };
  5014. /**
  5015. * Load a script (identified by an url). When the url returns, the
  5016. * content of this file is added into a new script element, attached to the DOM (body element)
  5017. */
  5018. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5019. var head = document.getElementsByTagName('head')[0];
  5020. var script = document.createElement('script');
  5021. script.type = 'text/javascript';
  5022. script.src = scriptUrl;
  5023. var self = this;
  5024. script.onload = function () {
  5025. if (onSuccess) {
  5026. onSuccess();
  5027. }
  5028. };
  5029. script.onerror = function () {
  5030. if (onError) {
  5031. onError();
  5032. }
  5033. };
  5034. head.appendChild(script);
  5035. };
  5036. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5037. var reader = new FileReader();
  5038. reader.onload = function (e) {
  5039. //target doesn't have result from ts 1.3
  5040. callback(e.target['result']);
  5041. };
  5042. reader.onprogress = progressCallback;
  5043. reader.readAsDataURL(fileToLoad);
  5044. };
  5045. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5046. var reader = new FileReader();
  5047. reader.onerror = function (e) {
  5048. Tools.Log("Error while reading file: " + fileToLoad.name);
  5049. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5050. };
  5051. reader.onload = function (e) {
  5052. //target doesn't have result from ts 1.3
  5053. callback(e.target['result']);
  5054. };
  5055. reader.onprogress = progressCallBack;
  5056. if (!useArrayBuffer) {
  5057. // Asynchronous read
  5058. reader.readAsText(fileToLoad);
  5059. }
  5060. else {
  5061. reader.readAsArrayBuffer(fileToLoad);
  5062. }
  5063. };
  5064. //returns a downloadable url to a file content.
  5065. Tools.FileAsURL = function (content) {
  5066. var fileBlob = new Blob([content]);
  5067. var url = window.URL || window.webkitURL;
  5068. var link = url.createObjectURL(fileBlob);
  5069. return link;
  5070. };
  5071. // Misc.
  5072. Tools.Format = function (value, decimals) {
  5073. if (decimals === void 0) { decimals = 2; }
  5074. return value.toFixed(decimals);
  5075. };
  5076. Tools.CheckExtends = function (v, min, max) {
  5077. if (v.x < min.x)
  5078. min.x = v.x;
  5079. if (v.y < min.y)
  5080. min.y = v.y;
  5081. if (v.z < min.z)
  5082. min.z = v.z;
  5083. if (v.x > max.x)
  5084. max.x = v.x;
  5085. if (v.y > max.y)
  5086. max.y = v.y;
  5087. if (v.z > max.z)
  5088. max.z = v.z;
  5089. };
  5090. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5091. for (var prop in source) {
  5092. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5093. continue;
  5094. }
  5095. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5096. continue;
  5097. }
  5098. var sourceValue = source[prop];
  5099. var typeOfSourceValue = typeof sourceValue;
  5100. if (typeOfSourceValue === "function") {
  5101. continue;
  5102. }
  5103. if (typeOfSourceValue === "object") {
  5104. if (sourceValue instanceof Array) {
  5105. destination[prop] = [];
  5106. if (sourceValue.length > 0) {
  5107. if (typeof sourceValue[0] == "object") {
  5108. for (var index = 0; index < sourceValue.length; index++) {
  5109. var clonedValue = cloneValue(sourceValue[index], destination);
  5110. if (destination[prop].indexOf(clonedValue) === -1) {
  5111. destination[prop].push(clonedValue);
  5112. }
  5113. }
  5114. }
  5115. else {
  5116. destination[prop] = sourceValue.slice(0);
  5117. }
  5118. }
  5119. }
  5120. else {
  5121. destination[prop] = cloneValue(sourceValue, destination);
  5122. }
  5123. }
  5124. else {
  5125. destination[prop] = sourceValue;
  5126. }
  5127. }
  5128. };
  5129. Tools.IsEmpty = function (obj) {
  5130. for (var i in obj) {
  5131. return false;
  5132. }
  5133. return true;
  5134. };
  5135. Tools.RegisterTopRootEvents = function (events) {
  5136. for (var index = 0; index < events.length; index++) {
  5137. var event = events[index];
  5138. window.addEventListener(event.name, event.handler, false);
  5139. try {
  5140. if (window.parent) {
  5141. window.parent.addEventListener(event.name, event.handler, false);
  5142. }
  5143. }
  5144. catch (e) {
  5145. }
  5146. }
  5147. };
  5148. Tools.UnregisterTopRootEvents = function (events) {
  5149. for (var index = 0; index < events.length; index++) {
  5150. var event = events[index];
  5151. window.removeEventListener(event.name, event.handler);
  5152. try {
  5153. if (window.parent) {
  5154. window.parent.removeEventListener(event.name, event.handler);
  5155. }
  5156. }
  5157. catch (e) {
  5158. }
  5159. }
  5160. };
  5161. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5162. if (mimeType === void 0) { mimeType = "image/png"; }
  5163. // Read the contents of the framebuffer
  5164. var numberOfChannelsByLine = width * 4;
  5165. var halfHeight = height / 2;
  5166. //Reading datas from WebGL
  5167. var data = engine.readPixels(0, 0, width, height);
  5168. //To flip image on Y axis.
  5169. for (var i = 0; i < halfHeight; i++) {
  5170. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5171. var currentCell = j + i * numberOfChannelsByLine;
  5172. var targetLine = height - i - 1;
  5173. var targetCell = j + targetLine * numberOfChannelsByLine;
  5174. var temp = data[currentCell];
  5175. data[currentCell] = data[targetCell];
  5176. data[targetCell] = temp;
  5177. }
  5178. }
  5179. // Create a 2D canvas to store the result
  5180. if (!screenshotCanvas) {
  5181. screenshotCanvas = document.createElement('canvas');
  5182. }
  5183. screenshotCanvas.width = width;
  5184. screenshotCanvas.height = height;
  5185. var context = screenshotCanvas.getContext('2d');
  5186. // Copy the pixels to a 2D canvas
  5187. var imageData = context.createImageData(width, height);
  5188. var castData = (imageData.data);
  5189. castData.set(data);
  5190. context.putImageData(imageData, 0, 0);
  5191. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5192. };
  5193. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5194. if (mimeType === void 0) { mimeType = "image/png"; }
  5195. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5196. if (successCallback) {
  5197. successCallback(base64Image);
  5198. }
  5199. else {
  5200. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5201. if (("download" in document.createElement("a"))) {
  5202. var a = window.document.createElement("a");
  5203. a.href = base64Image;
  5204. var date = new Date();
  5205. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5206. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5207. window.document.body.appendChild(a);
  5208. a.addEventListener("click", function () {
  5209. a.parentElement.removeChild(a);
  5210. });
  5211. a.click();
  5212. }
  5213. else {
  5214. var newWindow = window.open("");
  5215. var img = newWindow.document.createElement("img");
  5216. img.src = base64Image;
  5217. newWindow.document.body.appendChild(img);
  5218. }
  5219. }
  5220. };
  5221. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5222. if (mimeType === void 0) { mimeType = "image/png"; }
  5223. var width;
  5224. var height;
  5225. // If a precision value is specified
  5226. if (size.precision) {
  5227. width = Math.round(engine.getRenderWidth() * size.precision);
  5228. height = Math.round(width / engine.getAspectRatio(camera));
  5229. }
  5230. else if (size.width && size.height) {
  5231. width = size.width;
  5232. height = size.height;
  5233. }
  5234. else if (size.width && !size.height) {
  5235. width = size.width;
  5236. height = Math.round(width / engine.getAspectRatio(camera));
  5237. }
  5238. else if (size.height && !size.width) {
  5239. height = size.height;
  5240. width = Math.round(height * engine.getAspectRatio(camera));
  5241. }
  5242. else if (!isNaN(size)) {
  5243. height = size;
  5244. width = size;
  5245. }
  5246. else {
  5247. Tools.Error("Invalid 'size' parameter !");
  5248. return;
  5249. }
  5250. if (!screenshotCanvas) {
  5251. screenshotCanvas = document.createElement('canvas');
  5252. }
  5253. screenshotCanvas.width = width;
  5254. screenshotCanvas.height = height;
  5255. var renderContext = screenshotCanvas.getContext("2d");
  5256. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5257. var newWidth = width;
  5258. var newHeight = newWidth / ratio;
  5259. if (newHeight > height) {
  5260. newHeight = height;
  5261. newWidth = newHeight * ratio;
  5262. }
  5263. var offsetX = Math.max(0, width - newWidth) / 2;
  5264. var offsetY = Math.max(0, height - newHeight) / 2;
  5265. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5266. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5267. };
  5268. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5269. if (mimeType === void 0) { mimeType = "image/png"; }
  5270. var width;
  5271. var height;
  5272. //If a precision value is specified
  5273. if (size.precision) {
  5274. width = Math.round(engine.getRenderWidth() * size.precision);
  5275. height = Math.round(width / engine.getAspectRatio(camera));
  5276. size = { width: width, height: height };
  5277. }
  5278. else if (size.width && size.height) {
  5279. width = size.width;
  5280. height = size.height;
  5281. }
  5282. else if (size.width && !size.height) {
  5283. width = size.width;
  5284. height = Math.round(width / engine.getAspectRatio(camera));
  5285. size = { width: width, height: height };
  5286. }
  5287. else if (size.height && !size.width) {
  5288. height = size.height;
  5289. width = Math.round(height * engine.getAspectRatio(camera));
  5290. size = { width: width, height: height };
  5291. }
  5292. else if (!isNaN(size)) {
  5293. height = size;
  5294. width = size;
  5295. }
  5296. else {
  5297. Tools.Error("Invalid 'size' parameter !");
  5298. return;
  5299. }
  5300. var scene = camera.getScene();
  5301. var previousCamera = null;
  5302. if (scene.activeCamera !== camera) {
  5303. previousCamera = scene.activeCamera;
  5304. scene.activeCamera = camera;
  5305. }
  5306. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5307. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5308. texture.renderList = scene.meshes;
  5309. texture.onAfterRenderObservable.add(function () {
  5310. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5311. });
  5312. scene.incrementRenderId();
  5313. scene.resetCachedMaterial();
  5314. texture.render(true);
  5315. texture.dispose();
  5316. if (previousCamera) {
  5317. scene.activeCamera = previousCamera;
  5318. }
  5319. camera.getProjectionMatrix(true); // Force cache refresh;
  5320. };
  5321. // XHR response validator for local file scenario
  5322. Tools.ValidateXHRData = function (xhr, dataType) {
  5323. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5324. if (dataType === void 0) { dataType = 7; }
  5325. try {
  5326. if (dataType & 1) {
  5327. if (xhr.responseText && xhr.responseText.length > 0) {
  5328. return true;
  5329. }
  5330. else if (dataType === 1) {
  5331. return false;
  5332. }
  5333. }
  5334. if (dataType & 2) {
  5335. // Check header width and height since there is no "TGA" magic number
  5336. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5337. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5338. return true;
  5339. }
  5340. else if (dataType === 2) {
  5341. return false;
  5342. }
  5343. }
  5344. if (dataType & 4) {
  5345. // Check for the "DDS" magic number
  5346. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5347. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5348. return true;
  5349. }
  5350. else {
  5351. return false;
  5352. }
  5353. }
  5354. }
  5355. catch (e) {
  5356. }
  5357. return false;
  5358. };
  5359. /**
  5360. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5361. * Be aware Math.random() could cause collisions, but:
  5362. * "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"
  5363. */
  5364. Tools.RandomId = function () {
  5365. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5366. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5367. return v.toString(16);
  5368. });
  5369. };
  5370. Object.defineProperty(Tools, "NoneLogLevel", {
  5371. get: function () {
  5372. return Tools._NoneLogLevel;
  5373. },
  5374. enumerable: true,
  5375. configurable: true
  5376. });
  5377. Object.defineProperty(Tools, "MessageLogLevel", {
  5378. get: function () {
  5379. return Tools._MessageLogLevel;
  5380. },
  5381. enumerable: true,
  5382. configurable: true
  5383. });
  5384. Object.defineProperty(Tools, "WarningLogLevel", {
  5385. get: function () {
  5386. return Tools._WarningLogLevel;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(Tools, "ErrorLogLevel", {
  5392. get: function () {
  5393. return Tools._ErrorLogLevel;
  5394. },
  5395. enumerable: true,
  5396. configurable: true
  5397. });
  5398. Object.defineProperty(Tools, "AllLogLevel", {
  5399. get: function () {
  5400. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Tools._AddLogEntry = function (entry) {
  5406. Tools._LogCache = entry + Tools._LogCache;
  5407. if (Tools.OnNewCacheEntry) {
  5408. Tools.OnNewCacheEntry(entry);
  5409. }
  5410. };
  5411. Tools._FormatMessage = function (message) {
  5412. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5413. var date = new Date();
  5414. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5415. };
  5416. Tools._LogDisabled = function (message) {
  5417. // nothing to do
  5418. };
  5419. Tools._LogEnabled = function (message) {
  5420. var formattedMessage = Tools._FormatMessage(message);
  5421. console.log("BJS - " + formattedMessage);
  5422. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5423. Tools._AddLogEntry(entry);
  5424. };
  5425. Tools._WarnDisabled = function (message) {
  5426. // nothing to do
  5427. };
  5428. Tools._WarnEnabled = function (message) {
  5429. var formattedMessage = Tools._FormatMessage(message);
  5430. console.warn("BJS - " + formattedMessage);
  5431. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5432. Tools._AddLogEntry(entry);
  5433. };
  5434. Tools._ErrorDisabled = function (message) {
  5435. // nothing to do
  5436. };
  5437. Tools._ErrorEnabled = function (message) {
  5438. Tools.errorsCount++;
  5439. var formattedMessage = Tools._FormatMessage(message);
  5440. console.error("BJS - " + formattedMessage);
  5441. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5442. Tools._AddLogEntry(entry);
  5443. };
  5444. Object.defineProperty(Tools, "LogCache", {
  5445. get: function () {
  5446. return Tools._LogCache;
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Tools.ClearLogCache = function () {
  5452. Tools._LogCache = "";
  5453. Tools.errorsCount = 0;
  5454. };
  5455. Object.defineProperty(Tools, "LogLevels", {
  5456. set: function (level) {
  5457. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5458. Tools.Log = Tools._LogEnabled;
  5459. }
  5460. else {
  5461. Tools.Log = Tools._LogDisabled;
  5462. }
  5463. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5464. Tools.Warn = Tools._WarnEnabled;
  5465. }
  5466. else {
  5467. Tools.Warn = Tools._WarnDisabled;
  5468. }
  5469. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5470. Tools.Error = Tools._ErrorEnabled;
  5471. }
  5472. else {
  5473. Tools.Error = Tools._ErrorDisabled;
  5474. }
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5480. get: function () {
  5481. return Tools._PerformanceNoneLogLevel;
  5482. },
  5483. enumerable: true,
  5484. configurable: true
  5485. });
  5486. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5487. get: function () {
  5488. return Tools._PerformanceUserMarkLogLevel;
  5489. },
  5490. enumerable: true,
  5491. configurable: true
  5492. });
  5493. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5494. get: function () {
  5495. return Tools._PerformanceConsoleLogLevel;
  5496. },
  5497. enumerable: true,
  5498. configurable: true
  5499. });
  5500. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5501. set: function (level) {
  5502. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5503. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5504. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5505. return;
  5506. }
  5507. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5508. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5509. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5510. return;
  5511. }
  5512. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5513. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5519. };
  5520. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5521. };
  5522. Tools._StartUserMark = function (counterName, condition) {
  5523. if (condition === void 0) { condition = true; }
  5524. if (!condition || !Tools._performance.mark) {
  5525. return;
  5526. }
  5527. Tools._performance.mark(counterName + "-Begin");
  5528. };
  5529. Tools._EndUserMark = function (counterName, condition) {
  5530. if (condition === void 0) { condition = true; }
  5531. if (!condition || !Tools._performance.mark) {
  5532. return;
  5533. }
  5534. Tools._performance.mark(counterName + "-End");
  5535. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5536. };
  5537. Tools._StartPerformanceConsole = function (counterName, condition) {
  5538. if (condition === void 0) { condition = true; }
  5539. if (!condition) {
  5540. return;
  5541. }
  5542. Tools._StartUserMark(counterName, condition);
  5543. if (console.time) {
  5544. console.time(counterName);
  5545. }
  5546. };
  5547. Tools._EndPerformanceConsole = function (counterName, condition) {
  5548. if (condition === void 0) { condition = true; }
  5549. if (!condition) {
  5550. return;
  5551. }
  5552. Tools._EndUserMark(counterName, condition);
  5553. if (console.time) {
  5554. console.timeEnd(counterName);
  5555. }
  5556. };
  5557. Object.defineProperty(Tools, "Now", {
  5558. get: function () {
  5559. if (window.performance && window.performance.now) {
  5560. return window.performance.now();
  5561. }
  5562. return new Date().getTime();
  5563. },
  5564. enumerable: true,
  5565. configurable: true
  5566. });
  5567. /**
  5568. * This method will return the name of the class used to create the instance of the given object.
  5569. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5570. * @param object the object to get the class name from
  5571. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5572. */
  5573. Tools.getClassName = function (object, isType) {
  5574. if (isType === void 0) { isType = false; }
  5575. var name = null;
  5576. if (!isType && object.getClassName) {
  5577. name = object.getClassName();
  5578. }
  5579. else {
  5580. if (object instanceof Object) {
  5581. var classObj = isType ? object : Object.getPrototypeOf(object);
  5582. name = classObj.constructor["__bjsclassName__"];
  5583. }
  5584. if (!name) {
  5585. name = typeof object;
  5586. }
  5587. }
  5588. return name;
  5589. };
  5590. Tools.first = function (array, predicate) {
  5591. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5592. var el = array_1[_i];
  5593. if (predicate(el)) {
  5594. return el;
  5595. }
  5596. }
  5597. };
  5598. /**
  5599. * This method will return the name of the full name of the class, including its owning module (if any).
  5600. * 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).
  5601. * @param object the object to get the class name from
  5602. * @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.
  5603. */
  5604. Tools.getFullClassName = function (object, isType) {
  5605. if (isType === void 0) { isType = false; }
  5606. var className = null;
  5607. var moduleName = null;
  5608. if (!isType && object.getClassName) {
  5609. className = object.getClassName();
  5610. }
  5611. else {
  5612. if (object instanceof Object) {
  5613. var classObj = isType ? object : Object.getPrototypeOf(object);
  5614. className = classObj.constructor["__bjsclassName__"];
  5615. moduleName = classObj.constructor["__bjsmoduleName__"];
  5616. }
  5617. if (!className) {
  5618. className = typeof object;
  5619. }
  5620. }
  5621. if (!className) {
  5622. return null;
  5623. }
  5624. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5625. };
  5626. /**
  5627. * 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.
  5628. * @param array
  5629. */
  5630. Tools.arrayOrStringFeeder = function (array) {
  5631. return function (index) {
  5632. if (index >= array.length) {
  5633. return null;
  5634. }
  5635. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5636. if (val && val.getHashCode) {
  5637. val = val.getHashCode();
  5638. }
  5639. if (typeof val === "string") {
  5640. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5641. }
  5642. return val;
  5643. };
  5644. };
  5645. /**
  5646. * Compute the hashCode of a stream of number
  5647. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5648. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5649. * @return the hash code computed
  5650. */
  5651. Tools.hashCodeFromStream = function (feeder) {
  5652. // Based from here: http://stackoverflow.com/a/7616484/802124
  5653. var hash = 0;
  5654. var index = 0;
  5655. var chr = feeder(index++);
  5656. while (chr != null) {
  5657. hash = ((hash << 5) - hash) + chr;
  5658. hash |= 0; // Convert to 32bit integer
  5659. chr = feeder(index++);
  5660. }
  5661. return hash;
  5662. };
  5663. return Tools;
  5664. }());
  5665. Tools.BaseUrl = "";
  5666. Tools.CorsBehavior = "anonymous";
  5667. Tools.UseFallbackTexture = true;
  5668. // Used in case of a texture loading problem
  5669. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  5670. // Logs
  5671. Tools._NoneLogLevel = 0;
  5672. Tools._MessageLogLevel = 1;
  5673. Tools._WarningLogLevel = 2;
  5674. Tools._ErrorLogLevel = 4;
  5675. Tools._LogCache = "";
  5676. Tools.errorsCount = 0;
  5677. Tools.Log = Tools._LogEnabled;
  5678. Tools.Warn = Tools._WarnEnabled;
  5679. Tools.Error = Tools._ErrorEnabled;
  5680. // Performances
  5681. Tools._PerformanceNoneLogLevel = 0;
  5682. Tools._PerformanceUserMarkLogLevel = 1;
  5683. Tools._PerformanceConsoleLogLevel = 2;
  5684. Tools._performance = window.performance;
  5685. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5686. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5687. BABYLON.Tools = Tools;
  5688. /**
  5689. * This class is used to track a performance counter which is number based.
  5690. * The user has access to many properties which give statistics of different nature
  5691. *
  5692. * The implementer can track two kinds of Performance Counter: time and count
  5693. * 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.
  5694. * 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.
  5695. */
  5696. var PerfCounter = (function () {
  5697. function PerfCounter() {
  5698. this._startMonitoringTime = 0;
  5699. this._min = 0;
  5700. this._max = 0;
  5701. this._average = 0;
  5702. this._lastSecAverage = 0;
  5703. this._current = 0;
  5704. this._totalValueCount = 0;
  5705. this._totalAccumulated = 0;
  5706. this._lastSecAccumulated = 0;
  5707. this._lastSecTime = 0;
  5708. this._lastSecValueCount = 0;
  5709. }
  5710. Object.defineProperty(PerfCounter.prototype, "min", {
  5711. /**
  5712. * Returns the smallest value ever
  5713. */
  5714. get: function () {
  5715. return this._min;
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(PerfCounter.prototype, "max", {
  5721. /**
  5722. * Returns the biggest value ever
  5723. */
  5724. get: function () {
  5725. return this._max;
  5726. },
  5727. enumerable: true,
  5728. configurable: true
  5729. });
  5730. Object.defineProperty(PerfCounter.prototype, "average", {
  5731. /**
  5732. * Returns the average value since the performance counter is running
  5733. */
  5734. get: function () {
  5735. return this._average;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5741. /**
  5742. * Returns the average value of the last second the counter was monitored
  5743. */
  5744. get: function () {
  5745. return this._lastSecAverage;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(PerfCounter.prototype, "current", {
  5751. /**
  5752. * Returns the current value
  5753. */
  5754. get: function () {
  5755. return this._current;
  5756. },
  5757. enumerable: true,
  5758. configurable: true
  5759. });
  5760. Object.defineProperty(PerfCounter.prototype, "total", {
  5761. get: function () {
  5762. return this._totalAccumulated;
  5763. },
  5764. enumerable: true,
  5765. configurable: true
  5766. });
  5767. /**
  5768. * Call this method to start monitoring a new frame.
  5769. * 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.
  5770. */
  5771. PerfCounter.prototype.fetchNewFrame = function () {
  5772. this._totalValueCount++;
  5773. this._current = 0;
  5774. this._lastSecValueCount++;
  5775. };
  5776. /**
  5777. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5778. * @param newCount the count value to add to the monitored count
  5779. * @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.
  5780. */
  5781. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5782. this._current += newCount;
  5783. if (fetchResult) {
  5784. this._fetchResult();
  5785. }
  5786. };
  5787. /**
  5788. * Start monitoring this performance counter
  5789. */
  5790. PerfCounter.prototype.beginMonitoring = function () {
  5791. this._startMonitoringTime = Tools.Now;
  5792. };
  5793. /**
  5794. * Compute the time lapsed since the previous beginMonitoring() call.
  5795. * @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
  5796. */
  5797. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5798. if (newFrame === void 0) { newFrame = true; }
  5799. if (newFrame) {
  5800. this.fetchNewFrame();
  5801. }
  5802. var currentTime = Tools.Now;
  5803. this._current = currentTime - this._startMonitoringTime;
  5804. if (newFrame) {
  5805. this._fetchResult();
  5806. }
  5807. };
  5808. PerfCounter.prototype._fetchResult = function () {
  5809. this._totalAccumulated += this._current;
  5810. this._lastSecAccumulated += this._current;
  5811. // Min/Max update
  5812. this._min = Math.min(this._min, this._current);
  5813. this._max = Math.max(this._max, this._current);
  5814. this._average = this._totalAccumulated / this._totalValueCount;
  5815. // Reset last sec?
  5816. var now = Tools.Now;
  5817. if ((now - this._lastSecTime) > 1000) {
  5818. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5819. this._lastSecTime = now;
  5820. this._lastSecAccumulated = 0;
  5821. this._lastSecValueCount = 0;
  5822. }
  5823. };
  5824. return PerfCounter;
  5825. }());
  5826. BABYLON.PerfCounter = PerfCounter;
  5827. /**
  5828. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5829. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5830. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5831. * @param name The name of the class, case should be preserved
  5832. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5833. */
  5834. function className(name, module) {
  5835. return function (target) {
  5836. target["__bjsclassName__"] = name;
  5837. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5838. };
  5839. }
  5840. BABYLON.className = className;
  5841. /**
  5842. * An implementation of a loop for asynchronous functions.
  5843. */
  5844. var AsyncLoop = (function () {
  5845. /**
  5846. * Constroctor.
  5847. * @param iterations the number of iterations.
  5848. * @param _fn the function to run each iteration
  5849. * @param _successCallback the callback that will be called upon succesful execution
  5850. * @param offset starting offset.
  5851. */
  5852. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5853. if (offset === void 0) { offset = 0; }
  5854. this.iterations = iterations;
  5855. this._fn = _fn;
  5856. this._successCallback = _successCallback;
  5857. this.index = offset - 1;
  5858. this._done = false;
  5859. }
  5860. /**
  5861. * Execute the next iteration. Must be called after the last iteration was finished.
  5862. */
  5863. AsyncLoop.prototype.executeNext = function () {
  5864. if (!this._done) {
  5865. if (this.index + 1 < this.iterations) {
  5866. ++this.index;
  5867. this._fn(this);
  5868. }
  5869. else {
  5870. this.breakLoop();
  5871. }
  5872. }
  5873. };
  5874. /**
  5875. * Break the loop and run the success callback.
  5876. */
  5877. AsyncLoop.prototype.breakLoop = function () {
  5878. this._done = true;
  5879. this._successCallback();
  5880. };
  5881. /**
  5882. * Helper function
  5883. */
  5884. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5885. if (offset === void 0) { offset = 0; }
  5886. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5887. loop.executeNext();
  5888. return loop;
  5889. };
  5890. /**
  5891. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5892. * @param iterations total number of iterations
  5893. * @param syncedIterations number of synchronous iterations in each async iteration.
  5894. * @param fn the function to call each iteration.
  5895. * @param callback a success call back that will be called when iterating stops.
  5896. * @param breakFunction a break condition (optional)
  5897. * @param timeout timeout settings for the setTimeout function. default - 0.
  5898. * @constructor
  5899. */
  5900. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5901. if (timeout === void 0) { timeout = 0; }
  5902. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5903. if (breakFunction && breakFunction())
  5904. loop.breakLoop();
  5905. else {
  5906. setTimeout(function () {
  5907. for (var i = 0; i < syncedIterations; ++i) {
  5908. var iteration = (loop.index * syncedIterations) + i;
  5909. if (iteration >= iterations)
  5910. break;
  5911. fn(iteration);
  5912. if (breakFunction && breakFunction()) {
  5913. loop.breakLoop();
  5914. break;
  5915. }
  5916. }
  5917. loop.executeNext();
  5918. }, timeout);
  5919. }
  5920. }, callback);
  5921. };
  5922. return AsyncLoop;
  5923. }());
  5924. BABYLON.AsyncLoop = AsyncLoop;
  5925. })(BABYLON || (BABYLON = {}));
  5926. //# sourceMappingURL=babylon.tools.js.map
  5927. var BABYLON;
  5928. (function (BABYLON) {
  5929. var Internals;
  5930. (function (Internals) {
  5931. var _AlphaState = (function () {
  5932. /**
  5933. * Initializes the state.
  5934. */
  5935. function _AlphaState() {
  5936. this._isAlphaBlendDirty = false;
  5937. this._isBlendFunctionParametersDirty = false;
  5938. this._alphaBlend = false;
  5939. this._blendFunctionParameters = new Array(4);
  5940. this.reset();
  5941. }
  5942. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5943. get: function () {
  5944. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5945. },
  5946. enumerable: true,
  5947. configurable: true
  5948. });
  5949. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5950. get: function () {
  5951. return this._alphaBlend;
  5952. },
  5953. set: function (value) {
  5954. if (this._alphaBlend === value) {
  5955. return;
  5956. }
  5957. this._alphaBlend = value;
  5958. this._isAlphaBlendDirty = true;
  5959. },
  5960. enumerable: true,
  5961. configurable: true
  5962. });
  5963. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5964. if (this._blendFunctionParameters[0] === value0 &&
  5965. this._blendFunctionParameters[1] === value1 &&
  5966. this._blendFunctionParameters[2] === value2 &&
  5967. this._blendFunctionParameters[3] === value3) {
  5968. return;
  5969. }
  5970. this._blendFunctionParameters[0] = value0;
  5971. this._blendFunctionParameters[1] = value1;
  5972. this._blendFunctionParameters[2] = value2;
  5973. this._blendFunctionParameters[3] = value3;
  5974. this._isBlendFunctionParametersDirty = true;
  5975. };
  5976. _AlphaState.prototype.reset = function () {
  5977. this._alphaBlend = false;
  5978. this._blendFunctionParameters[0] = null;
  5979. this._blendFunctionParameters[1] = null;
  5980. this._blendFunctionParameters[2] = null;
  5981. this._blendFunctionParameters[3] = null;
  5982. this._isAlphaBlendDirty = true;
  5983. this._isBlendFunctionParametersDirty = false;
  5984. };
  5985. _AlphaState.prototype.apply = function (gl) {
  5986. if (!this.isDirty) {
  5987. return;
  5988. }
  5989. // Alpha blend
  5990. if (this._isAlphaBlendDirty) {
  5991. if (this._alphaBlend) {
  5992. gl.enable(gl.BLEND);
  5993. }
  5994. else {
  5995. gl.disable(gl.BLEND);
  5996. }
  5997. this._isAlphaBlendDirty = false;
  5998. }
  5999. // Alpha function
  6000. if (this._isBlendFunctionParametersDirty) {
  6001. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6002. this._isBlendFunctionParametersDirty = false;
  6003. }
  6004. };
  6005. return _AlphaState;
  6006. }());
  6007. Internals._AlphaState = _AlphaState;
  6008. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6009. })(BABYLON || (BABYLON = {}));
  6010. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6011. var BABYLON;
  6012. (function (BABYLON) {
  6013. var Internals;
  6014. (function (Internals) {
  6015. var _DepthCullingState = (function () {
  6016. /**
  6017. * Initializes the state.
  6018. */
  6019. function _DepthCullingState() {
  6020. this._isDepthTestDirty = false;
  6021. this._isDepthMaskDirty = false;
  6022. this._isDepthFuncDirty = false;
  6023. this._isCullFaceDirty = false;
  6024. this._isCullDirty = false;
  6025. this._isZOffsetDirty = false;
  6026. this.reset();
  6027. }
  6028. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6029. get: function () {
  6030. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6031. },
  6032. enumerable: true,
  6033. configurable: true
  6034. });
  6035. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6036. get: function () {
  6037. return this._zOffset;
  6038. },
  6039. set: function (value) {
  6040. if (this._zOffset === value) {
  6041. return;
  6042. }
  6043. this._zOffset = value;
  6044. this._isZOffsetDirty = true;
  6045. },
  6046. enumerable: true,
  6047. configurable: true
  6048. });
  6049. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6050. get: function () {
  6051. return this._cullFace;
  6052. },
  6053. set: function (value) {
  6054. if (this._cullFace === value) {
  6055. return;
  6056. }
  6057. this._cullFace = value;
  6058. this._isCullFaceDirty = true;
  6059. },
  6060. enumerable: true,
  6061. configurable: true
  6062. });
  6063. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6064. get: function () {
  6065. return this._cull;
  6066. },
  6067. set: function (value) {
  6068. if (this._cull === value) {
  6069. return;
  6070. }
  6071. this._cull = value;
  6072. this._isCullDirty = true;
  6073. },
  6074. enumerable: true,
  6075. configurable: true
  6076. });
  6077. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6078. get: function () {
  6079. return this._depthFunc;
  6080. },
  6081. set: function (value) {
  6082. if (this._depthFunc === value) {
  6083. return;
  6084. }
  6085. this._depthFunc = value;
  6086. this._isDepthFuncDirty = true;
  6087. },
  6088. enumerable: true,
  6089. configurable: true
  6090. });
  6091. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6092. get: function () {
  6093. return this._depthMask;
  6094. },
  6095. set: function (value) {
  6096. if (this._depthMask === value) {
  6097. return;
  6098. }
  6099. this._depthMask = value;
  6100. this._isDepthMaskDirty = true;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6106. get: function () {
  6107. return this._depthTest;
  6108. },
  6109. set: function (value) {
  6110. if (this._depthTest === value) {
  6111. return;
  6112. }
  6113. this._depthTest = value;
  6114. this._isDepthTestDirty = true;
  6115. },
  6116. enumerable: true,
  6117. configurable: true
  6118. });
  6119. _DepthCullingState.prototype.reset = function () {
  6120. this._depthMask = true;
  6121. this._depthTest = true;
  6122. this._depthFunc = null;
  6123. this._cullFace = null;
  6124. this._cull = null;
  6125. this._zOffset = 0;
  6126. this._isDepthTestDirty = true;
  6127. this._isDepthMaskDirty = true;
  6128. this._isDepthFuncDirty = false;
  6129. this._isCullFaceDirty = false;
  6130. this._isCullDirty = false;
  6131. this._isZOffsetDirty = false;
  6132. };
  6133. _DepthCullingState.prototype.apply = function (gl) {
  6134. if (!this.isDirty) {
  6135. return;
  6136. }
  6137. // Cull
  6138. if (this._isCullDirty) {
  6139. if (this.cull) {
  6140. gl.enable(gl.CULL_FACE);
  6141. }
  6142. else {
  6143. gl.disable(gl.CULL_FACE);
  6144. }
  6145. this._isCullDirty = false;
  6146. }
  6147. // Cull face
  6148. if (this._isCullFaceDirty) {
  6149. gl.cullFace(this.cullFace);
  6150. this._isCullFaceDirty = false;
  6151. }
  6152. // Depth mask
  6153. if (this._isDepthMaskDirty) {
  6154. gl.depthMask(this.depthMask);
  6155. this._isDepthMaskDirty = false;
  6156. }
  6157. // Depth test
  6158. if (this._isDepthTestDirty) {
  6159. if (this.depthTest) {
  6160. gl.enable(gl.DEPTH_TEST);
  6161. }
  6162. else {
  6163. gl.disable(gl.DEPTH_TEST);
  6164. }
  6165. this._isDepthTestDirty = false;
  6166. }
  6167. // Depth func
  6168. if (this._isDepthFuncDirty) {
  6169. gl.depthFunc(this.depthFunc);
  6170. this._isDepthFuncDirty = false;
  6171. }
  6172. // zOffset
  6173. if (this._isZOffsetDirty) {
  6174. if (this.zOffset) {
  6175. gl.enable(gl.POLYGON_OFFSET_FILL);
  6176. gl.polygonOffset(this.zOffset, 0);
  6177. }
  6178. else {
  6179. gl.disable(gl.POLYGON_OFFSET_FILL);
  6180. }
  6181. this._isZOffsetDirty = false;
  6182. }
  6183. };
  6184. return _DepthCullingState;
  6185. }());
  6186. Internals._DepthCullingState = _DepthCullingState;
  6187. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6188. })(BABYLON || (BABYLON = {}));
  6189. //# sourceMappingURL=babylon.depthCullingState.js.map
  6190. var BABYLON;
  6191. (function (BABYLON) {
  6192. var Internals;
  6193. (function (Internals) {
  6194. var _StencilState = (function () {
  6195. function _StencilState() {
  6196. this._isStencilTestDirty = false;
  6197. this._isStencilMaskDirty = false;
  6198. this._isStencilFuncDirty = false;
  6199. this._isStencilOpDirty = false;
  6200. this.reset();
  6201. }
  6202. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6203. get: function () {
  6204. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6210. get: function () {
  6211. return this._stencilFunc;
  6212. },
  6213. set: function (value) {
  6214. if (this._stencilFunc === value) {
  6215. return;
  6216. }
  6217. this._stencilFunc = value;
  6218. this._isStencilFuncDirty = true;
  6219. },
  6220. enumerable: true,
  6221. configurable: true
  6222. });
  6223. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6224. get: function () {
  6225. return this._stencilFuncRef;
  6226. },
  6227. set: function (value) {
  6228. if (this._stencilFuncRef === value) {
  6229. return;
  6230. }
  6231. this._stencilFuncRef = value;
  6232. this._isStencilFuncDirty = true;
  6233. },
  6234. enumerable: true,
  6235. configurable: true
  6236. });
  6237. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6238. get: function () {
  6239. return this._stencilFuncMask;
  6240. },
  6241. set: function (value) {
  6242. if (this._stencilFuncMask === value) {
  6243. return;
  6244. }
  6245. this._stencilFuncMask = value;
  6246. this._isStencilFuncDirty = true;
  6247. },
  6248. enumerable: true,
  6249. configurable: true
  6250. });
  6251. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6252. get: function () {
  6253. return this._stencilOpStencilFail;
  6254. },
  6255. set: function (value) {
  6256. if (this._stencilOpStencilFail === value) {
  6257. return;
  6258. }
  6259. this._stencilOpStencilFail = value;
  6260. this._isStencilOpDirty = true;
  6261. },
  6262. enumerable: true,
  6263. configurable: true
  6264. });
  6265. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6266. get: function () {
  6267. return this._stencilOpDepthFail;
  6268. },
  6269. set: function (value) {
  6270. if (this._stencilOpDepthFail === value) {
  6271. return;
  6272. }
  6273. this._stencilOpDepthFail = value;
  6274. this._isStencilOpDirty = true;
  6275. },
  6276. enumerable: true,
  6277. configurable: true
  6278. });
  6279. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6280. get: function () {
  6281. return this._stencilOpStencilDepthPass;
  6282. },
  6283. set: function (value) {
  6284. if (this._stencilOpStencilDepthPass === value) {
  6285. return;
  6286. }
  6287. this._stencilOpStencilDepthPass = value;
  6288. this._isStencilOpDirty = true;
  6289. },
  6290. enumerable: true,
  6291. configurable: true
  6292. });
  6293. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6294. get: function () {
  6295. return this._stencilMask;
  6296. },
  6297. set: function (value) {
  6298. if (this._stencilMask === value) {
  6299. return;
  6300. }
  6301. this._stencilMask = value;
  6302. this._isStencilMaskDirty = true;
  6303. },
  6304. enumerable: true,
  6305. configurable: true
  6306. });
  6307. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6308. get: function () {
  6309. return this._stencilTest;
  6310. },
  6311. set: function (value) {
  6312. if (this._stencilTest === value) {
  6313. return;
  6314. }
  6315. this._stencilTest = value;
  6316. this._isStencilTestDirty = true;
  6317. },
  6318. enumerable: true,
  6319. configurable: true
  6320. });
  6321. _StencilState.prototype.reset = function () {
  6322. this._stencilTest = false;
  6323. this._stencilMask = 0xFF;
  6324. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6325. this._stencilFuncRef = 1;
  6326. this._stencilFuncMask = 0xFF;
  6327. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6328. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6329. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6330. this._isStencilTestDirty = true;
  6331. this._isStencilMaskDirty = true;
  6332. this._isStencilFuncDirty = true;
  6333. this._isStencilOpDirty = true;
  6334. };
  6335. _StencilState.prototype.apply = function (gl) {
  6336. if (!this.isDirty) {
  6337. return;
  6338. }
  6339. // Stencil test
  6340. if (this._isStencilTestDirty) {
  6341. if (this.stencilTest) {
  6342. gl.enable(gl.STENCIL_TEST);
  6343. }
  6344. else {
  6345. gl.disable(gl.STENCIL_TEST);
  6346. }
  6347. this._isStencilTestDirty = false;
  6348. }
  6349. // Stencil mask
  6350. if (this._isStencilMaskDirty) {
  6351. gl.stencilMask(this.stencilMask);
  6352. this._isStencilMaskDirty = false;
  6353. }
  6354. // Stencil func
  6355. if (this._isStencilFuncDirty) {
  6356. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6357. this._isStencilFuncDirty = false;
  6358. }
  6359. // Stencil op
  6360. if (this._isStencilOpDirty) {
  6361. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6362. this._isStencilOpDirty = false;
  6363. }
  6364. };
  6365. return _StencilState;
  6366. }());
  6367. Internals._StencilState = _StencilState;
  6368. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6369. })(BABYLON || (BABYLON = {}));
  6370. //# sourceMappingURL=babylon.stencilState.js.map
  6371. var BABYLON;
  6372. (function (BABYLON) {
  6373. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6374. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6375. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6376. gl.compileShader(shader);
  6377. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6378. throw new Error(gl.getShaderInfoLog(shader));
  6379. }
  6380. return shader;
  6381. };
  6382. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6383. var magFilter = gl.NEAREST;
  6384. var minFilter = gl.NEAREST;
  6385. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6386. magFilter = gl.LINEAR;
  6387. if (generateMipMaps) {
  6388. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6389. }
  6390. else {
  6391. minFilter = gl.LINEAR;
  6392. }
  6393. }
  6394. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6395. magFilter = gl.LINEAR;
  6396. if (generateMipMaps) {
  6397. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6398. }
  6399. else {
  6400. minFilter = gl.LINEAR;
  6401. }
  6402. }
  6403. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6404. magFilter = gl.NEAREST;
  6405. if (generateMipMaps) {
  6406. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6407. }
  6408. else {
  6409. minFilter = gl.NEAREST;
  6410. }
  6411. }
  6412. return {
  6413. min: minFilter,
  6414. mag: magFilter
  6415. };
  6416. };
  6417. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6419. var engine = scene.getEngine();
  6420. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6421. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6422. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6423. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6424. texture._baseWidth = width;
  6425. texture._baseHeight = height;
  6426. texture._width = potWidth;
  6427. texture._height = potHeight;
  6428. texture.isReady = true;
  6429. processFunction(potWidth, potHeight);
  6430. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6433. if (!noMipmap && !isCompressed) {
  6434. gl.generateMipmap(gl.TEXTURE_2D);
  6435. }
  6436. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6437. engine.resetTextureCache();
  6438. scene._removePendingData(texture);
  6439. texture.onLoadedCallbacks.forEach(function (callback) {
  6440. callback();
  6441. });
  6442. texture.onLoadedCallbacks = [];
  6443. };
  6444. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6445. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6446. var img;
  6447. var onload = function () {
  6448. loadedImages[index] = img;
  6449. loadedImages._internalCount++;
  6450. scene._removePendingData(img);
  6451. if (loadedImages._internalCount === 6) {
  6452. onfinish(loadedImages);
  6453. }
  6454. };
  6455. var onerror = function () {
  6456. scene._removePendingData(img);
  6457. if (onErrorCallBack) {
  6458. onErrorCallBack();
  6459. }
  6460. };
  6461. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6462. scene._addPendingData(img);
  6463. };
  6464. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6465. if (onError === void 0) { onError = null; }
  6466. var loadedImages = [];
  6467. loadedImages._internalCount = 0;
  6468. for (var index = 0; index < 6; index++) {
  6469. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6470. }
  6471. };
  6472. var InstancingAttributeInfo = (function () {
  6473. function InstancingAttributeInfo() {
  6474. }
  6475. return InstancingAttributeInfo;
  6476. }());
  6477. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6478. var EngineCapabilities = (function () {
  6479. function EngineCapabilities() {
  6480. }
  6481. return EngineCapabilities;
  6482. }());
  6483. BABYLON.EngineCapabilities = EngineCapabilities;
  6484. /**
  6485. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6486. */
  6487. var Engine = (function () {
  6488. /**
  6489. * @constructor
  6490. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6491. * @param {boolean} [antialias] - enable antialias
  6492. * @param options - further options to be sent to the getContext function
  6493. */
  6494. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6495. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6496. var _this = this;
  6497. // Public members
  6498. this.isFullscreen = false;
  6499. this.isPointerLock = false;
  6500. this.cullBackFaces = true;
  6501. this.renderEvenInBackground = true;
  6502. // To enable/disable IDB support and avoid XHR on .manifest
  6503. this.enableOfflineSupport = true;
  6504. this.scenes = new Array();
  6505. this._windowIsBackground = false;
  6506. this._webGLVersion = 1.0;
  6507. this._badOS = false;
  6508. this._drawCalls = new BABYLON.PerfCounter();
  6509. this._renderingQueueLaunched = false;
  6510. this._activeRenderLoops = [];
  6511. // FPS
  6512. this.fpsRange = 60;
  6513. this.previousFramesDuration = [];
  6514. this.fps = 60;
  6515. this.deltaTime = 0;
  6516. // States
  6517. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6518. this._stencilState = new BABYLON.Internals._StencilState();
  6519. this._alphaState = new BABYLON.Internals._AlphaState();
  6520. this._alphaMode = Engine.ALPHA_DISABLE;
  6521. // Cache
  6522. this._loadedTexturesCache = new Array();
  6523. this._maxTextureChannels = 16;
  6524. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6525. this._compiledEffects = {};
  6526. this._vertexAttribArraysEnabled = [];
  6527. this._uintIndicesCurrentlySet = false;
  6528. this._currentBoundBuffer = new Array();
  6529. this._currentBufferPointers = [];
  6530. this._currentInstanceLocations = new Array();
  6531. this._currentInstanceBuffers = new Array();
  6532. this._vaoRecordInProgress = false;
  6533. this._mustWipeVertexAttributes = false;
  6534. // Hardware supported Compressed Textures
  6535. this._texturesSupported = new Array();
  6536. this._onVRFullScreenTriggered = function () {
  6537. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6538. //get the old size before we change
  6539. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6540. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6541. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6542. //But actually, no browser follow the specs...
  6543. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6544. //get the width and height, change the render size
  6545. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6546. var width, height;
  6547. _this.setHardwareScalingLevel(1);
  6548. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6549. }
  6550. else {
  6551. //When the specs are implemented, need to uncomment this.
  6552. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6553. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6554. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6555. _this._vrDisplayEnabled = undefined;
  6556. }
  6557. };
  6558. this._renderingCanvas = canvas;
  6559. this._externalData = new BABYLON.StringDictionary();
  6560. options = options || {};
  6561. if (antialias != null) {
  6562. options.antialias = antialias;
  6563. }
  6564. if (options.preserveDrawingBuffer === undefined) {
  6565. options.preserveDrawingBuffer = false;
  6566. }
  6567. // GL
  6568. if (!options.disableWebGL2Support) {
  6569. try {
  6570. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6571. if (this._gl) {
  6572. this._webGLVersion = 2.0;
  6573. }
  6574. }
  6575. catch (e) {
  6576. }
  6577. }
  6578. if (!this._gl) {
  6579. if (!canvas) {
  6580. throw new Error("The provided canvas is null or undefined.");
  6581. }
  6582. try {
  6583. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6584. }
  6585. catch (e) {
  6586. throw new Error("WebGL not supported");
  6587. }
  6588. }
  6589. if (!this._gl) {
  6590. throw new Error("WebGL not supported");
  6591. }
  6592. this._onBlur = function () {
  6593. _this._windowIsBackground = true;
  6594. };
  6595. this._onFocus = function () {
  6596. _this._windowIsBackground = false;
  6597. };
  6598. window.addEventListener("blur", this._onBlur);
  6599. window.addEventListener("focus", this._onFocus);
  6600. // Viewport
  6601. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6602. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6603. this.resize();
  6604. // Caps
  6605. this._isStencilEnable = options.stencil;
  6606. this._caps = new EngineCapabilities();
  6607. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6608. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6609. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6610. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6611. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6612. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6613. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6614. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6615. // Infos
  6616. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6617. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6618. if (rendererInfo != null) {
  6619. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6620. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6621. }
  6622. if (!this._glVendor) {
  6623. this._glVendor = "Unknown vendor";
  6624. }
  6625. if (!this._glRenderer) {
  6626. this._glRenderer = "Unknown renderer";
  6627. }
  6628. // Extensions
  6629. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  6630. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  6631. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  6632. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  6633. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  6634. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  6635. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  6636. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  6637. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  6638. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6639. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  6640. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  6641. this._caps.highPrecisionShaderSupported = true;
  6642. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  6643. // Checks if some of the format renders first to allow the use of webgl inspector.
  6644. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  6645. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  6646. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  6647. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  6648. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  6649. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  6650. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  6651. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  6652. // Vertex array object
  6653. if (this._webGLVersion > 1) {
  6654. this._caps.vertexArrayObject = true;
  6655. }
  6656. else {
  6657. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  6658. if (vertexArrayObjectExtension != null) {
  6659. this._caps.vertexArrayObject = true;
  6660. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  6661. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  6662. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  6663. }
  6664. else {
  6665. this._caps.vertexArrayObject = false;
  6666. }
  6667. }
  6668. // Instances count
  6669. if (this._webGLVersion > 1) {
  6670. this._caps.instancedArrays = true;
  6671. }
  6672. else {
  6673. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  6674. if (instanceExtension != null) {
  6675. this._caps.instancedArrays = true;
  6676. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  6677. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  6678. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  6679. }
  6680. else {
  6681. this._caps.instancedArrays = false;
  6682. }
  6683. }
  6684. // Intelligently add supported compressed formats in order to check for.
  6685. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6686. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  6687. // Likely no hardware which supports both PVR & DXT, so order matters little.
  6688. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  6689. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  6690. if (this._caps.astc)
  6691. this.texturesSupported.push('-astc.ktx');
  6692. if (this._caps.s3tc)
  6693. this.texturesSupported.push('-dxt.ktx');
  6694. if (this._caps.pvrtc)
  6695. this.texturesSupported.push('-pvrtc.ktx');
  6696. if (this._caps.etc2)
  6697. this.texturesSupported.push('-etc2.ktx');
  6698. if (this._caps.atc)
  6699. this.texturesSupported.push('-atc.ktx');
  6700. if (this._caps.etc1)
  6701. this.texturesSupported.push('-etc1.ktx');
  6702. if (this._gl.getShaderPrecisionFormat) {
  6703. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6704. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6705. }
  6706. // Depth buffer
  6707. this.setDepthBuffer(true);
  6708. this.setDepthFunctionToLessOrEqual();
  6709. this.setDepthWrite(true);
  6710. // Fullscreen
  6711. this._onFullscreenChange = function () {
  6712. if (document.fullscreen !== undefined) {
  6713. _this.isFullscreen = document.fullscreen;
  6714. }
  6715. else if (document.mozFullScreen !== undefined) {
  6716. _this.isFullscreen = document.mozFullScreen;
  6717. }
  6718. else if (document.webkitIsFullScreen !== undefined) {
  6719. _this.isFullscreen = document.webkitIsFullScreen;
  6720. }
  6721. else if (document.msIsFullScreen !== undefined) {
  6722. _this.isFullscreen = document.msIsFullScreen;
  6723. }
  6724. // Pointer lock
  6725. if (_this.isFullscreen && _this._pointerLockRequested) {
  6726. canvas.requestPointerLock = canvas.requestPointerLock ||
  6727. canvas.msRequestPointerLock ||
  6728. canvas.mozRequestPointerLock ||
  6729. canvas.webkitRequestPointerLock;
  6730. if (canvas.requestPointerLock) {
  6731. canvas.requestPointerLock();
  6732. }
  6733. }
  6734. };
  6735. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6736. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6737. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6738. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6739. // Pointer lock
  6740. this._onPointerLockChange = function () {
  6741. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6742. document.webkitPointerLockElement === canvas ||
  6743. document.msPointerLockElement === canvas ||
  6744. document.pointerLockElement === canvas);
  6745. };
  6746. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6747. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6748. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6749. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6750. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6751. Engine.audioEngine = new BABYLON.AudioEngine();
  6752. }
  6753. //default loading screen
  6754. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6755. //Load WebVR Devices
  6756. if (options.autoEnableWebVR) {
  6757. this.initWebVR();
  6758. }
  6759. //Detect if we are running on a faulty buggy OS.
  6760. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6761. //ua sniffing is the tool of the devil.
  6762. this._badOS = regexp.test(navigator.userAgent);
  6763. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6764. }
  6765. Object.defineProperty(Engine, "NEVER", {
  6766. get: function () {
  6767. return Engine._NEVER;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(Engine, "ALWAYS", {
  6773. get: function () {
  6774. return Engine._ALWAYS;
  6775. },
  6776. enumerable: true,
  6777. configurable: true
  6778. });
  6779. Object.defineProperty(Engine, "LESS", {
  6780. get: function () {
  6781. return Engine._LESS;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Object.defineProperty(Engine, "EQUAL", {
  6787. get: function () {
  6788. return Engine._EQUAL;
  6789. },
  6790. enumerable: true,
  6791. configurable: true
  6792. });
  6793. Object.defineProperty(Engine, "LEQUAL", {
  6794. get: function () {
  6795. return Engine._LEQUAL;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(Engine, "GREATER", {
  6801. get: function () {
  6802. return Engine._GREATER;
  6803. },
  6804. enumerable: true,
  6805. configurable: true
  6806. });
  6807. Object.defineProperty(Engine, "GEQUAL", {
  6808. get: function () {
  6809. return Engine._GEQUAL;
  6810. },
  6811. enumerable: true,
  6812. configurable: true
  6813. });
  6814. Object.defineProperty(Engine, "NOTEQUAL", {
  6815. get: function () {
  6816. return Engine._NOTEQUAL;
  6817. },
  6818. enumerable: true,
  6819. configurable: true
  6820. });
  6821. Object.defineProperty(Engine, "KEEP", {
  6822. get: function () {
  6823. return Engine._KEEP;
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Object.defineProperty(Engine, "REPLACE", {
  6829. get: function () {
  6830. return Engine._REPLACE;
  6831. },
  6832. enumerable: true,
  6833. configurable: true
  6834. });
  6835. Object.defineProperty(Engine, "INCR", {
  6836. get: function () {
  6837. return Engine._INCR;
  6838. },
  6839. enumerable: true,
  6840. configurable: true
  6841. });
  6842. Object.defineProperty(Engine, "DECR", {
  6843. get: function () {
  6844. return Engine._DECR;
  6845. },
  6846. enumerable: true,
  6847. configurable: true
  6848. });
  6849. Object.defineProperty(Engine, "INVERT", {
  6850. get: function () {
  6851. return Engine._INVERT;
  6852. },
  6853. enumerable: true,
  6854. configurable: true
  6855. });
  6856. Object.defineProperty(Engine, "INCR_WRAP", {
  6857. get: function () {
  6858. return Engine._INCR_WRAP;
  6859. },
  6860. enumerable: true,
  6861. configurable: true
  6862. });
  6863. Object.defineProperty(Engine, "DECR_WRAP", {
  6864. get: function () {
  6865. return Engine._DECR_WRAP;
  6866. },
  6867. enumerable: true,
  6868. configurable: true
  6869. });
  6870. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6871. get: function () {
  6872. return Engine._ALPHA_DISABLE;
  6873. },
  6874. enumerable: true,
  6875. configurable: true
  6876. });
  6877. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6878. get: function () {
  6879. return Engine._ALPHA_ONEONE;
  6880. },
  6881. enumerable: true,
  6882. configurable: true
  6883. });
  6884. Object.defineProperty(Engine, "ALPHA_ADD", {
  6885. get: function () {
  6886. return Engine._ALPHA_ADD;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6892. get: function () {
  6893. return Engine._ALPHA_COMBINE;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6899. get: function () {
  6900. return Engine._ALPHA_SUBTRACT;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6906. get: function () {
  6907. return Engine._ALPHA_MULTIPLY;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6913. get: function () {
  6914. return Engine._ALPHA_MAXIMIZED;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6920. get: function () {
  6921. return Engine._ALPHA_PREMULTIPLIED;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6927. get: function () {
  6928. return Engine._DELAYLOADSTATE_NONE;
  6929. },
  6930. enumerable: true,
  6931. configurable: true
  6932. });
  6933. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6934. get: function () {
  6935. return Engine._DELAYLOADSTATE_LOADED;
  6936. },
  6937. enumerable: true,
  6938. configurable: true
  6939. });
  6940. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6941. get: function () {
  6942. return Engine._DELAYLOADSTATE_LOADING;
  6943. },
  6944. enumerable: true,
  6945. configurable: true
  6946. });
  6947. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6948. get: function () {
  6949. return Engine._DELAYLOADSTATE_NOTLOADED;
  6950. },
  6951. enumerable: true,
  6952. configurable: true
  6953. });
  6954. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6955. get: function () {
  6956. return Engine._TEXTUREFORMAT_ALPHA;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6962. get: function () {
  6963. return Engine._TEXTUREFORMAT_LUMINANCE;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6969. get: function () {
  6970. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6976. get: function () {
  6977. return Engine._TEXTUREFORMAT_RGB;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6983. get: function () {
  6984. return Engine._TEXTUREFORMAT_RGBA;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6990. get: function () {
  6991. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6992. },
  6993. enumerable: true,
  6994. configurable: true
  6995. });
  6996. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6997. get: function () {
  6998. return Engine._TEXTURETYPE_FLOAT;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7004. get: function () {
  7005. return Engine._TEXTURETYPE_HALF_FLOAT;
  7006. },
  7007. enumerable: true,
  7008. configurable: true
  7009. });
  7010. Object.defineProperty(Engine, "Version", {
  7011. get: function () {
  7012. return "2.6-alpha";
  7013. },
  7014. enumerable: true,
  7015. configurable: true
  7016. });
  7017. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7018. get: function () {
  7019. return this._texturesSupported;
  7020. },
  7021. enumerable: true,
  7022. configurable: true
  7023. });
  7024. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7025. get: function () {
  7026. return this._textureFormatInUse;
  7027. },
  7028. enumerable: true,
  7029. configurable: true
  7030. });
  7031. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7032. get: function () {
  7033. return this._webGLVersion;
  7034. },
  7035. enumerable: true,
  7036. configurable: true
  7037. });
  7038. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7039. /**
  7040. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7041. */
  7042. get: function () {
  7043. return this._isStencilEnable;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Engine.prototype._prepareWorkingCanvas = function () {
  7049. if (this._workingCanvas) {
  7050. return;
  7051. }
  7052. this._workingCanvas = document.createElement("canvas");
  7053. this._workingContext = this._workingCanvas.getContext("2d");
  7054. };
  7055. Engine.prototype.resetTextureCache = function () {
  7056. for (var index = 0; index < this._maxTextureChannels; index++) {
  7057. this._activeTexturesCache[index] = null;
  7058. }
  7059. };
  7060. Engine.prototype.getGlInfo = function () {
  7061. return {
  7062. vendor: this._glVendor,
  7063. renderer: this._glRenderer,
  7064. version: this._glVersion
  7065. };
  7066. };
  7067. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7068. if (useScreen === void 0) { useScreen = false; }
  7069. var viewport = camera.viewport;
  7070. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7071. };
  7072. Engine.prototype.getRenderWidth = function (useScreen) {
  7073. if (useScreen === void 0) { useScreen = false; }
  7074. if (!useScreen && this._currentRenderTarget) {
  7075. return this._currentRenderTarget._width;
  7076. }
  7077. return this._renderingCanvas.width;
  7078. };
  7079. Engine.prototype.getRenderHeight = function (useScreen) {
  7080. if (useScreen === void 0) { useScreen = false; }
  7081. if (!useScreen && this._currentRenderTarget) {
  7082. return this._currentRenderTarget._height;
  7083. }
  7084. return this._renderingCanvas.height;
  7085. };
  7086. Engine.prototype.getRenderingCanvas = function () {
  7087. return this._renderingCanvas;
  7088. };
  7089. Engine.prototype.getRenderingCanvasClientRect = function () {
  7090. return this._renderingCanvas.getBoundingClientRect();
  7091. };
  7092. Engine.prototype.setHardwareScalingLevel = function (level) {
  7093. this._hardwareScalingLevel = level;
  7094. this.resize();
  7095. };
  7096. Engine.prototype.getHardwareScalingLevel = function () {
  7097. return this._hardwareScalingLevel;
  7098. };
  7099. Engine.prototype.getLoadedTexturesCache = function () {
  7100. return this._loadedTexturesCache;
  7101. };
  7102. Engine.prototype.getCaps = function () {
  7103. return this._caps;
  7104. };
  7105. Object.defineProperty(Engine.prototype, "drawCalls", {
  7106. get: function () {
  7107. return this._drawCalls.current;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7113. get: function () {
  7114. return this._drawCalls;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Engine.prototype.getDepthFunction = function () {
  7120. return this._depthCullingState.depthFunc;
  7121. };
  7122. Engine.prototype.setDepthFunction = function (depthFunc) {
  7123. this._depthCullingState.depthFunc = depthFunc;
  7124. };
  7125. Engine.prototype.setDepthFunctionToGreater = function () {
  7126. this._depthCullingState.depthFunc = this._gl.GREATER;
  7127. };
  7128. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7129. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7130. };
  7131. Engine.prototype.setDepthFunctionToLess = function () {
  7132. this._depthCullingState.depthFunc = this._gl.LESS;
  7133. };
  7134. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7135. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7136. };
  7137. Engine.prototype.getStencilBuffer = function () {
  7138. return this._stencilState.stencilTest;
  7139. };
  7140. Engine.prototype.setStencilBuffer = function (enable) {
  7141. this._stencilState.stencilTest = enable;
  7142. };
  7143. Engine.prototype.getStencilMask = function () {
  7144. return this._stencilState.stencilMask;
  7145. };
  7146. Engine.prototype.setStencilMask = function (mask) {
  7147. this._stencilState.stencilMask = mask;
  7148. };
  7149. Engine.prototype.getStencilFunction = function () {
  7150. return this._stencilState.stencilFunc;
  7151. };
  7152. Engine.prototype.getStencilFunctionReference = function () {
  7153. return this._stencilState.stencilFuncRef;
  7154. };
  7155. Engine.prototype.getStencilFunctionMask = function () {
  7156. return this._stencilState.stencilFuncMask;
  7157. };
  7158. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7159. this._stencilState.stencilFunc = stencilFunc;
  7160. };
  7161. Engine.prototype.setStencilFunctionReference = function (reference) {
  7162. this._stencilState.stencilFuncRef = reference;
  7163. };
  7164. Engine.prototype.setStencilFunctionMask = function (mask) {
  7165. this._stencilState.stencilFuncMask = mask;
  7166. };
  7167. Engine.prototype.getStencilOperationFail = function () {
  7168. return this._stencilState.stencilOpStencilFail;
  7169. };
  7170. Engine.prototype.getStencilOperationDepthFail = function () {
  7171. return this._stencilState.stencilOpDepthFail;
  7172. };
  7173. Engine.prototype.getStencilOperationPass = function () {
  7174. return this._stencilState.stencilOpStencilDepthPass;
  7175. };
  7176. Engine.prototype.setStencilOperationFail = function (operation) {
  7177. this._stencilState.stencilOpStencilFail = operation;
  7178. };
  7179. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7180. this._stencilState.stencilOpDepthFail = operation;
  7181. };
  7182. Engine.prototype.setStencilOperationPass = function (operation) {
  7183. this._stencilState.stencilOpStencilDepthPass = operation;
  7184. };
  7185. /**
  7186. * stop executing a render loop function and remove it from the execution array
  7187. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7188. */
  7189. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7190. if (!renderFunction) {
  7191. this._activeRenderLoops = [];
  7192. return;
  7193. }
  7194. var index = this._activeRenderLoops.indexOf(renderFunction);
  7195. if (index >= 0) {
  7196. this._activeRenderLoops.splice(index, 1);
  7197. }
  7198. };
  7199. Engine.prototype._renderLoop = function () {
  7200. var shouldRender = true;
  7201. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7202. shouldRender = false;
  7203. }
  7204. if (shouldRender) {
  7205. // Start new frame
  7206. this.beginFrame();
  7207. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7208. var renderFunction = this._activeRenderLoops[index];
  7209. renderFunction();
  7210. }
  7211. // Present
  7212. this.endFrame();
  7213. }
  7214. if (this._activeRenderLoops.length > 0) {
  7215. // Register new frame
  7216. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7217. }
  7218. else {
  7219. this._renderingQueueLaunched = false;
  7220. }
  7221. };
  7222. /**
  7223. * Register and execute a render loop. The engine can have more than one render function.
  7224. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7225. * @example
  7226. * engine.runRenderLoop(function () {
  7227. * scene.render()
  7228. * })
  7229. */
  7230. Engine.prototype.runRenderLoop = function (renderFunction) {
  7231. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7232. return;
  7233. }
  7234. this._activeRenderLoops.push(renderFunction);
  7235. if (!this._renderingQueueLaunched) {
  7236. this._renderingQueueLaunched = true;
  7237. this._bindedRenderFunction = this._renderLoop.bind(this);
  7238. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7239. }
  7240. };
  7241. /**
  7242. * Toggle full screen mode.
  7243. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7244. * @param {any} options - an options object to be sent to the requestFullscreen function
  7245. */
  7246. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7247. if (this.isFullscreen) {
  7248. BABYLON.Tools.ExitFullscreen();
  7249. }
  7250. else {
  7251. this._pointerLockRequested = requestPointerLock;
  7252. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7253. }
  7254. };
  7255. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7256. if (stencil === void 0) { stencil = false; }
  7257. this.applyStates();
  7258. var mode = 0;
  7259. if (backBuffer && color) {
  7260. this._gl.clearColor(color.r, color.g, color.b, color.a);
  7261. mode |= this._gl.COLOR_BUFFER_BIT;
  7262. }
  7263. if (depth) {
  7264. this._gl.clearDepth(1.0);
  7265. mode |= this._gl.DEPTH_BUFFER_BIT;
  7266. }
  7267. if (stencil) {
  7268. this._gl.clearStencil(0);
  7269. mode |= this._gl.STENCIL_BUFFER_BIT;
  7270. }
  7271. this._gl.clear(mode);
  7272. };
  7273. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7274. var gl = this._gl;
  7275. // Save state
  7276. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7277. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7278. // Change state
  7279. gl.enable(gl.SCISSOR_TEST);
  7280. gl.scissor(x, y, width, height);
  7281. // Clear
  7282. this.clear(clearColor, true, true, true);
  7283. // Restore state
  7284. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7285. if (curScissor === true) {
  7286. gl.enable(gl.SCISSOR_TEST);
  7287. }
  7288. else {
  7289. gl.disable(gl.SCISSOR_TEST);
  7290. }
  7291. };
  7292. /**
  7293. * Set the WebGL's viewport
  7294. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7295. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7296. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7297. */
  7298. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7299. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7300. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7301. var x = viewport.x || 0;
  7302. var y = viewport.y || 0;
  7303. this._cachedViewport = viewport;
  7304. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7305. };
  7306. /**
  7307. * Directly set the WebGL Viewport
  7308. * The x, y, width & height are directly passed to the WebGL call
  7309. * @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.
  7310. */
  7311. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7312. var currentViewport = this._cachedViewport;
  7313. this._cachedViewport = null;
  7314. this._gl.viewport(x, y, width, height);
  7315. return currentViewport;
  7316. };
  7317. Engine.prototype.beginFrame = function () {
  7318. this._measureFps();
  7319. };
  7320. Engine.prototype.endFrame = function () {
  7321. //force a flush in case we are using a bad OS.
  7322. if (this._badOS) {
  7323. this.flushFramebuffer();
  7324. }
  7325. //submit frame to the vr device, if enabled
  7326. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7327. this._vrDisplayEnabled.submitFrame();
  7328. }
  7329. };
  7330. /**
  7331. * resize the view according to the canvas' size.
  7332. * @example
  7333. * window.addEventListener("resize", function () {
  7334. * engine.resize();
  7335. * });
  7336. */
  7337. Engine.prototype.resize = function () {
  7338. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7339. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7340. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7341. };
  7342. /**
  7343. * force a specific size of the canvas
  7344. * @param {number} width - the new canvas' width
  7345. * @param {number} height - the new canvas' height
  7346. */
  7347. Engine.prototype.setSize = function (width, height) {
  7348. this._renderingCanvas.width = width;
  7349. this._renderingCanvas.height = height;
  7350. for (var index = 0; index < this.scenes.length; index++) {
  7351. var scene = this.scenes[index];
  7352. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7353. var cam = scene.cameras[camIndex];
  7354. cam._currentRenderId = 0;
  7355. }
  7356. }
  7357. };
  7358. //WebVR functions
  7359. Engine.prototype.initWebVR = function () {
  7360. if (!this.vrDisplaysPromise) {
  7361. this._getVRDisplays();
  7362. }
  7363. };
  7364. Engine.prototype.enableVR = function (vrDevice) {
  7365. this._vrDisplayEnabled = vrDevice;
  7366. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7367. };
  7368. Engine.prototype.disableVR = function () {
  7369. if (this._vrDisplayEnabled) {
  7370. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7371. }
  7372. };
  7373. Engine.prototype._getVRDisplays = function () {
  7374. var _this = this;
  7375. var getWebVRDevices = function (devices) {
  7376. var size = devices.length;
  7377. var i = 0;
  7378. _this._vrDisplays = devices.filter(function (device) {
  7379. return devices[i] instanceof VRDisplay;
  7380. });
  7381. return _this._vrDisplays;
  7382. };
  7383. //using a key due to typescript
  7384. if (navigator.getVRDisplays) {
  7385. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7386. }
  7387. };
  7388. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7389. this._currentRenderTarget = texture;
  7390. this.bindUnboundFramebuffer(texture._framebuffer);
  7391. var gl = this._gl;
  7392. if (texture.isCube) {
  7393. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7394. }
  7395. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7396. this.wipeCaches();
  7397. };
  7398. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7399. if (this._currentFramebuffer !== framebuffer) {
  7400. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7401. this._currentFramebuffer = framebuffer;
  7402. }
  7403. };
  7404. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7405. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7406. this._currentRenderTarget = null;
  7407. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7408. var gl = this._gl;
  7409. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7410. gl.generateMipmap(gl.TEXTURE_2D);
  7411. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7412. }
  7413. this.bindUnboundFramebuffer(null);
  7414. };
  7415. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7416. if (texture.generateMipMaps) {
  7417. var gl = this._gl;
  7418. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7419. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7420. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7421. }
  7422. };
  7423. Engine.prototype.flushFramebuffer = function () {
  7424. this._gl.flush();
  7425. };
  7426. Engine.prototype.restoreDefaultFramebuffer = function () {
  7427. this._currentRenderTarget = null;
  7428. this.bindUnboundFramebuffer(null);
  7429. this.setViewport(this._cachedViewport);
  7430. this.wipeCaches();
  7431. };
  7432. // VBOs
  7433. Engine.prototype._resetVertexBufferBinding = function () {
  7434. this.bindArrayBuffer(null);
  7435. this._cachedVertexBuffers = null;
  7436. };
  7437. Engine.prototype.createVertexBuffer = function (vertices) {
  7438. var vbo = this._gl.createBuffer();
  7439. this.bindArrayBuffer(vbo);
  7440. if (vertices instanceof Float32Array) {
  7441. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7442. }
  7443. else {
  7444. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7445. }
  7446. this._resetVertexBufferBinding();
  7447. vbo.references = 1;
  7448. return vbo;
  7449. };
  7450. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7451. var vbo = this._gl.createBuffer();
  7452. this.bindArrayBuffer(vbo);
  7453. if (vertices instanceof Float32Array) {
  7454. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7455. }
  7456. else {
  7457. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7458. }
  7459. this._resetVertexBufferBinding();
  7460. vbo.references = 1;
  7461. return vbo;
  7462. };
  7463. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7464. this.bindArrayBuffer(vertexBuffer);
  7465. if (offset === undefined) {
  7466. offset = 0;
  7467. }
  7468. if (count === undefined) {
  7469. if (vertices instanceof Float32Array) {
  7470. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7471. }
  7472. else {
  7473. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7474. }
  7475. }
  7476. else {
  7477. if (vertices instanceof Float32Array) {
  7478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7479. }
  7480. else {
  7481. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7482. }
  7483. }
  7484. this._resetVertexBufferBinding();
  7485. };
  7486. Engine.prototype._resetIndexBufferBinding = function () {
  7487. this.bindIndexBuffer(null);
  7488. this._cachedIndexBuffer = null;
  7489. };
  7490. Engine.prototype.createIndexBuffer = function (indices) {
  7491. var vbo = this._gl.createBuffer();
  7492. this.bindIndexBuffer(vbo);
  7493. // Check for 32 bits indices
  7494. var arrayBuffer;
  7495. var need32Bits = false;
  7496. if (indices instanceof Uint16Array) {
  7497. arrayBuffer = indices;
  7498. }
  7499. else {
  7500. //check 32 bit support
  7501. if (this._caps.uintIndices) {
  7502. if (indices instanceof Uint32Array) {
  7503. arrayBuffer = indices;
  7504. need32Bits = true;
  7505. }
  7506. else {
  7507. //number[] or Int32Array, check if 32 bit is necessary
  7508. for (var index = 0; index < indices.length; index++) {
  7509. if (indices[index] > 65535) {
  7510. need32Bits = true;
  7511. break;
  7512. }
  7513. }
  7514. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7515. }
  7516. }
  7517. else {
  7518. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  7519. arrayBuffer = new Uint16Array(indices);
  7520. }
  7521. }
  7522. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7523. this._resetIndexBufferBinding();
  7524. vbo.references = 1;
  7525. vbo.is32Bits = need32Bits;
  7526. return vbo;
  7527. };
  7528. Engine.prototype.bindArrayBuffer = function (buffer) {
  7529. if (!this._vaoRecordInProgress) {
  7530. this._unBindVertexArrayObject();
  7531. }
  7532. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7533. };
  7534. Engine.prototype.bindIndexBuffer = function (buffer) {
  7535. if (!this._vaoRecordInProgress) {
  7536. this._unBindVertexArrayObject();
  7537. }
  7538. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7539. };
  7540. Engine.prototype.bindBuffer = function (buffer, target) {
  7541. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  7542. this._gl.bindBuffer(target, buffer);
  7543. this._currentBoundBuffer[target] = buffer;
  7544. }
  7545. };
  7546. Engine.prototype.updateArrayBuffer = function (data) {
  7547. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7548. };
  7549. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7550. var pointer = this._currentBufferPointers[indx];
  7551. var changed = false;
  7552. if (!pointer) {
  7553. changed = true;
  7554. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7555. }
  7556. else {
  7557. if (pointer.buffer !== buffer) {
  7558. pointer.buffer = buffer;
  7559. changed = true;
  7560. }
  7561. if (pointer.size !== size) {
  7562. pointer.size = size;
  7563. changed = true;
  7564. }
  7565. if (pointer.type !== type) {
  7566. pointer.type = type;
  7567. changed = true;
  7568. }
  7569. if (pointer.normalized !== normalized) {
  7570. pointer.normalized = normalized;
  7571. changed = true;
  7572. }
  7573. if (pointer.stride !== stride) {
  7574. pointer.stride = stride;
  7575. changed = true;
  7576. }
  7577. if (pointer.offset !== offset) {
  7578. pointer.offset = offset;
  7579. changed = true;
  7580. }
  7581. }
  7582. if (changed || this._vaoRecordInProgress) {
  7583. this.bindArrayBuffer(buffer);
  7584. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7585. }
  7586. };
  7587. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  7588. if (indexBuffer == null) {
  7589. return;
  7590. }
  7591. if (this._cachedIndexBuffer !== indexBuffer) {
  7592. this._cachedIndexBuffer = indexBuffer;
  7593. this.bindIndexBuffer(indexBuffer);
  7594. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7595. }
  7596. };
  7597. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  7598. var attributes = effect.getAttributesNames();
  7599. if (!this._vaoRecordInProgress) {
  7600. this._unBindVertexArrayObject();
  7601. }
  7602. this.unbindAllAttributes();
  7603. for (var index = 0; index < attributes.length; index++) {
  7604. var order = effect.getAttributeLocation(index);
  7605. if (order >= 0) {
  7606. var vertexBuffer = vertexBuffers[attributes[index]];
  7607. if (!vertexBuffer) {
  7608. continue;
  7609. }
  7610. this._gl.enableVertexAttribArray(order);
  7611. if (!this._vaoRecordInProgress) {
  7612. this._vertexAttribArraysEnabled[order] = true;
  7613. }
  7614. var buffer = vertexBuffer.getBuffer();
  7615. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7616. if (vertexBuffer.getIsInstanced()) {
  7617. this._gl.vertexAttribDivisor(order, 1);
  7618. if (!this._vaoRecordInProgress) {
  7619. this._currentInstanceLocations.push(order);
  7620. this._currentInstanceBuffers.push(buffer);
  7621. }
  7622. }
  7623. }
  7624. }
  7625. };
  7626. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  7627. var vao = this._gl.createVertexArray();
  7628. this._vaoRecordInProgress = true;
  7629. this._gl.bindVertexArray(vao);
  7630. this._mustWipeVertexAttributes = true;
  7631. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7632. this.bindIndexBuffer(indexBuffer);
  7633. this._vaoRecordInProgress = false;
  7634. this._gl.bindVertexArray(null);
  7635. return vao;
  7636. };
  7637. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  7638. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  7639. this._cachedVertexArrayObject = vertexArrayObject;
  7640. this._gl.bindVertexArray(vertexArrayObject);
  7641. this._cachedVertexBuffers = null;
  7642. this._cachedIndexBuffer = null;
  7643. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  7644. this._mustWipeVertexAttributes = true;
  7645. }
  7646. };
  7647. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7648. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7649. this._cachedVertexBuffers = vertexBuffer;
  7650. this._cachedEffectForVertexBuffers = effect;
  7651. var attributesCount = effect.getAttributesCount();
  7652. this._unBindVertexArrayObject();
  7653. this.unbindAllAttributes();
  7654. var offset = 0;
  7655. for (var index = 0; index < attributesCount; index++) {
  7656. if (index < vertexDeclaration.length) {
  7657. var order = effect.getAttributeLocation(index);
  7658. if (order >= 0) {
  7659. this._gl.enableVertexAttribArray(order);
  7660. this._vertexAttribArraysEnabled[order] = true;
  7661. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7662. }
  7663. offset += vertexDeclaration[index] * 4;
  7664. }
  7665. }
  7666. }
  7667. this._bindIndexBufferWithCache(indexBuffer);
  7668. };
  7669. Engine.prototype._unBindVertexArrayObject = function () {
  7670. if (!this._cachedVertexArrayObject) {
  7671. return;
  7672. }
  7673. this._cachedVertexArrayObject = null;
  7674. this._gl.bindVertexArray(null);
  7675. };
  7676. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7677. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7678. this._cachedVertexBuffers = vertexBuffers;
  7679. this._cachedEffectForVertexBuffers = effect;
  7680. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7681. }
  7682. this._bindIndexBufferWithCache(indexBuffer);
  7683. };
  7684. Engine.prototype.unbindInstanceAttributes = function () {
  7685. var boundBuffer;
  7686. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7687. var instancesBuffer = this._currentInstanceBuffers[i];
  7688. if (boundBuffer != instancesBuffer) {
  7689. boundBuffer = instancesBuffer;
  7690. this.bindArrayBuffer(instancesBuffer);
  7691. }
  7692. var offsetLocation = this._currentInstanceLocations[i];
  7693. this._gl.vertexAttribDivisor(offsetLocation, 0);
  7694. }
  7695. this._currentInstanceBuffers.length = 0;
  7696. this._currentInstanceLocations.length = 0;
  7697. };
  7698. Engine.prototype.releaseVertexArrayObject = function (vao) {
  7699. this._gl.deleteVertexArray(vao);
  7700. };
  7701. Engine.prototype._releaseBuffer = function (buffer) {
  7702. buffer.references--;
  7703. if (buffer.references === 0) {
  7704. this._gl.deleteBuffer(buffer);
  7705. return true;
  7706. }
  7707. return false;
  7708. };
  7709. Engine.prototype.createInstancesBuffer = function (capacity) {
  7710. var buffer = this._gl.createBuffer();
  7711. buffer.capacity = capacity;
  7712. this.bindArrayBuffer(buffer);
  7713. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7714. return buffer;
  7715. };
  7716. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7717. this._gl.deleteBuffer(buffer);
  7718. };
  7719. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7720. this.bindArrayBuffer(instancesBuffer);
  7721. if (data) {
  7722. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7723. }
  7724. if (offsetLocations[0].index !== undefined) {
  7725. var stride = 0;
  7726. for (var i = 0; i < offsetLocations.length; i++) {
  7727. var ai = offsetLocations[i];
  7728. stride += ai.attributeSize * 4;
  7729. }
  7730. for (var i = 0; i < offsetLocations.length; i++) {
  7731. var ai = offsetLocations[i];
  7732. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7733. this._gl.enableVertexAttribArray(ai.index);
  7734. this._vertexAttribArraysEnabled[ai.index] = true;
  7735. }
  7736. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7737. this._gl.vertexAttribDivisor(ai.index, 1);
  7738. this._currentInstanceLocations.push(ai.index);
  7739. this._currentInstanceBuffers.push(instancesBuffer);
  7740. }
  7741. }
  7742. else {
  7743. for (var index = 0; index < 4; index++) {
  7744. var offsetLocation = offsetLocations[index];
  7745. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7746. this._gl.enableVertexAttribArray(offsetLocation);
  7747. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7748. }
  7749. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7750. this._gl.vertexAttribDivisor(offsetLocation, 1);
  7751. this._currentInstanceLocations.push(offsetLocation);
  7752. this._currentInstanceBuffers.push(instancesBuffer);
  7753. }
  7754. }
  7755. };
  7756. Engine.prototype.applyStates = function () {
  7757. this._depthCullingState.apply(this._gl);
  7758. this._stencilState.apply(this._gl);
  7759. this._alphaState.apply(this._gl);
  7760. };
  7761. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7762. // Apply states
  7763. this.applyStates();
  7764. this._drawCalls.addCount(1, false);
  7765. // Render
  7766. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7767. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7768. if (instancesCount) {
  7769. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7770. return;
  7771. }
  7772. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7773. };
  7774. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7775. // Apply states
  7776. this.applyStates();
  7777. this._drawCalls.addCount(1, false);
  7778. if (instancesCount) {
  7779. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7780. return;
  7781. }
  7782. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7783. };
  7784. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7785. // Apply states
  7786. this.applyStates();
  7787. this._drawCalls.addCount(1, false);
  7788. if (instancesCount) {
  7789. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7790. return;
  7791. }
  7792. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7793. };
  7794. // Shaders
  7795. Engine.prototype._releaseEffect = function (effect) {
  7796. if (this._compiledEffects[effect._key]) {
  7797. delete this._compiledEffects[effect._key];
  7798. if (effect.getProgram()) {
  7799. this._gl.deleteProgram(effect.getProgram());
  7800. }
  7801. }
  7802. };
  7803. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7804. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7805. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7806. var name = vertex + "+" + fragment + "@" + defines;
  7807. if (this._compiledEffects[name]) {
  7808. return this._compiledEffects[name];
  7809. }
  7810. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7811. effect._key = name;
  7812. this._compiledEffects[name] = effect;
  7813. return effect;
  7814. };
  7815. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7816. if (uniformsNames === void 0) { uniformsNames = []; }
  7817. if (samplers === void 0) { samplers = []; }
  7818. if (defines === void 0) { defines = ""; }
  7819. return this.createEffect({
  7820. vertex: "particles",
  7821. fragmentElement: fragmentName
  7822. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7823. };
  7824. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7825. context = context || this._gl;
  7826. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  7827. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  7828. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  7829. var shaderProgram = context.createProgram();
  7830. context.attachShader(shaderProgram, vertexShader);
  7831. context.attachShader(shaderProgram, fragmentShader);
  7832. context.linkProgram(shaderProgram);
  7833. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7834. if (!linked) {
  7835. var error = context.getProgramInfoLog(shaderProgram);
  7836. if (error) {
  7837. throw new Error(error);
  7838. }
  7839. }
  7840. context.deleteShader(vertexShader);
  7841. context.deleteShader(fragmentShader);
  7842. return shaderProgram;
  7843. };
  7844. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7845. var results = [];
  7846. for (var index = 0; index < uniformsNames.length; index++) {
  7847. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7848. }
  7849. return results;
  7850. };
  7851. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7852. var results = [];
  7853. for (var index = 0; index < attributesNames.length; index++) {
  7854. try {
  7855. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7856. }
  7857. catch (e) {
  7858. results.push(-1);
  7859. }
  7860. }
  7861. return results;
  7862. };
  7863. Engine.prototype.enableEffect = function (effect) {
  7864. // Use program
  7865. this.setProgram(effect.getProgram());
  7866. this._currentEffect = effect;
  7867. if (effect.onBind) {
  7868. effect.onBind(effect);
  7869. }
  7870. };
  7871. Engine.prototype.setIntArray = function (uniform, array) {
  7872. if (!uniform)
  7873. return;
  7874. this._gl.uniform1iv(uniform, array);
  7875. };
  7876. Engine.prototype.setIntArray2 = function (uniform, array) {
  7877. if (!uniform || array.length % 2 !== 0)
  7878. return;
  7879. this._gl.uniform2iv(uniform, array);
  7880. };
  7881. Engine.prototype.setIntArray3 = function (uniform, array) {
  7882. if (!uniform || array.length % 3 !== 0)
  7883. return;
  7884. this._gl.uniform3iv(uniform, array);
  7885. };
  7886. Engine.prototype.setIntArray4 = function (uniform, array) {
  7887. if (!uniform || array.length % 4 !== 0)
  7888. return;
  7889. this._gl.uniform4iv(uniform, array);
  7890. };
  7891. Engine.prototype.setFloatArray = function (uniform, array) {
  7892. if (!uniform)
  7893. return;
  7894. this._gl.uniform1fv(uniform, array);
  7895. };
  7896. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7897. if (!uniform || array.length % 2 !== 0)
  7898. return;
  7899. this._gl.uniform2fv(uniform, array);
  7900. };
  7901. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7902. if (!uniform || array.length % 3 !== 0)
  7903. return;
  7904. this._gl.uniform3fv(uniform, array);
  7905. };
  7906. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7907. if (!uniform || array.length % 4 !== 0)
  7908. return;
  7909. this._gl.uniform4fv(uniform, array);
  7910. };
  7911. Engine.prototype.setArray = function (uniform, array) {
  7912. if (!uniform)
  7913. return;
  7914. this._gl.uniform1fv(uniform, array);
  7915. };
  7916. Engine.prototype.setArray2 = function (uniform, array) {
  7917. if (!uniform || array.length % 2 !== 0)
  7918. return;
  7919. this._gl.uniform2fv(uniform, array);
  7920. };
  7921. Engine.prototype.setArray3 = function (uniform, array) {
  7922. if (!uniform || array.length % 3 !== 0)
  7923. return;
  7924. this._gl.uniform3fv(uniform, array);
  7925. };
  7926. Engine.prototype.setArray4 = function (uniform, array) {
  7927. if (!uniform || array.length % 4 !== 0)
  7928. return;
  7929. this._gl.uniform4fv(uniform, array);
  7930. };
  7931. Engine.prototype.setMatrices = function (uniform, matrices) {
  7932. if (!uniform)
  7933. return;
  7934. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7935. };
  7936. Engine.prototype.setMatrix = function (uniform, matrix) {
  7937. if (!uniform)
  7938. return;
  7939. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7940. };
  7941. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7942. if (!uniform)
  7943. return;
  7944. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7945. };
  7946. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7947. if (!uniform)
  7948. return;
  7949. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7950. };
  7951. Engine.prototype.setFloat = function (uniform, value) {
  7952. if (!uniform)
  7953. return;
  7954. this._gl.uniform1f(uniform, value);
  7955. };
  7956. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7957. if (!uniform)
  7958. return;
  7959. this._gl.uniform2f(uniform, x, y);
  7960. };
  7961. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7962. if (!uniform)
  7963. return;
  7964. this._gl.uniform3f(uniform, x, y, z);
  7965. };
  7966. Engine.prototype.setBool = function (uniform, bool) {
  7967. if (!uniform)
  7968. return;
  7969. this._gl.uniform1i(uniform, bool);
  7970. };
  7971. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7972. if (!uniform)
  7973. return;
  7974. this._gl.uniform4f(uniform, x, y, z, w);
  7975. };
  7976. Engine.prototype.setColor3 = function (uniform, color3) {
  7977. if (!uniform)
  7978. return;
  7979. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7980. };
  7981. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7982. if (!uniform)
  7983. return;
  7984. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7985. };
  7986. // States
  7987. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7988. if (zOffset === void 0) { zOffset = 0; }
  7989. if (reverseSide === void 0) { reverseSide = false; }
  7990. // Culling
  7991. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7992. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7993. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7994. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7995. if (culling) {
  7996. this._depthCullingState.cullFace = cullFace;
  7997. this._depthCullingState.cull = true;
  7998. }
  7999. else {
  8000. this._depthCullingState.cull = false;
  8001. }
  8002. }
  8003. // Z offset
  8004. this._depthCullingState.zOffset = zOffset;
  8005. };
  8006. Engine.prototype.setDepthBuffer = function (enable) {
  8007. this._depthCullingState.depthTest = enable;
  8008. };
  8009. Engine.prototype.getDepthWrite = function () {
  8010. return this._depthCullingState.depthMask;
  8011. };
  8012. Engine.prototype.setDepthWrite = function (enable) {
  8013. this._depthCullingState.depthMask = enable;
  8014. };
  8015. Engine.prototype.setColorWrite = function (enable) {
  8016. this._gl.colorMask(enable, enable, enable, enable);
  8017. };
  8018. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8019. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8020. if (this._alphaMode === mode) {
  8021. return;
  8022. }
  8023. switch (mode) {
  8024. case Engine.ALPHA_DISABLE:
  8025. this._alphaState.alphaBlend = false;
  8026. break;
  8027. case Engine.ALPHA_PREMULTIPLIED:
  8028. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8029. this._alphaState.alphaBlend = true;
  8030. break;
  8031. case Engine.ALPHA_COMBINE:
  8032. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8033. this._alphaState.alphaBlend = true;
  8034. break;
  8035. case Engine.ALPHA_ONEONE:
  8036. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8037. this._alphaState.alphaBlend = true;
  8038. break;
  8039. case Engine.ALPHA_ADD:
  8040. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8041. this._alphaState.alphaBlend = true;
  8042. break;
  8043. case Engine.ALPHA_SUBTRACT:
  8044. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8045. this._alphaState.alphaBlend = true;
  8046. break;
  8047. case Engine.ALPHA_MULTIPLY:
  8048. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8049. this._alphaState.alphaBlend = true;
  8050. break;
  8051. case Engine.ALPHA_MAXIMIZED:
  8052. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8053. this._alphaState.alphaBlend = true;
  8054. break;
  8055. }
  8056. if (!noDepthWriteChange) {
  8057. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8058. }
  8059. this._alphaMode = mode;
  8060. };
  8061. Engine.prototype.getAlphaMode = function () {
  8062. return this._alphaMode;
  8063. };
  8064. Engine.prototype.setAlphaTesting = function (enable) {
  8065. this._alphaTest = enable;
  8066. };
  8067. Engine.prototype.getAlphaTesting = function () {
  8068. return this._alphaTest;
  8069. };
  8070. // Textures
  8071. Engine.prototype.wipeCaches = function () {
  8072. this.resetTextureCache();
  8073. this._currentEffect = null;
  8074. this._stencilState.reset();
  8075. this._depthCullingState.reset();
  8076. this.setDepthFunctionToLessOrEqual();
  8077. this._alphaState.reset();
  8078. this._cachedVertexBuffers = null;
  8079. this._cachedIndexBuffer = null;
  8080. this._cachedEffectForVertexBuffers = null;
  8081. this._unBindVertexArrayObject();
  8082. this.bindIndexBuffer(null);
  8083. this.bindArrayBuffer(null);
  8084. };
  8085. /**
  8086. * Set the compressed texture format to use, based on the formats you have, and the formats
  8087. * supported by the hardware / browser.
  8088. *
  8089. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8090. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8091. * to API arguments needed to compressed textures. This puts the burden on the container
  8092. * generator to house the arcane code for determining these for current & future formats.
  8093. *
  8094. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8095. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8096. *
  8097. * Note: The result of this call is not taken into account when a texture is base64.
  8098. *
  8099. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8100. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8101. *
  8102. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  8103. * @returns The extension selected.
  8104. */
  8105. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8106. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8107. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8108. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8109. return this._textureFormatInUse = this._texturesSupported[i];
  8110. }
  8111. }
  8112. }
  8113. // actively set format to nothing, to allow this to be called more than once
  8114. // and possibly fail the 2nd time
  8115. return this._textureFormatInUse = null;
  8116. };
  8117. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack) {
  8118. var _this = this;
  8119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8120. if (onLoad === void 0) { onLoad = null; }
  8121. if (onError === void 0) { onError = null; }
  8122. if (buffer === void 0) { buffer = null; }
  8123. var texture = fallBack ? fallBack : this._gl.createTexture();
  8124. var extension;
  8125. var isKTX = false;
  8126. var fromData = false;
  8127. var url = String(urlArg);
  8128. if (url.substr(0, 5) === "data:") {
  8129. fromData = true;
  8130. }
  8131. if (!fromData) {
  8132. var lastDot = url.lastIndexOf('.');
  8133. extension = url.substring(lastDot).toLowerCase();
  8134. if (this._textureFormatInUse && !fromData && !fallBack) {
  8135. extension = this._textureFormatInUse;
  8136. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8137. isKTX = true;
  8138. }
  8139. }
  8140. else {
  8141. var oldUrl = url;
  8142. fromData = oldUrl.split(':');
  8143. url = oldUrl;
  8144. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8145. }
  8146. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8147. var isTGA = (extension === ".tga");
  8148. scene._addPendingData(texture);
  8149. texture.url = url;
  8150. texture.noMipmap = noMipmap;
  8151. texture.references = 1;
  8152. texture.samplingMode = samplingMode;
  8153. texture.onLoadedCallbacks = [];
  8154. if (onLoad) {
  8155. texture.onLoadedCallbacks.push(onLoad);
  8156. }
  8157. if (!fallBack)
  8158. this._loadedTexturesCache.push(texture);
  8159. var onerror = function () {
  8160. scene._removePendingData(texture);
  8161. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8162. if (isKTX) {
  8163. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  8164. }
  8165. else if (onError) {
  8166. onError();
  8167. }
  8168. };
  8169. var callback;
  8170. if (isKTX || isTGA || isDDS) {
  8171. if (isKTX) {
  8172. callback = function (data) {
  8173. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8174. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8175. ktx.uploadLevels(_this._gl, !noMipmap);
  8176. }, samplingMode);
  8177. };
  8178. }
  8179. else if (isTGA) {
  8180. callback = function (arrayBuffer) {
  8181. var data = new Uint8Array(arrayBuffer);
  8182. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8183. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8184. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8185. }, samplingMode);
  8186. };
  8187. }
  8188. else if (isDDS) {
  8189. callback = function (data) {
  8190. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8191. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8192. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8193. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8194. }, samplingMode);
  8195. };
  8196. }
  8197. if (!(fromData instanceof Array))
  8198. BABYLON.Tools.LoadFile(url, function (data) {
  8199. callback(data);
  8200. }, null, scene.database, true, onerror);
  8201. else
  8202. callback(buffer);
  8203. }
  8204. else {
  8205. var onload = function (img) {
  8206. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8207. var isPot = (img.width === potWidth && img.height === potHeight);
  8208. if (!isPot) {
  8209. _this._prepareWorkingCanvas();
  8210. _this._workingCanvas.width = potWidth;
  8211. _this._workingCanvas.height = potHeight;
  8212. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8213. _this._workingContext.imageSmoothingEnabled = false;
  8214. _this._workingContext.mozImageSmoothingEnabled = false;
  8215. _this._workingContext.oImageSmoothingEnabled = false;
  8216. _this._workingContext.webkitImageSmoothingEnabled = false;
  8217. _this._workingContext.msImageSmoothingEnabled = false;
  8218. }
  8219. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8220. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8221. _this._workingContext.imageSmoothingEnabled = true;
  8222. _this._workingContext.mozImageSmoothingEnabled = true;
  8223. _this._workingContext.oImageSmoothingEnabled = true;
  8224. _this._workingContext.webkitImageSmoothingEnabled = true;
  8225. _this._workingContext.msImageSmoothingEnabled = true;
  8226. }
  8227. }
  8228. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8229. }, samplingMode);
  8230. };
  8231. if (!(fromData instanceof Array))
  8232. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8233. else
  8234. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8235. }
  8236. return texture;
  8237. };
  8238. Engine.prototype._getInternalFormat = function (format) {
  8239. var internalFormat = this._gl.RGBA;
  8240. switch (format) {
  8241. case Engine.TEXTUREFORMAT_ALPHA:
  8242. internalFormat = this._gl.ALPHA;
  8243. break;
  8244. case Engine.TEXTUREFORMAT_LUMINANCE:
  8245. internalFormat = this._gl.LUMINANCE;
  8246. break;
  8247. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8248. internalFormat = this._gl.LUMINANCE_ALPHA;
  8249. break;
  8250. case Engine.TEXTUREFORMAT_RGB:
  8251. internalFormat = this._gl.RGB;
  8252. break;
  8253. case Engine.TEXTUREFORMAT_RGBA:
  8254. internalFormat = this._gl.RGBA;
  8255. break;
  8256. }
  8257. return internalFormat;
  8258. };
  8259. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8260. if (compression === void 0) { compression = null; }
  8261. var internalFormat = this._getInternalFormat(format);
  8262. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8263. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8264. if (texture._width % 4 !== 0) {
  8265. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8266. }
  8267. if (compression) {
  8268. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8269. }
  8270. else {
  8271. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8272. }
  8273. if (texture.generateMipMaps) {
  8274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8275. }
  8276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8277. this.resetTextureCache();
  8278. texture.isReady = true;
  8279. };
  8280. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8281. if (compression === void 0) { compression = null; }
  8282. var texture = this._gl.createTexture();
  8283. texture._baseWidth = width;
  8284. texture._baseHeight = height;
  8285. texture._width = width;
  8286. texture._height = height;
  8287. texture.references = 1;
  8288. this.updateRawTexture(texture, data, format, invertY, compression);
  8289. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8290. // Filters
  8291. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8292. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8293. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8294. if (generateMipMaps) {
  8295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8296. }
  8297. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8298. texture.samplingMode = samplingMode;
  8299. this._loadedTexturesCache.push(texture);
  8300. return texture;
  8301. };
  8302. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8303. var texture = this._gl.createTexture();
  8304. texture._baseWidth = width;
  8305. texture._baseHeight = height;
  8306. if (generateMipMaps) {
  8307. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8308. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8309. }
  8310. this.resetTextureCache();
  8311. texture._width = width;
  8312. texture._height = height;
  8313. texture.isReady = false;
  8314. texture.generateMipMaps = generateMipMaps;
  8315. texture.references = 1;
  8316. texture.samplingMode = samplingMode;
  8317. this.updateTextureSamplingMode(samplingMode, texture);
  8318. this._loadedTexturesCache.push(texture);
  8319. return texture;
  8320. };
  8321. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8322. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8323. if (texture.isCube) {
  8324. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8325. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8326. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8327. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8328. }
  8329. else {
  8330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8333. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8334. }
  8335. texture.samplingMode = samplingMode;
  8336. };
  8337. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8338. if (premulAlpha === void 0) { premulAlpha = false; }
  8339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8341. if (premulAlpha) {
  8342. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8343. }
  8344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8345. if (texture.generateMipMaps) {
  8346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8347. }
  8348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8349. if (premulAlpha) {
  8350. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8351. }
  8352. this.resetTextureCache();
  8353. texture.isReady = true;
  8354. };
  8355. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8356. if (texture._isDisabled) {
  8357. return;
  8358. }
  8359. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8360. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8361. try {
  8362. // Testing video texture support
  8363. if (this._videoTextureSupported === undefined) {
  8364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8365. if (this._gl.getError() !== 0) {
  8366. this._videoTextureSupported = false;
  8367. }
  8368. else {
  8369. this._videoTextureSupported = true;
  8370. }
  8371. }
  8372. // Copy video through the current working canvas if video texture is not supported
  8373. if (!this._videoTextureSupported) {
  8374. if (!texture._workingCanvas) {
  8375. texture._workingCanvas = document.createElement("canvas");
  8376. texture._workingContext = texture._workingCanvas.getContext("2d");
  8377. texture._workingCanvas.width = texture._width;
  8378. texture._workingCanvas.height = texture._height;
  8379. }
  8380. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8381. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8382. }
  8383. else {
  8384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8385. }
  8386. if (texture.generateMipMaps) {
  8387. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8388. }
  8389. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8390. this.resetTextureCache();
  8391. texture.isReady = true;
  8392. }
  8393. catch (ex) {
  8394. // Something unexpected
  8395. // Let's disable the texture
  8396. texture._isDisabled = true;
  8397. }
  8398. };
  8399. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8400. // old version had a "generateMipMaps" arg instead of options.
  8401. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8402. // in the same way, generateDepthBuffer is defaulted to true
  8403. var generateMipMaps = false;
  8404. var generateDepthBuffer = true;
  8405. var generateStencilBuffer = false;
  8406. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8407. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8408. if (options !== undefined) {
  8409. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8410. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8411. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8412. type = options.type === undefined ? type : options.type;
  8413. if (options.samplingMode !== undefined) {
  8414. samplingMode = options.samplingMode;
  8415. }
  8416. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8417. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8418. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8419. }
  8420. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8421. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8422. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8423. }
  8424. }
  8425. var gl = this._gl;
  8426. var texture = gl.createTexture();
  8427. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8428. var width = size.width || size;
  8429. var height = size.height || size;
  8430. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8431. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8432. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8433. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8434. }
  8435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8439. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  8440. var depthStencilBuffer;
  8441. // Create the depth/stencil buffer
  8442. if (generateStencilBuffer) {
  8443. depthStencilBuffer = gl.createRenderbuffer();
  8444. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8445. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8446. }
  8447. else if (generateDepthBuffer) {
  8448. depthStencilBuffer = gl.createRenderbuffer();
  8449. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8450. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8451. }
  8452. // Create the framebuffer
  8453. var framebuffer = gl.createFramebuffer();
  8454. this.bindUnboundFramebuffer(framebuffer);
  8455. // Manage attachments
  8456. if (generateStencilBuffer) {
  8457. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8458. }
  8459. else if (generateDepthBuffer) {
  8460. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8461. }
  8462. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8463. if (generateMipMaps) {
  8464. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8465. }
  8466. // Unbind
  8467. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8468. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8469. this.bindUnboundFramebuffer(null);
  8470. texture._framebuffer = framebuffer;
  8471. if (generateDepthBuffer) {
  8472. texture._depthBuffer = depthStencilBuffer;
  8473. }
  8474. texture._baseWidth = width;
  8475. texture._baseHeight = height;
  8476. texture._width = width;
  8477. texture._height = height;
  8478. texture.isReady = true;
  8479. texture.generateMipMaps = generateMipMaps;
  8480. texture.references = 1;
  8481. texture.samplingMode = samplingMode;
  8482. texture.type = type;
  8483. this.resetTextureCache();
  8484. this._loadedTexturesCache.push(texture);
  8485. return texture;
  8486. };
  8487. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8488. var gl = this._gl;
  8489. var texture = gl.createTexture();
  8490. var generateMipMaps = true;
  8491. var generateDepthBuffer = true;
  8492. var generateStencilBuffer = false;
  8493. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8494. if (options !== undefined) {
  8495. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8496. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8497. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8498. if (options.samplingMode !== undefined) {
  8499. samplingMode = options.samplingMode;
  8500. }
  8501. }
  8502. texture.isCube = true;
  8503. texture.references = 1;
  8504. texture.generateMipMaps = generateMipMaps;
  8505. texture.references = 1;
  8506. texture.samplingMode = samplingMode;
  8507. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8508. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8509. for (var face = 0; face < 6; face++) {
  8510. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8511. }
  8512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8516. // Create the depth buffer
  8517. var depthStencilBuffer;
  8518. // Create the depth/stencil buffer
  8519. if (generateStencilBuffer) {
  8520. depthStencilBuffer = gl.createRenderbuffer();
  8521. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8522. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8523. }
  8524. else if (generateDepthBuffer) {
  8525. depthStencilBuffer = gl.createRenderbuffer();
  8526. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8527. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8528. }
  8529. // Create the framebuffer
  8530. var framebuffer = gl.createFramebuffer();
  8531. this.bindUnboundFramebuffer(framebuffer);
  8532. // Manage attachments
  8533. if (generateStencilBuffer) {
  8534. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8535. }
  8536. else if (generateDepthBuffer) {
  8537. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8538. }
  8539. // Mipmaps
  8540. if (texture.generateMipMaps) {
  8541. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8542. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8543. }
  8544. // Unbind
  8545. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8546. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8547. this.bindUnboundFramebuffer(null);
  8548. texture._framebuffer = framebuffer;
  8549. if (generateDepthBuffer) {
  8550. texture._depthBuffer = depthStencilBuffer;
  8551. }
  8552. texture._width = size;
  8553. texture._height = size;
  8554. texture.isReady = true;
  8555. this.resetTextureCache();
  8556. this._loadedTexturesCache.push(texture);
  8557. return texture;
  8558. };
  8559. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8560. var _this = this;
  8561. if (onLoad === void 0) { onLoad = null; }
  8562. if (onError === void 0) { onError = null; }
  8563. var gl = this._gl;
  8564. var texture = gl.createTexture();
  8565. texture.isCube = true;
  8566. texture.url = rootUrl;
  8567. texture.references = 1;
  8568. texture.onLoadedCallbacks = [];
  8569. var isKTX = false;
  8570. var lastDot = rootUrl.lastIndexOf('.');
  8571. var extension = rootUrl.substring(lastDot).toLowerCase();
  8572. if (this._textureFormatInUse) {
  8573. extension = this._textureFormatInUse;
  8574. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  8575. isKTX = true;
  8576. }
  8577. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8578. if (isKTX) {
  8579. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8580. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  8581. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  8582. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8584. ktx.uploadLevels(_this._gl, !noMipmap);
  8585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8589. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8590. _this.resetTextureCache();
  8591. texture._width = ktx.pixelWidth;
  8592. texture._height = ktx.pixelHeight;
  8593. texture.isReady = true;
  8594. }, null, null, true, onError);
  8595. }
  8596. else if (isDDS) {
  8597. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8598. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8599. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8600. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8601. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8602. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8603. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8604. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8605. }
  8606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8610. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8611. _this.resetTextureCache();
  8612. texture._width = info.width;
  8613. texture._height = info.height;
  8614. texture.isReady = true;
  8615. }, null, null, true, onError);
  8616. }
  8617. else {
  8618. cascadeLoad(rootUrl, scene, function (imgs) {
  8619. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8620. var height = width;
  8621. _this._prepareWorkingCanvas();
  8622. _this._workingCanvas.width = width;
  8623. _this._workingCanvas.height = height;
  8624. var faces = [
  8625. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8626. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8627. ];
  8628. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8629. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8630. for (var index = 0; index < faces.length; index++) {
  8631. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8632. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8633. }
  8634. if (!noMipmap) {
  8635. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8636. }
  8637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8642. _this.resetTextureCache();
  8643. texture._width = width;
  8644. texture._height = height;
  8645. texture.isReady = true;
  8646. texture.onLoadedCallbacks.forEach(function (callback) {
  8647. callback();
  8648. });
  8649. if (onLoad) {
  8650. onLoad();
  8651. }
  8652. }, files, onError);
  8653. }
  8654. this._loadedTexturesCache.push(texture);
  8655. return texture;
  8656. };
  8657. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8658. texture._width = width;
  8659. texture._height = height;
  8660. texture._size = width * height;
  8661. texture._baseWidth = width;
  8662. texture._baseHeight = height;
  8663. };
  8664. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8665. var _this = this;
  8666. var gl = this._gl;
  8667. var texture = gl.createTexture();
  8668. scene._addPendingData(texture);
  8669. texture.isCube = true;
  8670. texture.references = 1;
  8671. texture.url = url;
  8672. var textureType = gl.UNSIGNED_BYTE;
  8673. if (type === Engine.TEXTURETYPE_FLOAT) {
  8674. textureType = gl.FLOAT;
  8675. }
  8676. var internalFormat = this._getInternalFormat(format);
  8677. var needConversion = false;
  8678. if (internalFormat === gl.RGB) {
  8679. internalFormat = gl.RGBA;
  8680. needConversion = true;
  8681. }
  8682. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  8683. var width = size;
  8684. var height = width;
  8685. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8686. texture._width = width;
  8687. texture._height = height;
  8688. var onerror = function () {
  8689. scene._removePendingData(texture);
  8690. };
  8691. var internalCallback = function (data) {
  8692. var rgbeDataArrays = callback(data);
  8693. var facesIndex = [
  8694. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8695. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8696. ];
  8697. width = texture._width;
  8698. height = texture._height;
  8699. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8700. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8701. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8702. if (mipmmapGenerator) {
  8703. var arrayTemp = [];
  8704. // Data are known to be in +X +Y +Z -X -Y -Z
  8705. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8706. arrayTemp.push(rgbeDataArrays[0]); // +X
  8707. arrayTemp.push(rgbeDataArrays[3]); // -X
  8708. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8709. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8710. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8711. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8712. var mipData = mipmmapGenerator(arrayTemp);
  8713. // mipData is order in +X -X +Y -Y +Z -Z
  8714. var mipFaces = [0, 2, 4, 1, 3, 5];
  8715. for (var level = 0; level < mipData.length; level++) {
  8716. var mipSize = width >> level;
  8717. for (var mipIndex in mipFaces) {
  8718. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  8719. if (needConversion) {
  8720. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  8721. }
  8722. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  8723. }
  8724. }
  8725. }
  8726. else {
  8727. // Data are known to be in +X +Y +Z -X -Y -Z
  8728. for (var index = 0; index < facesIndex.length; index++) {
  8729. var faceData = rgbeDataArrays[index];
  8730. if (needConversion) {
  8731. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  8732. }
  8733. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  8734. }
  8735. if (!noMipmap && isPot) {
  8736. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8737. }
  8738. else {
  8739. noMipmap = true;
  8740. }
  8741. }
  8742. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8745. }
  8746. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8749. }
  8750. else {
  8751. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8752. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8753. }
  8754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8756. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8757. texture.isReady = true;
  8758. _this.resetTextureCache();
  8759. scene._removePendingData(texture);
  8760. };
  8761. BABYLON.Tools.LoadFile(url, function (data) {
  8762. internalCallback(data);
  8763. }, onerror, scene.database, true);
  8764. return texture;
  8765. };
  8766. ;
  8767. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  8768. // Create new RGBA data container.
  8769. var rgbaData;
  8770. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  8771. rgbaData = new Float32Array(width * height * 4);
  8772. }
  8773. else {
  8774. rgbaData = new Uint32Array(width * height * 4);
  8775. }
  8776. // Convert each pixel.
  8777. for (var x = 0; x < width; x++) {
  8778. for (var y = 0; y < height; y++) {
  8779. var index = (y * width + x) * 3;
  8780. var newIndex = (y * width + x) * 4;
  8781. // Map Old Value to new value.
  8782. rgbaData[newIndex + 0] = rgbData[index + 0];
  8783. rgbaData[newIndex + 1] = rgbData[index + 1];
  8784. rgbaData[newIndex + 2] = rgbData[index + 2];
  8785. // Add fully opaque alpha channel.
  8786. rgbaData[newIndex + 3] = 1;
  8787. }
  8788. }
  8789. return rgbaData;
  8790. };
  8791. Engine.prototype._releaseTexture = function (texture) {
  8792. var gl = this._gl;
  8793. if (texture._framebuffer) {
  8794. gl.deleteFramebuffer(texture._framebuffer);
  8795. }
  8796. if (texture._depthBuffer) {
  8797. gl.deleteRenderbuffer(texture._depthBuffer);
  8798. }
  8799. gl.deleteTexture(texture);
  8800. // Unbind channels
  8801. this.unbindAllTextures();
  8802. var index = this._loadedTexturesCache.indexOf(texture);
  8803. if (index !== -1) {
  8804. this._loadedTexturesCache.splice(index, 1);
  8805. }
  8806. };
  8807. Engine.prototype.setProgram = function (program) {
  8808. if (this._currentProgram !== program) {
  8809. this._gl.useProgram(program);
  8810. this._currentProgram = program;
  8811. }
  8812. };
  8813. Engine.prototype.bindSamplers = function (effect) {
  8814. this.setProgram(effect.getProgram());
  8815. var samplers = effect.getSamplers();
  8816. for (var index = 0; index < samplers.length; index++) {
  8817. var uniform = effect.getUniform(samplers[index]);
  8818. this._gl.uniform1i(uniform, index);
  8819. }
  8820. this._currentEffect = null;
  8821. };
  8822. Engine.prototype.activateTexture = function (texture) {
  8823. if (this._activeTexture !== texture) {
  8824. this._gl.activeTexture(texture);
  8825. this._activeTexture = texture;
  8826. }
  8827. };
  8828. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8829. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8830. this._gl.bindTexture(target, texture);
  8831. this._activeTexturesCache[this._activeTexture] = texture;
  8832. }
  8833. };
  8834. Engine.prototype._bindTexture = function (channel, texture) {
  8835. if (channel < 0) {
  8836. return;
  8837. }
  8838. this.activateTexture(this._gl.TEXTURE0 + channel);
  8839. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8840. };
  8841. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8842. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8843. };
  8844. Engine.prototype.unbindAllTextures = function () {
  8845. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8846. this.activateTexture(this._gl["TEXTURE" + channel]);
  8847. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8848. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8849. }
  8850. };
  8851. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8852. if (channel < 0) {
  8853. return;
  8854. }
  8855. this._gl.uniform1i(uniform, channel);
  8856. this._setTexture(channel, texture);
  8857. };
  8858. Engine.prototype._setTexture = function (channel, texture) {
  8859. // Not ready?
  8860. if (!texture || !texture.isReady()) {
  8861. if (this._activeTexturesCache[channel] != null) {
  8862. this.activateTexture(this._gl["TEXTURE" + channel]);
  8863. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8864. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8865. }
  8866. return;
  8867. }
  8868. // Video
  8869. var alreadyActivated = false;
  8870. if (texture instanceof BABYLON.VideoTexture) {
  8871. this.activateTexture(this._gl["TEXTURE" + channel]);
  8872. alreadyActivated = true;
  8873. texture.update();
  8874. }
  8875. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8876. texture.delayLoad();
  8877. return;
  8878. }
  8879. var internalTexture = texture.getInternalTexture();
  8880. if (this._activeTexturesCache[channel] === internalTexture) {
  8881. return;
  8882. }
  8883. if (!alreadyActivated) {
  8884. this.activateTexture(this._gl["TEXTURE" + channel]);
  8885. }
  8886. if (internalTexture.isCube) {
  8887. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8888. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8889. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8890. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8891. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8892. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8893. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8894. }
  8895. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8896. }
  8897. else {
  8898. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8899. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8900. internalTexture._cachedWrapU = texture.wrapU;
  8901. switch (texture.wrapU) {
  8902. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8903. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8904. break;
  8905. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8906. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8907. break;
  8908. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8910. break;
  8911. }
  8912. }
  8913. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8914. internalTexture._cachedWrapV = texture.wrapV;
  8915. switch (texture.wrapV) {
  8916. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8917. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8918. break;
  8919. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8920. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8921. break;
  8922. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8923. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8924. break;
  8925. }
  8926. }
  8927. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8928. }
  8929. };
  8930. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8931. if (channel < 0) {
  8932. return;
  8933. }
  8934. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8935. this._textureUnits = new Int32Array(textures.length);
  8936. }
  8937. for (var i = 0; i < textures.length; i++) {
  8938. this._textureUnits[i] = channel + i;
  8939. }
  8940. this._gl.uniform1iv(uniform, this._textureUnits);
  8941. for (var index = 0; index < textures.length; index++) {
  8942. this._setTexture(channel + index, textures[index]);
  8943. }
  8944. };
  8945. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8946. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8947. var value = texture.anisotropicFilteringLevel;
  8948. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8949. value = 1;
  8950. }
  8951. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8952. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8953. texture._cachedAnisotropicFilteringLevel = value;
  8954. }
  8955. };
  8956. Engine.prototype.readPixels = function (x, y, width, height) {
  8957. var data = new Uint8Array(height * width * 4);
  8958. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8959. return data;
  8960. };
  8961. /**
  8962. * Add an externaly attached data from its key.
  8963. * This method call will fail and return false, if such key already exists.
  8964. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8965. * @param key the unique key that identifies the data
  8966. * @param data the data object to associate to the key for this Engine instance
  8967. * @return true if no such key were already present and the data was added successfully, false otherwise
  8968. */
  8969. Engine.prototype.addExternalData = function (key, data) {
  8970. return this._externalData.add(key, data);
  8971. };
  8972. /**
  8973. * Get an externaly attached data from its key
  8974. * @param key the unique key that identifies the data
  8975. * @return the associated data, if present (can be null), or undefined if not present
  8976. */
  8977. Engine.prototype.getExternalData = function (key) {
  8978. return this._externalData.get(key);
  8979. };
  8980. /**
  8981. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8982. * @param key the unique key that identifies the data
  8983. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8984. * @return the associated data, can be null if the factory returned null.
  8985. */
  8986. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8987. return this._externalData.getOrAddWithFactory(key, factory);
  8988. };
  8989. /**
  8990. * Remove an externaly attached data from the Engine instance
  8991. * @param key the unique key that identifies the data
  8992. * @return true if the data was successfully removed, false if it doesn't exist
  8993. */
  8994. Engine.prototype.removeExternalData = function (key) {
  8995. return this._externalData.remove(key);
  8996. };
  8997. Engine.prototype.releaseInternalTexture = function (texture) {
  8998. if (!texture) {
  8999. return;
  9000. }
  9001. texture.references--;
  9002. // Final reference ?
  9003. if (texture.references === 0) {
  9004. var texturesCache = this.getLoadedTexturesCache();
  9005. var index = texturesCache.indexOf(texture);
  9006. if (index > -1) {
  9007. texturesCache.splice(index, 1);
  9008. }
  9009. this._releaseTexture(texture);
  9010. }
  9011. };
  9012. Engine.prototype.unbindAllAttributes = function () {
  9013. if (this._mustWipeVertexAttributes) {
  9014. this._mustWipeVertexAttributes = false;
  9015. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9016. this._gl.disableVertexAttribArray(i);
  9017. this._vertexAttribArraysEnabled[i] = false;
  9018. this._currentBufferPointers[i] = null;
  9019. }
  9020. return;
  9021. }
  9022. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9023. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9024. continue;
  9025. }
  9026. this._gl.disableVertexAttribArray(i);
  9027. this._vertexAttribArraysEnabled[i] = false;
  9028. this._currentBufferPointers[i] = null;
  9029. }
  9030. };
  9031. // Dispose
  9032. Engine.prototype.dispose = function () {
  9033. this.hideLoadingUI();
  9034. this.stopRenderLoop();
  9035. // Release scenes
  9036. while (this.scenes.length) {
  9037. this.scenes[0].dispose();
  9038. }
  9039. // Release audio engine
  9040. Engine.audioEngine.dispose();
  9041. // Release effects
  9042. for (var name in this._compiledEffects) {
  9043. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9044. }
  9045. // Unbind
  9046. this.unbindAllAttributes();
  9047. this._gl = null;
  9048. //WebVR
  9049. this.disableVR();
  9050. // Events
  9051. window.removeEventListener("blur", this._onBlur);
  9052. window.removeEventListener("focus", this._onFocus);
  9053. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9054. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9055. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9056. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9057. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9058. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9059. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9060. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9061. };
  9062. // Loading screen
  9063. Engine.prototype.displayLoadingUI = function () {
  9064. this._loadingScreen.displayLoadingUI();
  9065. };
  9066. Engine.prototype.hideLoadingUI = function () {
  9067. this._loadingScreen.hideLoadingUI();
  9068. };
  9069. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9070. get: function () {
  9071. return this._loadingScreen;
  9072. },
  9073. set: function (loadingScreen) {
  9074. this._loadingScreen = loadingScreen;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9080. set: function (text) {
  9081. this._loadingScreen.loadingUIText = text;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9087. set: function (color) {
  9088. this._loadingScreen.loadingUIBackgroundColor = color;
  9089. },
  9090. enumerable: true,
  9091. configurable: true
  9092. });
  9093. Engine.prototype.attachContextLostEvent = function (callback) {
  9094. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9095. };
  9096. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9097. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9098. };
  9099. Engine.prototype.getVertexShaderSource = function (program) {
  9100. var shaders = this._gl.getAttachedShaders(program);
  9101. return this._gl.getShaderSource(shaders[0]);
  9102. };
  9103. Engine.prototype.getFragmentShaderSource = function (program) {
  9104. var shaders = this._gl.getAttachedShaders(program);
  9105. return this._gl.getShaderSource(shaders[1]);
  9106. };
  9107. // FPS
  9108. Engine.prototype.getFps = function () {
  9109. return this.fps;
  9110. };
  9111. Engine.prototype.getDeltaTime = function () {
  9112. return this.deltaTime;
  9113. };
  9114. Engine.prototype._measureFps = function () {
  9115. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9116. var length = this.previousFramesDuration.length;
  9117. if (length >= 2) {
  9118. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9119. }
  9120. if (length >= this.fpsRange) {
  9121. if (length > this.fpsRange) {
  9122. this.previousFramesDuration.splice(0, 1);
  9123. length = this.previousFramesDuration.length;
  9124. }
  9125. var sum = 0;
  9126. for (var id = 0; id < length - 1; id++) {
  9127. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9128. }
  9129. this.fps = 1000.0 / (sum / (length - 1));
  9130. }
  9131. };
  9132. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9133. if (this._webGLVersion > 1) {
  9134. return this._caps.colorBufferFloat;
  9135. }
  9136. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9137. };
  9138. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9139. if (this._webGLVersion > 1) {
  9140. return this._caps.colorBufferFloat;
  9141. }
  9142. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9143. };
  9144. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9145. Engine.prototype._canRenderToFramebuffer = function (type) {
  9146. var gl = this._gl;
  9147. //clear existing errors
  9148. while (gl.getError() !== gl.NO_ERROR) { }
  9149. var successful = true;
  9150. var texture = gl.createTexture();
  9151. gl.bindTexture(gl.TEXTURE_2D, texture);
  9152. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9155. var fb = gl.createFramebuffer();
  9156. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9158. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9159. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9160. successful = successful && (gl.getError() === gl.NO_ERROR);
  9161. //try render by clearing frame buffer's color buffer
  9162. if (successful) {
  9163. gl.clear(gl.COLOR_BUFFER_BIT);
  9164. successful = successful && (gl.getError() === gl.NO_ERROR);
  9165. }
  9166. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9167. if (successful) {
  9168. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9169. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9170. var readFormat = gl.RGBA;
  9171. var readType = gl.UNSIGNED_BYTE;
  9172. var buffer = new Uint8Array(4);
  9173. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9174. successful = successful && (gl.getError() === gl.NO_ERROR);
  9175. }
  9176. //clean up
  9177. gl.deleteTexture(texture);
  9178. gl.deleteFramebuffer(fb);
  9179. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9180. //clear accumulated errors
  9181. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9182. return successful;
  9183. };
  9184. Engine.prototype._getWebGLTextureType = function (type) {
  9185. if (type === Engine.TEXTURETYPE_FLOAT) {
  9186. return this._gl.FLOAT;
  9187. }
  9188. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9189. // Add Half Float Constant.
  9190. return Engine.HALF_FLOAT_OES;
  9191. }
  9192. return this._gl.UNSIGNED_BYTE;
  9193. };
  9194. ;
  9195. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9196. if (this._webGLVersion === 1) {
  9197. return this._gl.RGBA;
  9198. }
  9199. if (type === Engine.TEXTURETYPE_FLOAT) {
  9200. return Engine.RGBA32F;
  9201. }
  9202. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9203. return Engine.RGBA16F;
  9204. }
  9205. return this._gl.RGBA;
  9206. };
  9207. ;
  9208. // Statics
  9209. Engine.isSupported = function () {
  9210. try {
  9211. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9212. if (navigator.isCocoonJS) {
  9213. return true;
  9214. }
  9215. var tempcanvas = document.createElement("canvas");
  9216. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9217. return gl != null && !!window.WebGLRenderingContext;
  9218. }
  9219. catch (e) {
  9220. return false;
  9221. }
  9222. };
  9223. return Engine;
  9224. }());
  9225. // Const statics
  9226. Engine._ALPHA_DISABLE = 0;
  9227. Engine._ALPHA_ADD = 1;
  9228. Engine._ALPHA_COMBINE = 2;
  9229. Engine._ALPHA_SUBTRACT = 3;
  9230. Engine._ALPHA_MULTIPLY = 4;
  9231. Engine._ALPHA_MAXIMIZED = 5;
  9232. Engine._ALPHA_ONEONE = 6;
  9233. Engine._ALPHA_PREMULTIPLIED = 7;
  9234. Engine._DELAYLOADSTATE_NONE = 0;
  9235. Engine._DELAYLOADSTATE_LOADED = 1;
  9236. Engine._DELAYLOADSTATE_LOADING = 2;
  9237. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9238. Engine._TEXTUREFORMAT_ALPHA = 0;
  9239. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9240. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9241. Engine._TEXTUREFORMAT_RGB = 4;
  9242. Engine._TEXTUREFORMAT_RGBA = 5;
  9243. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9244. Engine._TEXTURETYPE_FLOAT = 1;
  9245. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9246. // Depht or Stencil test Constants.
  9247. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9248. 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.
  9249. 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.
  9250. 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.
  9251. 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.
  9252. 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.
  9253. 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.
  9254. 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.
  9255. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9256. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9257. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9258. // Stencil Actions Constants.
  9259. Engine._KEEP = 0x1E00;
  9260. Engine._REPLACE = 0x1E01;
  9261. Engine._INCR = 0x1E02;
  9262. Engine._DECR = 0x1E03;
  9263. Engine._INVERT = 0x150A;
  9264. Engine._INCR_WRAP = 0x8507;
  9265. Engine._DECR_WRAP = 0x8508;
  9266. // Updatable statics so stick with vars here
  9267. Engine.CollisionsEpsilon = 0.001;
  9268. Engine.CodeRepository = "src/";
  9269. Engine.ShadersRepository = "src/Shaders/";
  9270. BABYLON.Engine = Engine;
  9271. })(BABYLON || (BABYLON = {}));
  9272. //# sourceMappingURL=babylon.engine.js.map
  9273. var BABYLON;
  9274. (function (BABYLON) {
  9275. /**
  9276. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9277. */
  9278. var Node = (function () {
  9279. /**
  9280. * @constructor
  9281. * @param {string} name - the name and id to be given to this node
  9282. * @param {BABYLON.Scene} the scene this node will be added to
  9283. */
  9284. function Node(name, scene) {
  9285. this.state = "";
  9286. this.metadata = null;
  9287. this.doNotSerialize = false;
  9288. this.animations = new Array();
  9289. this._ranges = {};
  9290. this._childrenFlag = -1;
  9291. this._isEnabled = true;
  9292. this._isReady = true;
  9293. this._currentRenderId = -1;
  9294. this._parentRenderId = -1;
  9295. /**
  9296. * An event triggered when the mesh is disposed.
  9297. * @type {BABYLON.Observable}
  9298. */
  9299. this.onDisposeObservable = new BABYLON.Observable();
  9300. this.name = name;
  9301. this.id = name;
  9302. this._scene = scene;
  9303. this._initCache();
  9304. }
  9305. Object.defineProperty(Node.prototype, "parent", {
  9306. get: function () {
  9307. return this._parentNode;
  9308. },
  9309. set: function (parent) {
  9310. if (this._parentNode === parent) {
  9311. return;
  9312. }
  9313. if (this._parentNode) {
  9314. var index = this._parentNode._children.indexOf(this);
  9315. if (index !== -1) {
  9316. this._parentNode._children.splice(index, 1);
  9317. }
  9318. }
  9319. this._parentNode = parent;
  9320. if (this._parentNode) {
  9321. if (!this._parentNode._children) {
  9322. this._parentNode._children = new Array();
  9323. }
  9324. this._parentNode._children.push(this);
  9325. }
  9326. },
  9327. enumerable: true,
  9328. configurable: true
  9329. });
  9330. Node.prototype.getClassName = function () {
  9331. return "Node";
  9332. };
  9333. Object.defineProperty(Node.prototype, "onDispose", {
  9334. set: function (callback) {
  9335. if (this._onDisposeObserver) {
  9336. this.onDisposeObservable.remove(this._onDisposeObserver);
  9337. }
  9338. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9339. },
  9340. enumerable: true,
  9341. configurable: true
  9342. });
  9343. Node.prototype.getScene = function () {
  9344. return this._scene;
  9345. };
  9346. Node.prototype.getEngine = function () {
  9347. return this._scene.getEngine();
  9348. };
  9349. // override it in derived class
  9350. Node.prototype.getWorldMatrix = function () {
  9351. return BABYLON.Matrix.Identity();
  9352. };
  9353. // override it in derived class if you add new variables to the cache
  9354. // and call the parent class method
  9355. Node.prototype._initCache = function () {
  9356. this._cache = {};
  9357. this._cache.parent = undefined;
  9358. };
  9359. Node.prototype.updateCache = function (force) {
  9360. if (!force && this.isSynchronized())
  9361. return;
  9362. this._cache.parent = this.parent;
  9363. this._updateCache();
  9364. };
  9365. // override it in derived class if you add new variables to the cache
  9366. // and call the parent class method if !ignoreParentClass
  9367. Node.prototype._updateCache = function (ignoreParentClass) {
  9368. };
  9369. // override it in derived class if you add new variables to the cache
  9370. Node.prototype._isSynchronized = function () {
  9371. return true;
  9372. };
  9373. Node.prototype._markSyncedWithParent = function () {
  9374. this._parentRenderId = this.parent._currentRenderId;
  9375. };
  9376. Node.prototype.isSynchronizedWithParent = function () {
  9377. if (!this.parent) {
  9378. return true;
  9379. }
  9380. if (this._parentRenderId !== this.parent._currentRenderId) {
  9381. return false;
  9382. }
  9383. return this.parent.isSynchronized();
  9384. };
  9385. Node.prototype.isSynchronized = function (updateCache) {
  9386. var check = this.hasNewParent();
  9387. check = check || !this.isSynchronizedWithParent();
  9388. check = check || !this._isSynchronized();
  9389. if (updateCache)
  9390. this.updateCache(true);
  9391. return !check;
  9392. };
  9393. Node.prototype.hasNewParent = function (update) {
  9394. if (this._cache.parent === this.parent)
  9395. return false;
  9396. if (update)
  9397. this._cache.parent = this.parent;
  9398. return true;
  9399. };
  9400. /**
  9401. * Is this node ready to be used/rendered
  9402. * @return {boolean} is it ready
  9403. */
  9404. Node.prototype.isReady = function () {
  9405. return this._isReady;
  9406. };
  9407. /**
  9408. * Is this node enabled.
  9409. * If the node has a parent and is enabled, the parent will be inspected as well.
  9410. * @return {boolean} whether this node (and its parent) is enabled.
  9411. * @see setEnabled
  9412. */
  9413. Node.prototype.isEnabled = function () {
  9414. if (!this._isEnabled) {
  9415. return false;
  9416. }
  9417. if (this.parent) {
  9418. return this.parent.isEnabled();
  9419. }
  9420. return true;
  9421. };
  9422. /**
  9423. * Set the enabled state of this node.
  9424. * @param {boolean} value - the new enabled state
  9425. * @see isEnabled
  9426. */
  9427. Node.prototype.setEnabled = function (value) {
  9428. this._isEnabled = value;
  9429. };
  9430. /**
  9431. * Is this node a descendant of the given node.
  9432. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9433. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9434. * @see parent
  9435. */
  9436. Node.prototype.isDescendantOf = function (ancestor) {
  9437. if (this.parent) {
  9438. if (this.parent === ancestor) {
  9439. return true;
  9440. }
  9441. return this.parent.isDescendantOf(ancestor);
  9442. }
  9443. return false;
  9444. };
  9445. /**
  9446. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9447. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9448. * @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.
  9449. * @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.
  9450. */
  9451. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9452. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9453. if (!this._children) {
  9454. return;
  9455. }
  9456. for (var index = 0; index < this._children.length; index++) {
  9457. var item = this._children[index];
  9458. if (!predicate || predicate(item)) {
  9459. results.push(item);
  9460. }
  9461. if (!directDescendantsOnly) {
  9462. item._getDescendants(results, false, predicate);
  9463. }
  9464. }
  9465. };
  9466. /**
  9467. * Will return all nodes that have this node as ascendant.
  9468. * @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.
  9469. * @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.
  9470. * @return {BABYLON.Node[]} all children nodes of all types.
  9471. */
  9472. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9473. var results = [];
  9474. this._getDescendants(results, directDescendantsOnly, predicate);
  9475. return results;
  9476. };
  9477. /**
  9478. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  9479. * @Deprecated, legacy support.
  9480. * use getDecendants instead.
  9481. */
  9482. Node.prototype.getChildren = function (predicate) {
  9483. return this.getDescendants(true, predicate);
  9484. };
  9485. /**
  9486. * Get all child-meshes of this node.
  9487. */
  9488. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9489. var results = [];
  9490. this._getDescendants(results, directDecendantsOnly, function (node) {
  9491. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9492. });
  9493. return results;
  9494. };
  9495. Node.prototype._setReady = function (state) {
  9496. if (state === this._isReady) {
  9497. return;
  9498. }
  9499. if (!state) {
  9500. this._isReady = false;
  9501. return;
  9502. }
  9503. this._isReady = true;
  9504. if (this.onReady) {
  9505. this.onReady(this);
  9506. }
  9507. };
  9508. Node.prototype.getAnimationByName = function (name) {
  9509. for (var i = 0; i < this.animations.length; i++) {
  9510. var animation = this.animations[i];
  9511. if (animation.name === name) {
  9512. return animation;
  9513. }
  9514. }
  9515. return null;
  9516. };
  9517. Node.prototype.createAnimationRange = function (name, from, to) {
  9518. // check name not already in use
  9519. if (!this._ranges[name]) {
  9520. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9521. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9522. if (this.animations[i]) {
  9523. this.animations[i].createRange(name, from, to);
  9524. }
  9525. }
  9526. }
  9527. };
  9528. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9529. if (deleteFrames === void 0) { deleteFrames = true; }
  9530. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9531. if (this.animations[i]) {
  9532. this.animations[i].deleteRange(name, deleteFrames);
  9533. }
  9534. }
  9535. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9536. };
  9537. Node.prototype.getAnimationRange = function (name) {
  9538. return this._ranges[name];
  9539. };
  9540. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9541. var range = this.getAnimationRange(name);
  9542. if (!range) {
  9543. return null;
  9544. }
  9545. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9546. };
  9547. Node.prototype.serializeAnimationRanges = function () {
  9548. var serializationRanges = [];
  9549. for (var name in this._ranges) {
  9550. var range = {};
  9551. range.name = name;
  9552. range.from = this._ranges[name].from;
  9553. range.to = this._ranges[name].to;
  9554. serializationRanges.push(range);
  9555. }
  9556. return serializationRanges;
  9557. };
  9558. Node.prototype.dispose = function () {
  9559. this.parent = null;
  9560. // Callback
  9561. this.onDisposeObservable.notifyObservers(this);
  9562. this.onDisposeObservable.clear();
  9563. };
  9564. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9565. if (parsedNode.ranges) {
  9566. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9567. var data = parsedNode.ranges[index];
  9568. node.createAnimationRange(data.name, data.from, data.to);
  9569. }
  9570. }
  9571. };
  9572. return Node;
  9573. }());
  9574. __decorate([
  9575. BABYLON.serialize()
  9576. ], Node.prototype, "name", void 0);
  9577. __decorate([
  9578. BABYLON.serialize()
  9579. ], Node.prototype, "id", void 0);
  9580. __decorate([
  9581. BABYLON.serialize()
  9582. ], Node.prototype, "uniqueId", void 0);
  9583. __decorate([
  9584. BABYLON.serialize()
  9585. ], Node.prototype, "state", void 0);
  9586. __decorate([
  9587. BABYLON.serialize()
  9588. ], Node.prototype, "metadata", void 0);
  9589. BABYLON.Node = Node;
  9590. })(BABYLON || (BABYLON = {}));
  9591. //# sourceMappingURL=babylon.node.js.map
  9592. var BABYLON;
  9593. (function (BABYLON) {
  9594. var FilesInput = (function () {
  9595. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9596. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9597. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9598. this._engine = p_engine;
  9599. this._canvas = p_canvas;
  9600. this._currentScene = p_scene;
  9601. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9602. this._progressCallback = p_progressCallback;
  9603. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9604. this._textureLoadingCallback = p_textureLoadingCallback;
  9605. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9606. }
  9607. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9608. var _this = this;
  9609. if (p_elementToMonitor) {
  9610. this._elementToMonitor = p_elementToMonitor;
  9611. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9612. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9613. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9614. }
  9615. };
  9616. FilesInput.prototype.renderFunction = function () {
  9617. if (this._additionnalRenderLoopLogicCallback) {
  9618. this._additionnalRenderLoopLogicCallback();
  9619. }
  9620. if (this._currentScene) {
  9621. if (this._textureLoadingCallback) {
  9622. var remaining = this._currentScene.getWaitingItemsCount();
  9623. if (remaining > 0) {
  9624. this._textureLoadingCallback(remaining);
  9625. }
  9626. }
  9627. this._currentScene.render();
  9628. }
  9629. };
  9630. FilesInput.prototype.drag = function (e) {
  9631. e.stopPropagation();
  9632. e.preventDefault();
  9633. };
  9634. FilesInput.prototype.drop = function (eventDrop) {
  9635. eventDrop.stopPropagation();
  9636. eventDrop.preventDefault();
  9637. this.loadFiles(eventDrop);
  9638. };
  9639. FilesInput.prototype.loadFiles = function (event) {
  9640. if (this._startingProcessingFilesCallback)
  9641. this._startingProcessingFilesCallback();
  9642. // Handling data transfer via drag'n'drop
  9643. if (event && event.dataTransfer && event.dataTransfer.files) {
  9644. this._filesToLoad = event.dataTransfer.files;
  9645. }
  9646. // Handling files from input files
  9647. if (event && event.target && event.target.files) {
  9648. this._filesToLoad = event.target.files;
  9649. }
  9650. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9651. for (var i = 0; i < this._filesToLoad.length; i++) {
  9652. var name_1 = this._filesToLoad[i].name.toLowerCase();
  9653. var extension = name_1.split('.').pop();
  9654. var type = this._filesToLoad[i].type;
  9655. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  9656. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  9657. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  9658. }
  9659. else {
  9660. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  9661. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  9662. this._sceneFileToLoad = this._filesToLoad[i];
  9663. }
  9664. else {
  9665. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  9666. }
  9667. }
  9668. }
  9669. this.reload();
  9670. }
  9671. };
  9672. FilesInput.prototype.reload = function () {
  9673. var _this = this;
  9674. var that = this;
  9675. // If a ".babylon" file has been provided
  9676. if (this._sceneFileToLoad) {
  9677. if (this._currentScene) {
  9678. if (BABYLON.Tools.errorsCount > 0) {
  9679. BABYLON.Tools.ClearLogCache();
  9680. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9681. }
  9682. this._engine.stopRenderLoop();
  9683. this._currentScene.dispose();
  9684. }
  9685. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9686. that._currentScene = newScene;
  9687. // Wait for textures and shaders to be ready
  9688. that._currentScene.executeWhenReady(function () {
  9689. // Attach camera to canvas inputs
  9690. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9691. that._currentScene.createDefaultCameraOrLight();
  9692. }
  9693. that._currentScene.activeCamera.attachControl(that._canvas);
  9694. if (that._sceneLoadedCallback) {
  9695. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9696. }
  9697. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9698. });
  9699. }, function (progress) {
  9700. if (_this._progressCallback) {
  9701. _this._progressCallback(progress);
  9702. }
  9703. });
  9704. }
  9705. else {
  9706. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9707. }
  9708. };
  9709. return FilesInput;
  9710. }());
  9711. FilesInput.FilesTextures = new Array();
  9712. FilesInput.FilesToLoad = new Array();
  9713. BABYLON.FilesInput = FilesInput;
  9714. })(BABYLON || (BABYLON = {}));
  9715. //# sourceMappingURL=babylon.filesInput.js.map
  9716. var BABYLON;
  9717. (function (BABYLON) {
  9718. var IntersectionInfo = (function () {
  9719. function IntersectionInfo(bu, bv, distance) {
  9720. this.bu = bu;
  9721. this.bv = bv;
  9722. this.distance = distance;
  9723. this.faceId = 0;
  9724. this.subMeshId = 0;
  9725. }
  9726. return IntersectionInfo;
  9727. }());
  9728. BABYLON.IntersectionInfo = IntersectionInfo;
  9729. var PickingInfo = (function () {
  9730. function PickingInfo() {
  9731. this.hit = false;
  9732. this.distance = 0;
  9733. this.pickedPoint = null;
  9734. this.pickedMesh = null;
  9735. this.bu = 0;
  9736. this.bv = 0;
  9737. this.faceId = -1;
  9738. this.subMeshId = 0;
  9739. this.pickedSprite = null;
  9740. }
  9741. // Methods
  9742. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9743. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9744. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9745. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9746. return null;
  9747. }
  9748. var indices = this.pickedMesh.getIndices();
  9749. var result;
  9750. if (useVerticesNormals) {
  9751. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9752. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9753. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9754. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9755. normal0 = normal0.scale(this.bu);
  9756. normal1 = normal1.scale(this.bv);
  9757. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9758. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9759. }
  9760. else {
  9761. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9762. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9763. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9764. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9765. var p1p2 = vertex1.subtract(vertex2);
  9766. var p3p2 = vertex3.subtract(vertex2);
  9767. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9768. }
  9769. if (useWorldCoordinates) {
  9770. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9771. }
  9772. return BABYLON.Vector3.Normalize(result);
  9773. };
  9774. PickingInfo.prototype.getTextureCoordinates = function () {
  9775. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9776. return null;
  9777. }
  9778. var indices = this.pickedMesh.getIndices();
  9779. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9780. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9781. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9782. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9783. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9784. uv1 = uv1.scale(this.bu);
  9785. uv2 = uv2.scale(this.bv);
  9786. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9787. };
  9788. return PickingInfo;
  9789. }());
  9790. BABYLON.PickingInfo = PickingInfo;
  9791. })(BABYLON || (BABYLON = {}));
  9792. //# sourceMappingURL=babylon.pickingInfo.js.map
  9793. var BABYLON;
  9794. (function (BABYLON) {
  9795. var BoundingSphere = (function () {
  9796. function BoundingSphere(minimum, maximum) {
  9797. this.minimum = minimum;
  9798. this.maximum = maximum;
  9799. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9800. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9801. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9802. this.radius = distance * 0.5;
  9803. this.centerWorld = BABYLON.Vector3.Zero();
  9804. this._update(BABYLON.Matrix.Identity());
  9805. }
  9806. // Methods
  9807. BoundingSphere.prototype._update = function (world) {
  9808. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9809. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9810. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9811. };
  9812. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9813. for (var i = 0; i < 6; i++) {
  9814. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9815. return false;
  9816. }
  9817. return true;
  9818. };
  9819. BoundingSphere.prototype.intersectsPoint = function (point) {
  9820. var x = this.centerWorld.x - point.x;
  9821. var y = this.centerWorld.y - point.y;
  9822. var z = this.centerWorld.z - point.z;
  9823. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9824. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9825. return false;
  9826. return true;
  9827. };
  9828. // Statics
  9829. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9830. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9831. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9832. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9833. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9834. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9835. return false;
  9836. return true;
  9837. };
  9838. return BoundingSphere;
  9839. }());
  9840. BABYLON.BoundingSphere = BoundingSphere;
  9841. })(BABYLON || (BABYLON = {}));
  9842. //# sourceMappingURL=babylon.boundingSphere.js.map
  9843. var BABYLON;
  9844. (function (BABYLON) {
  9845. var BoundingBox = (function () {
  9846. function BoundingBox(minimum, maximum) {
  9847. this.minimum = minimum;
  9848. this.maximum = maximum;
  9849. this.vectors = new Array();
  9850. this.vectorsWorld = new Array();
  9851. // Bounding vectors
  9852. this.vectors.push(this.minimum.clone());
  9853. this.vectors.push(this.maximum.clone());
  9854. this.vectors.push(this.minimum.clone());
  9855. this.vectors[2].x = this.maximum.x;
  9856. this.vectors.push(this.minimum.clone());
  9857. this.vectors[3].y = this.maximum.y;
  9858. this.vectors.push(this.minimum.clone());
  9859. this.vectors[4].z = this.maximum.z;
  9860. this.vectors.push(this.maximum.clone());
  9861. this.vectors[5].z = this.minimum.z;
  9862. this.vectors.push(this.maximum.clone());
  9863. this.vectors[6].x = this.minimum.x;
  9864. this.vectors.push(this.maximum.clone());
  9865. this.vectors[7].y = this.minimum.y;
  9866. // OBB
  9867. this.center = this.maximum.add(this.minimum).scale(0.5);
  9868. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9869. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9870. // World
  9871. for (var index = 0; index < this.vectors.length; index++) {
  9872. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9873. }
  9874. this.minimumWorld = BABYLON.Vector3.Zero();
  9875. this.maximumWorld = BABYLON.Vector3.Zero();
  9876. this._update(BABYLON.Matrix.Identity());
  9877. }
  9878. // Methods
  9879. BoundingBox.prototype.getWorldMatrix = function () {
  9880. return this._worldMatrix;
  9881. };
  9882. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9883. this._worldMatrix.copyFrom(matrix);
  9884. return this;
  9885. };
  9886. BoundingBox.prototype._update = function (world) {
  9887. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9888. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9889. for (var index = 0; index < this.vectors.length; index++) {
  9890. var v = this.vectorsWorld[index];
  9891. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9892. if (v.x < this.minimumWorld.x)
  9893. this.minimumWorld.x = v.x;
  9894. if (v.y < this.minimumWorld.y)
  9895. this.minimumWorld.y = v.y;
  9896. if (v.z < this.minimumWorld.z)
  9897. this.minimumWorld.z = v.z;
  9898. if (v.x > this.maximumWorld.x)
  9899. this.maximumWorld.x = v.x;
  9900. if (v.y > this.maximumWorld.y)
  9901. this.maximumWorld.y = v.y;
  9902. if (v.z > this.maximumWorld.z)
  9903. this.maximumWorld.z = v.z;
  9904. }
  9905. // OBB
  9906. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9907. this.center.scaleInPlace(0.5);
  9908. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9909. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9910. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9911. this._worldMatrix = world;
  9912. };
  9913. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9914. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9915. };
  9916. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9917. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9918. };
  9919. BoundingBox.prototype.intersectsPoint = function (point) {
  9920. var delta = -BABYLON.Epsilon;
  9921. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9922. return false;
  9923. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9924. return false;
  9925. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9926. return false;
  9927. return true;
  9928. };
  9929. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9930. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9931. };
  9932. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9933. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9934. return false;
  9935. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9936. return false;
  9937. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9938. return false;
  9939. return true;
  9940. };
  9941. // Statics
  9942. BoundingBox.Intersects = function (box0, box1) {
  9943. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9944. return false;
  9945. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9946. return false;
  9947. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9948. return false;
  9949. return true;
  9950. };
  9951. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9952. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9953. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9954. return (num <= (sphereRadius * sphereRadius));
  9955. };
  9956. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9957. for (var p = 0; p < 6; p++) {
  9958. for (var i = 0; i < 8; i++) {
  9959. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9960. return false;
  9961. }
  9962. }
  9963. }
  9964. return true;
  9965. };
  9966. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9967. for (var p = 0; p < 6; p++) {
  9968. var inCount = 8;
  9969. for (var i = 0; i < 8; i++) {
  9970. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9971. --inCount;
  9972. }
  9973. else {
  9974. break;
  9975. }
  9976. }
  9977. if (inCount === 0)
  9978. return false;
  9979. }
  9980. return true;
  9981. };
  9982. return BoundingBox;
  9983. }());
  9984. BABYLON.BoundingBox = BoundingBox;
  9985. })(BABYLON || (BABYLON = {}));
  9986. //# sourceMappingURL=babylon.boundingBox.js.map
  9987. var BABYLON;
  9988. (function (BABYLON) {
  9989. var computeBoxExtents = function (axis, box) {
  9990. var p = BABYLON.Vector3.Dot(box.center, axis);
  9991. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9992. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9993. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9994. var r = r0 + r1 + r2;
  9995. return {
  9996. min: p - r,
  9997. max: p + r
  9998. };
  9999. };
  10000. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10001. var axisOverlap = function (axis, box0, box1) {
  10002. var result0 = computeBoxExtents(axis, box0);
  10003. var result1 = computeBoxExtents(axis, box1);
  10004. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10005. };
  10006. var BoundingInfo = (function () {
  10007. function BoundingInfo(minimum, maximum) {
  10008. this.minimum = minimum;
  10009. this.maximum = maximum;
  10010. this._isLocked = false;
  10011. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10012. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10013. }
  10014. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10015. get: function () {
  10016. return this._isLocked;
  10017. },
  10018. set: function (value) {
  10019. this._isLocked = value;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. // Methods
  10025. BoundingInfo.prototype.update = function (world) {
  10026. if (this._isLocked) {
  10027. return;
  10028. }
  10029. this.boundingBox._update(world);
  10030. this.boundingSphere._update(world);
  10031. };
  10032. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10033. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10034. return false;
  10035. return this.boundingBox.isInFrustum(frustumPlanes);
  10036. };
  10037. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10038. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10039. };
  10040. BoundingInfo.prototype._checkCollision = function (collider) {
  10041. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10042. };
  10043. BoundingInfo.prototype.intersectsPoint = function (point) {
  10044. if (!this.boundingSphere.centerWorld) {
  10045. return false;
  10046. }
  10047. if (!this.boundingSphere.intersectsPoint(point)) {
  10048. return false;
  10049. }
  10050. if (!this.boundingBox.intersectsPoint(point)) {
  10051. return false;
  10052. }
  10053. return true;
  10054. };
  10055. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10056. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10057. return false;
  10058. }
  10059. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10060. return false;
  10061. }
  10062. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10063. return false;
  10064. }
  10065. if (!precise) {
  10066. return true;
  10067. }
  10068. var box0 = this.boundingBox;
  10069. var box1 = boundingInfo.boundingBox;
  10070. if (!axisOverlap(box0.directions[0], box0, box1))
  10071. return false;
  10072. if (!axisOverlap(box0.directions[1], box0, box1))
  10073. return false;
  10074. if (!axisOverlap(box0.directions[2], box0, box1))
  10075. return false;
  10076. if (!axisOverlap(box1.directions[0], box0, box1))
  10077. return false;
  10078. if (!axisOverlap(box1.directions[1], box0, box1))
  10079. return false;
  10080. if (!axisOverlap(box1.directions[2], box0, box1))
  10081. return false;
  10082. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10083. return false;
  10084. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10085. return false;
  10086. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10087. return false;
  10088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10089. return false;
  10090. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10091. return false;
  10092. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10093. return false;
  10094. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10095. return false;
  10096. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10097. return false;
  10098. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10099. return false;
  10100. return true;
  10101. };
  10102. return BoundingInfo;
  10103. }());
  10104. BABYLON.BoundingInfo = BoundingInfo;
  10105. })(BABYLON || (BABYLON = {}));
  10106. //# sourceMappingURL=babylon.boundingInfo.js.map
  10107. var BABYLON;
  10108. (function (BABYLON) {
  10109. var Ray = (function () {
  10110. function Ray(origin, direction, length) {
  10111. if (length === void 0) { length = Number.MAX_VALUE; }
  10112. this.origin = origin;
  10113. this.direction = direction;
  10114. this.length = length;
  10115. }
  10116. // Methods
  10117. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10118. var d = 0.0;
  10119. var maxValue = Number.MAX_VALUE;
  10120. var inv;
  10121. var min;
  10122. var max;
  10123. var temp;
  10124. if (Math.abs(this.direction.x) < 0.0000001) {
  10125. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10126. return false;
  10127. }
  10128. }
  10129. else {
  10130. inv = 1.0 / this.direction.x;
  10131. min = (minimum.x - this.origin.x) * inv;
  10132. max = (maximum.x - this.origin.x) * inv;
  10133. if (max === -Infinity) {
  10134. max = Infinity;
  10135. }
  10136. if (min > max) {
  10137. temp = min;
  10138. min = max;
  10139. max = temp;
  10140. }
  10141. d = Math.max(min, d);
  10142. maxValue = Math.min(max, maxValue);
  10143. if (d > maxValue) {
  10144. return false;
  10145. }
  10146. }
  10147. if (Math.abs(this.direction.y) < 0.0000001) {
  10148. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10149. return false;
  10150. }
  10151. }
  10152. else {
  10153. inv = 1.0 / this.direction.y;
  10154. min = (minimum.y - this.origin.y) * inv;
  10155. max = (maximum.y - this.origin.y) * inv;
  10156. if (max === -Infinity) {
  10157. max = Infinity;
  10158. }
  10159. if (min > max) {
  10160. temp = min;
  10161. min = max;
  10162. max = temp;
  10163. }
  10164. d = Math.max(min, d);
  10165. maxValue = Math.min(max, maxValue);
  10166. if (d > maxValue) {
  10167. return false;
  10168. }
  10169. }
  10170. if (Math.abs(this.direction.z) < 0.0000001) {
  10171. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10172. return false;
  10173. }
  10174. }
  10175. else {
  10176. inv = 1.0 / this.direction.z;
  10177. min = (minimum.z - this.origin.z) * inv;
  10178. max = (maximum.z - this.origin.z) * inv;
  10179. if (max === -Infinity) {
  10180. max = Infinity;
  10181. }
  10182. if (min > max) {
  10183. temp = min;
  10184. min = max;
  10185. max = temp;
  10186. }
  10187. d = Math.max(min, d);
  10188. maxValue = Math.min(max, maxValue);
  10189. if (d > maxValue) {
  10190. return false;
  10191. }
  10192. }
  10193. return true;
  10194. };
  10195. Ray.prototype.intersectsBox = function (box) {
  10196. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10197. };
  10198. Ray.prototype.intersectsSphere = function (sphere) {
  10199. var x = sphere.center.x - this.origin.x;
  10200. var y = sphere.center.y - this.origin.y;
  10201. var z = sphere.center.z - this.origin.z;
  10202. var pyth = (x * x) + (y * y) + (z * z);
  10203. var rr = sphere.radius * sphere.radius;
  10204. if (pyth <= rr) {
  10205. return true;
  10206. }
  10207. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10208. if (dot < 0.0) {
  10209. return false;
  10210. }
  10211. var temp = pyth - (dot * dot);
  10212. return temp <= rr;
  10213. };
  10214. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10215. if (!this._edge1) {
  10216. this._edge1 = BABYLON.Vector3.Zero();
  10217. this._edge2 = BABYLON.Vector3.Zero();
  10218. this._pvec = BABYLON.Vector3.Zero();
  10219. this._tvec = BABYLON.Vector3.Zero();
  10220. this._qvec = BABYLON.Vector3.Zero();
  10221. }
  10222. vertex1.subtractToRef(vertex0, this._edge1);
  10223. vertex2.subtractToRef(vertex0, this._edge2);
  10224. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10225. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10226. if (det === 0) {
  10227. return null;
  10228. }
  10229. var invdet = 1 / det;
  10230. this.origin.subtractToRef(vertex0, this._tvec);
  10231. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10232. if (bu < 0 || bu > 1.0) {
  10233. return null;
  10234. }
  10235. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10236. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10237. if (bv < 0 || bu + bv > 1.0) {
  10238. return null;
  10239. }
  10240. //check if the distance is longer than the predefined length.
  10241. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10242. if (distance > this.length) {
  10243. return null;
  10244. }
  10245. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10246. };
  10247. Ray.prototype.intersectsPlane = function (plane) {
  10248. var distance;
  10249. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10250. if (Math.abs(result1) < 9.99999997475243E-07) {
  10251. return null;
  10252. }
  10253. else {
  10254. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10255. distance = (-plane.d - result2) / result1;
  10256. if (distance < 0.0) {
  10257. if (distance < -9.99999997475243E-07) {
  10258. return null;
  10259. }
  10260. else {
  10261. return 0;
  10262. }
  10263. }
  10264. return distance;
  10265. }
  10266. };
  10267. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10268. var tm = BABYLON.Tmp.Matrix[0];
  10269. mesh.getWorldMatrix().invertToRef(tm);
  10270. if (this._tmpRay) {
  10271. Ray.TransformToRef(this, tm, this._tmpRay);
  10272. }
  10273. else {
  10274. this._tmpRay = Ray.Transform(this, tm);
  10275. }
  10276. return mesh.intersects(this._tmpRay, fastCheck);
  10277. };
  10278. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  10279. if (results) {
  10280. results.length = 0;
  10281. }
  10282. else {
  10283. results = [];
  10284. }
  10285. for (var i = 0; i < meshes.length; i++) {
  10286. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  10287. if (pickInfo.hit) {
  10288. results.push(pickInfo);
  10289. }
  10290. }
  10291. results.sort(this._comparePickingInfo);
  10292. return results;
  10293. };
  10294. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  10295. if (pickingInfoA.distance < pickingInfoB.distance) {
  10296. return -1;
  10297. }
  10298. else if (pickingInfoA.distance > pickingInfoB.distance) {
  10299. return 1;
  10300. }
  10301. else {
  10302. return 0;
  10303. }
  10304. };
  10305. /**
  10306. * @Deprecated. Use new RayHelper.show() instead.
  10307. * */
  10308. Ray.prototype.show = function (scene, color) {
  10309. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  10310. if (!this._rayHelper) {
  10311. this._rayHelper = new BABYLON.RayHelper(this);
  10312. }
  10313. this._rayHelper.show(scene, color);
  10314. };
  10315. /**
  10316. * @Deprecated. Use new RayHelper.hide() instead.
  10317. * */
  10318. Ray.prototype.hide = function () {
  10319. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  10320. if (this._rayHelper) {
  10321. this._rayHelper.hide();
  10322. this._rayHelper = null;
  10323. }
  10324. };
  10325. /**
  10326. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10327. * @param sega the first point of the segment to test the intersection against
  10328. * @param segb the second point of the segment to test the intersection against
  10329. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10330. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10331. */
  10332. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10333. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10334. var u = segb.subtract(sega);
  10335. var v = rsegb.subtract(this.origin);
  10336. var w = sega.subtract(this.origin);
  10337. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10338. var b = BABYLON.Vector3.Dot(u, v);
  10339. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10340. var d = BABYLON.Vector3.Dot(u, w);
  10341. var e = BABYLON.Vector3.Dot(v, w);
  10342. var D = a * c - b * b; // always >= 0
  10343. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10344. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10345. // compute the line parameters of the two closest points
  10346. if (D < Ray.smallnum) {
  10347. sN = 0.0; // force using point P0 on segment S1
  10348. sD = 1.0; // to prevent possible division by 0.0 later
  10349. tN = e;
  10350. tD = c;
  10351. }
  10352. else {
  10353. sN = (b * e - c * d);
  10354. tN = (a * e - b * d);
  10355. if (sN < 0.0) {
  10356. sN = 0.0;
  10357. tN = e;
  10358. tD = c;
  10359. }
  10360. else if (sN > sD) {
  10361. sN = sD;
  10362. tN = e + b;
  10363. tD = c;
  10364. }
  10365. }
  10366. if (tN < 0.0) {
  10367. tN = 0.0;
  10368. // recompute sc for this edge
  10369. if (-d < 0.0) {
  10370. sN = 0.0;
  10371. }
  10372. else if (-d > a)
  10373. sN = sD;
  10374. else {
  10375. sN = -d;
  10376. sD = a;
  10377. }
  10378. }
  10379. else if (tN > tD) {
  10380. tN = tD;
  10381. // recompute sc for this edge
  10382. if ((-d + b) < 0.0) {
  10383. sN = 0;
  10384. }
  10385. else if ((-d + b) > a) {
  10386. sN = sD;
  10387. }
  10388. else {
  10389. sN = (-d + b);
  10390. sD = a;
  10391. }
  10392. }
  10393. // finally do the division to get sc and tc
  10394. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10395. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10396. // get the difference of the two closest points
  10397. var qtc = v.multiplyByFloats(tc, tc, tc);
  10398. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10399. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10400. if (isIntersected) {
  10401. return qtc.length();
  10402. }
  10403. return -1;
  10404. };
  10405. // Statics
  10406. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10407. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10408. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10409. var direction = end.subtract(start);
  10410. direction.normalize();
  10411. return new Ray(start, direction);
  10412. };
  10413. /**
  10414. * 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
  10415. * transformed to the given world matrix.
  10416. * @param origin The origin point
  10417. * @param end The end point
  10418. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10419. */
  10420. Ray.CreateNewFromTo = function (origin, end, world) {
  10421. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10422. var direction = end.subtract(origin);
  10423. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10424. direction.normalize();
  10425. return Ray.Transform(new Ray(origin, direction, length), world);
  10426. };
  10427. Ray.Transform = function (ray, matrix) {
  10428. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10429. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10430. newDirection.normalize();
  10431. return new Ray(newOrigin, newDirection, ray.length);
  10432. };
  10433. Ray.TransformToRef = function (ray, matrix, result) {
  10434. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10435. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10436. ray.direction.normalize();
  10437. };
  10438. return Ray;
  10439. }());
  10440. Ray.smallnum = 0.00000001;
  10441. Ray.rayl = 10e8;
  10442. BABYLON.Ray = Ray;
  10443. })(BABYLON || (BABYLON = {}));
  10444. //# sourceMappingURL=babylon.ray.js.map
  10445. var BABYLON;
  10446. (function (BABYLON) {
  10447. var RayHelper = (function () {
  10448. function RayHelper(ray) {
  10449. this.ray = ray;
  10450. }
  10451. RayHelper.prototype.show = function (scene, color) {
  10452. if (!this._renderFunction) {
  10453. var ray = this.ray;
  10454. this._renderFunction = this._render.bind(this);
  10455. this._scene = scene;
  10456. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  10457. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10458. this._scene.registerBeforeRender(this._renderFunction);
  10459. }
  10460. if (color) {
  10461. this._renderLine.color.copyFrom(color);
  10462. }
  10463. };
  10464. RayHelper.prototype.hide = function () {
  10465. if (this._renderFunction) {
  10466. this._scene.unregisterBeforeRender(this._renderFunction);
  10467. this._scene = null;
  10468. this._renderFunction = null;
  10469. this._renderLine.dispose();
  10470. this._renderLine = null;
  10471. this._renderPoints = null;
  10472. }
  10473. };
  10474. RayHelper.prototype._render = function () {
  10475. var ray = this.ray;
  10476. var point = this._renderPoints[1];
  10477. var len = Math.min(ray.length, 1000000);
  10478. point.copyFrom(ray.direction);
  10479. point.scaleInPlace(len);
  10480. point.addInPlace(ray.origin);
  10481. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10482. };
  10483. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  10484. this._attachedToMesh = mesh;
  10485. var ray = this.ray;
  10486. if (!ray.direction) {
  10487. ray.direction = BABYLON.Vector3.Zero();
  10488. }
  10489. if (!ray.origin) {
  10490. ray.origin = BABYLON.Vector3.Zero();
  10491. }
  10492. if (length) {
  10493. ray.length = length;
  10494. }
  10495. if (!meshSpaceOrigin) {
  10496. meshSpaceOrigin = BABYLON.Vector3.Zero();
  10497. }
  10498. if (!meshSpaceDirection) {
  10499. // -1 so that this will work with Mesh.lookAt
  10500. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  10501. }
  10502. if (!this._meshSpaceDirection) {
  10503. this._meshSpaceDirection = meshSpaceDirection.clone();
  10504. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  10505. }
  10506. else {
  10507. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  10508. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  10509. }
  10510. if (!this._updateToMeshFunction) {
  10511. this._updateToMeshFunction = this._updateToMesh.bind(this);
  10512. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  10513. }
  10514. this._updateToMesh();
  10515. };
  10516. RayHelper.prototype.detachFromMesh = function () {
  10517. if (this._attachedToMesh) {
  10518. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  10519. this._attachedToMesh = null;
  10520. this._updateToMeshFunction = null;
  10521. }
  10522. };
  10523. RayHelper.prototype._updateToMesh = function () {
  10524. var ray = this.ray;
  10525. if (this._attachedToMesh._isDisposed) {
  10526. this.detachFromMesh();
  10527. return;
  10528. }
  10529. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  10530. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  10531. };
  10532. RayHelper.prototype.dispose = function () {
  10533. this.hide();
  10534. this.detachFromMesh();
  10535. this.ray = null;
  10536. };
  10537. return RayHelper;
  10538. }());
  10539. BABYLON.RayHelper = RayHelper;
  10540. })(BABYLON || (BABYLON = {}));
  10541. //# sourceMappingURL=babylon.rayHelper.js.map
  10542. var BABYLON;
  10543. (function (BABYLON) {
  10544. var AbstractMesh = (function (_super) {
  10545. __extends(AbstractMesh, _super);
  10546. // Constructor
  10547. function AbstractMesh(name, scene) {
  10548. var _this = _super.call(this, name, scene) || this;
  10549. _this._facetNb = 0; // facet number
  10550. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10551. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10552. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10553. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10554. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10555. _this._subDiv = {
  10556. max: 1,
  10557. X: 1,
  10558. Y: 1,
  10559. Z: 1
  10560. };
  10561. // Events
  10562. /**
  10563. * An event triggered when this mesh collides with another one
  10564. * @type {BABYLON.Observable}
  10565. */
  10566. _this.onCollideObservable = new BABYLON.Observable();
  10567. /**
  10568. * An event triggered when the collision's position changes
  10569. * @type {BABYLON.Observable}
  10570. */
  10571. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10572. /**
  10573. * An event triggered after the world matrix is updated
  10574. * @type {BABYLON.Observable}
  10575. */
  10576. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10577. // Properties
  10578. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10579. _this.position = new BABYLON.Vector3(0, 0, 0);
  10580. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10581. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10582. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10583. _this.visibility = 1.0;
  10584. _this.alphaIndex = Number.MAX_VALUE;
  10585. _this.infiniteDistance = false;
  10586. _this.isVisible = true;
  10587. _this.isPickable = true;
  10588. _this.showBoundingBox = false;
  10589. _this.showSubMeshesBoundingBox = false;
  10590. _this.isBlocker = false;
  10591. _this.renderingGroupId = 0;
  10592. _this.receiveShadows = false;
  10593. _this.renderOutline = false;
  10594. _this.outlineColor = BABYLON.Color3.Red();
  10595. _this.outlineWidth = 0.02;
  10596. _this.renderOverlay = false;
  10597. _this.overlayColor = BABYLON.Color3.Red();
  10598. _this.overlayAlpha = 0.5;
  10599. _this.hasVertexAlpha = false;
  10600. _this.useVertexColors = true;
  10601. _this.applyFog = true;
  10602. _this.computeBonesUsingShaders = true;
  10603. _this.scalingDeterminant = 1;
  10604. _this.numBoneInfluencers = 4;
  10605. _this.useOctreeForRenderingSelection = true;
  10606. _this.useOctreeForPicking = true;
  10607. _this.useOctreeForCollisions = true;
  10608. _this.layerMask = 0x0FFFFFFF;
  10609. _this.alwaysSelectAsActiveMesh = false;
  10610. // Collisions
  10611. _this._checkCollisions = false;
  10612. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10613. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10614. _this._collider = new BABYLON.Collider();
  10615. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10616. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10617. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10618. // Edges
  10619. _this.edgesWidth = 1;
  10620. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10621. // Cache
  10622. _this._localWorld = BABYLON.Matrix.Zero();
  10623. _this._worldMatrix = BABYLON.Matrix.Zero();
  10624. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10625. _this._absolutePosition = BABYLON.Vector3.Zero();
  10626. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10627. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10628. _this._isDirty = false;
  10629. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10630. _this._isDisposed = false;
  10631. _this._renderId = 0;
  10632. _this._intersectionsInProgress = new Array();
  10633. _this._isWorldMatrixFrozen = false;
  10634. _this._unIndexed = false;
  10635. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10636. if (collidedMesh === void 0) { collidedMesh = null; }
  10637. //TODO move this to the collision coordinator!
  10638. if (_this.getScene().workerCollisions)
  10639. newPosition.multiplyInPlace(_this._collider.radius);
  10640. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10641. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10642. _this.position.addInPlace(_this._diffPositionForCollisions);
  10643. }
  10644. if (collidedMesh) {
  10645. _this.onCollideObservable.notifyObservers(collidedMesh);
  10646. }
  10647. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10648. };
  10649. scene.addMesh(_this);
  10650. return _this;
  10651. }
  10652. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10653. get: function () {
  10654. return AbstractMesh._BILLBOARDMODE_NONE;
  10655. },
  10656. enumerable: true,
  10657. configurable: true
  10658. });
  10659. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10660. get: function () {
  10661. return AbstractMesh._BILLBOARDMODE_X;
  10662. },
  10663. enumerable: true,
  10664. configurable: true
  10665. });
  10666. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10667. get: function () {
  10668. return AbstractMesh._BILLBOARDMODE_Y;
  10669. },
  10670. enumerable: true,
  10671. configurable: true
  10672. });
  10673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10674. get: function () {
  10675. return AbstractMesh._BILLBOARDMODE_Z;
  10676. },
  10677. enumerable: true,
  10678. configurable: true
  10679. });
  10680. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10681. get: function () {
  10682. return AbstractMesh._BILLBOARDMODE_ALL;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10688. /**
  10689. * Read-only : the number of facets in the mesh
  10690. */
  10691. get: function () {
  10692. return this._facetNb;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10698. /**
  10699. * The number of subdivisions per axis in the partioning space
  10700. */
  10701. get: function () {
  10702. return this._partitioningSubdivisions;
  10703. },
  10704. set: function (nb) {
  10705. this._partitioningSubdivisions = nb;
  10706. },
  10707. enumerable: true,
  10708. configurable: true
  10709. });
  10710. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10711. /**
  10712. * The ratio to apply to the bouding box size to set to the partioning space.
  10713. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10714. */
  10715. get: function () {
  10716. return this._partitioningBBoxRatio;
  10717. },
  10718. set: function (ratio) {
  10719. this._partitioningBBoxRatio = ratio;
  10720. },
  10721. enumerable: true,
  10722. configurable: true
  10723. });
  10724. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10725. /**
  10726. * Read-only : is the feature facetData enabled ?
  10727. */
  10728. get: function () {
  10729. return this._facetDataEnabled;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10735. set: function (callback) {
  10736. if (this._onCollideObserver) {
  10737. this.onCollideObservable.remove(this._onCollideObserver);
  10738. }
  10739. this._onCollideObserver = this.onCollideObservable.add(callback);
  10740. },
  10741. enumerable: true,
  10742. configurable: true
  10743. });
  10744. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10745. set: function (callback) {
  10746. if (this._onCollisionPositionChangeObserver) {
  10747. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10748. }
  10749. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10755. get: function () {
  10756. return this._skeleton;
  10757. },
  10758. set: function (value) {
  10759. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10760. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10761. }
  10762. if (value && value.needInitialSkinMatrix) {
  10763. value._registerMeshWithPoseMatrix(this);
  10764. }
  10765. this._skeleton = value;
  10766. if (!this._skeleton) {
  10767. this._bonesTransformMatrices = null;
  10768. }
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. AbstractMesh.prototype.getClassName = function () {
  10774. return "AbstractMesh";
  10775. };
  10776. /**
  10777. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10778. */
  10779. AbstractMesh.prototype.toString = function (fullDetails) {
  10780. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10781. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10782. if (this._skeleton) {
  10783. ret += ", skeleton: " + this._skeleton.name;
  10784. }
  10785. if (fullDetails) {
  10786. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10787. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10788. }
  10789. return ret;
  10790. };
  10791. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10792. /**
  10793. * Getting the rotation object.
  10794. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10795. */
  10796. get: function () {
  10797. return this._rotation;
  10798. },
  10799. set: function (newRotation) {
  10800. this._rotation = newRotation;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10806. get: function () {
  10807. return this._scaling;
  10808. },
  10809. set: function (newScaling) {
  10810. this._scaling = newScaling;
  10811. if (this.physicsImpostor) {
  10812. this.physicsImpostor.forceUpdate();
  10813. }
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10819. get: function () {
  10820. return this._rotationQuaternion;
  10821. },
  10822. set: function (quaternion) {
  10823. this._rotationQuaternion = quaternion;
  10824. //reset the rotation vector.
  10825. if (quaternion && this.rotation.length()) {
  10826. this.rotation.copyFromFloats(0, 0, 0);
  10827. }
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. // Methods
  10833. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10834. this._poseMatrix.copyFrom(matrix);
  10835. };
  10836. AbstractMesh.prototype.getPoseMatrix = function () {
  10837. return this._poseMatrix;
  10838. };
  10839. AbstractMesh.prototype.disableEdgesRendering = function () {
  10840. if (this._edgesRenderer !== undefined) {
  10841. this._edgesRenderer.dispose();
  10842. this._edgesRenderer = undefined;
  10843. }
  10844. };
  10845. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10846. if (epsilon === void 0) { epsilon = 0.95; }
  10847. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10848. this.disableEdgesRendering();
  10849. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10850. };
  10851. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10852. get: function () {
  10853. return false;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. AbstractMesh.prototype.getLOD = function (camera) {
  10859. return this;
  10860. };
  10861. AbstractMesh.prototype.getTotalVertices = function () {
  10862. return 0;
  10863. };
  10864. AbstractMesh.prototype.getIndices = function () {
  10865. return null;
  10866. };
  10867. AbstractMesh.prototype.getVerticesData = function (kind) {
  10868. return null;
  10869. };
  10870. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10871. return false;
  10872. };
  10873. AbstractMesh.prototype.getBoundingInfo = function () {
  10874. if (this._masterMesh) {
  10875. return this._masterMesh.getBoundingInfo();
  10876. }
  10877. if (!this._boundingInfo) {
  10878. this._updateBoundingInfo();
  10879. }
  10880. return this._boundingInfo;
  10881. };
  10882. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10883. this._boundingInfo = boundingInfo;
  10884. };
  10885. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10886. get: function () {
  10887. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. AbstractMesh.prototype._preActivate = function () {
  10893. };
  10894. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10895. };
  10896. AbstractMesh.prototype._activate = function (renderId) {
  10897. this._renderId = renderId;
  10898. };
  10899. AbstractMesh.prototype.getWorldMatrix = function () {
  10900. if (this._masterMesh) {
  10901. return this._masterMesh.getWorldMatrix();
  10902. }
  10903. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10904. this.computeWorldMatrix();
  10905. }
  10906. return this._worldMatrix;
  10907. };
  10908. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10909. get: function () {
  10910. return this._worldMatrix;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10916. get: function () {
  10917. return this._absolutePosition;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10923. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10924. this.computeWorldMatrix(true);
  10925. this._isWorldMatrixFrozen = true;
  10926. };
  10927. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10928. this._isWorldMatrixFrozen = false;
  10929. this.computeWorldMatrix(true);
  10930. };
  10931. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10932. get: function () {
  10933. return this._isWorldMatrixFrozen;
  10934. },
  10935. enumerable: true,
  10936. configurable: true
  10937. });
  10938. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10939. axis.normalize();
  10940. if (!this.rotationQuaternion) {
  10941. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10942. this.rotation = BABYLON.Vector3.Zero();
  10943. }
  10944. var rotationQuaternion;
  10945. if (!space || space === BABYLON.Space.LOCAL) {
  10946. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10947. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10948. }
  10949. else {
  10950. if (this.parent) {
  10951. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10952. invertParentWorldMatrix.invert();
  10953. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10954. }
  10955. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10956. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10957. }
  10958. };
  10959. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10960. var displacementVector = axis.scale(distance);
  10961. if (!space || space === BABYLON.Space.LOCAL) {
  10962. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10963. this.setPositionWithLocalVector(tempV3);
  10964. }
  10965. else {
  10966. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10967. }
  10968. };
  10969. AbstractMesh.prototype.getAbsolutePosition = function () {
  10970. this.computeWorldMatrix();
  10971. return this._absolutePosition;
  10972. };
  10973. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10974. if (!absolutePosition) {
  10975. return;
  10976. }
  10977. var absolutePositionX;
  10978. var absolutePositionY;
  10979. var absolutePositionZ;
  10980. if (absolutePosition.x === undefined) {
  10981. if (arguments.length < 3) {
  10982. return;
  10983. }
  10984. absolutePositionX = arguments[0];
  10985. absolutePositionY = arguments[1];
  10986. absolutePositionZ = arguments[2];
  10987. }
  10988. else {
  10989. absolutePositionX = absolutePosition.x;
  10990. absolutePositionY = absolutePosition.y;
  10991. absolutePositionZ = absolutePosition.z;
  10992. }
  10993. if (this.parent) {
  10994. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10995. invertParentWorldMatrix.invert();
  10996. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10997. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10998. }
  10999. else {
  11000. this.position.x = absolutePositionX;
  11001. this.position.y = absolutePositionY;
  11002. this.position.z = absolutePositionZ;
  11003. }
  11004. };
  11005. // ================================== Point of View Movement =================================
  11006. /**
  11007. * Perform relative position change from the point of view of behind the front of the mesh.
  11008. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11009. * Supports definition of mesh facing forward or backward.
  11010. * @param {number} amountRight
  11011. * @param {number} amountUp
  11012. * @param {number} amountForward
  11013. */
  11014. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11015. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11016. };
  11017. /**
  11018. * Calculate relative position change from the point of view of behind the front of the mesh.
  11019. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11020. * Supports definition of mesh facing forward or backward.
  11021. * @param {number} amountRight
  11022. * @param {number} amountUp
  11023. * @param {number} amountForward
  11024. */
  11025. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11026. var rotMatrix = new BABYLON.Matrix();
  11027. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11028. rotQuaternion.toRotationMatrix(rotMatrix);
  11029. var translationDelta = BABYLON.Vector3.Zero();
  11030. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11032. return translationDelta;
  11033. };
  11034. // ================================== Point of View Rotation =================================
  11035. /**
  11036. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11037. * Supports definition of mesh facing forward or backward.
  11038. * @param {number} flipBack
  11039. * @param {number} twirlClockwise
  11040. * @param {number} tiltRight
  11041. */
  11042. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11043. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11044. };
  11045. /**
  11046. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11047. * Supports definition of mesh facing forward or backward.
  11048. * @param {number} flipBack
  11049. * @param {number} twirlClockwise
  11050. * @param {number} tiltRight
  11051. */
  11052. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11053. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11054. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11055. };
  11056. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11057. this._pivotMatrix = matrix;
  11058. this._cache.pivotMatrixUpdated = true;
  11059. };
  11060. AbstractMesh.prototype.getPivotMatrix = function () {
  11061. return this._pivotMatrix;
  11062. };
  11063. AbstractMesh.prototype._isSynchronized = function () {
  11064. if (this._isDirty) {
  11065. return false;
  11066. }
  11067. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11068. return false;
  11069. if (this._cache.pivotMatrixUpdated) {
  11070. return false;
  11071. }
  11072. if (this.infiniteDistance) {
  11073. return false;
  11074. }
  11075. if (!this._cache.position.equals(this.position))
  11076. return false;
  11077. if (this.rotationQuaternion) {
  11078. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11079. return false;
  11080. }
  11081. if (!this._cache.rotation.equals(this.rotation))
  11082. return false;
  11083. if (!this._cache.scaling.equals(this.scaling))
  11084. return false;
  11085. return true;
  11086. };
  11087. AbstractMesh.prototype._initCache = function () {
  11088. _super.prototype._initCache.call(this);
  11089. this._cache.localMatrixUpdated = false;
  11090. this._cache.position = BABYLON.Vector3.Zero();
  11091. this._cache.scaling = BABYLON.Vector3.Zero();
  11092. this._cache.rotation = BABYLON.Vector3.Zero();
  11093. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11094. this._cache.billboardMode = -1;
  11095. };
  11096. AbstractMesh.prototype.markAsDirty = function (property) {
  11097. if (property === "rotation") {
  11098. this.rotationQuaternion = null;
  11099. }
  11100. this._currentRenderId = Number.MAX_VALUE;
  11101. this._isDirty = true;
  11102. };
  11103. AbstractMesh.prototype._updateBoundingInfo = function () {
  11104. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11105. this._boundingInfo.update(this.worldMatrixFromCache);
  11106. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11107. };
  11108. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11109. if (!this.subMeshes) {
  11110. return;
  11111. }
  11112. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11113. var subMesh = this.subMeshes[subIndex];
  11114. if (!subMesh.IsGlobal) {
  11115. subMesh.updateBoundingInfo(matrix);
  11116. }
  11117. }
  11118. };
  11119. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11120. if (this._isWorldMatrixFrozen) {
  11121. return this._worldMatrix;
  11122. }
  11123. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  11124. this._currentRenderId = this.getScene().getRenderId();
  11125. return this._worldMatrix;
  11126. }
  11127. this._cache.position.copyFrom(this.position);
  11128. this._cache.scaling.copyFrom(this.scaling);
  11129. this._cache.pivotMatrixUpdated = false;
  11130. this._cache.billboardMode = this.billboardMode;
  11131. this._currentRenderId = this.getScene().getRenderId();
  11132. this._isDirty = false;
  11133. // Scaling
  11134. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11135. // Rotation
  11136. //rotate, if quaternion is set and rotation was used
  11137. if (this.rotationQuaternion) {
  11138. var len = this.rotation.length();
  11139. if (len) {
  11140. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11141. this.rotation.copyFromFloats(0, 0, 0);
  11142. }
  11143. }
  11144. if (this.rotationQuaternion) {
  11145. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11146. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11147. }
  11148. else {
  11149. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11150. this._cache.rotation.copyFrom(this.rotation);
  11151. }
  11152. // Translation
  11153. if (this.infiniteDistance && !this.parent) {
  11154. var camera = this.getScene().activeCamera;
  11155. if (camera) {
  11156. var cameraWorldMatrix = camera.getWorldMatrix();
  11157. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11158. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11159. }
  11160. }
  11161. else {
  11162. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11163. }
  11164. // Composing transformations
  11165. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11166. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11167. // Billboarding
  11168. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11169. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  11170. var localPosition = BABYLON.Tmp.Vector3[0];
  11171. if (this.parent && this.parent.getWorldMatrix) {
  11172. this._markSyncedWithParent();
  11173. var parentMatrix;
  11174. if (this._meshToBoneReferal) {
  11175. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11176. parentMatrix = BABYLON.Tmp.Matrix[6];
  11177. }
  11178. else {
  11179. parentMatrix = this.parent.getWorldMatrix();
  11180. }
  11181. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  11182. localPosition = BABYLON.Tmp.Vector3[1];
  11183. }
  11184. var zero = this.getScene().activeCamera.globalPosition.clone();
  11185. if (this.parent && this.parent.position) {
  11186. localPosition.addInPlace(this.parent.position);
  11187. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  11188. }
  11189. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11190. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  11191. zero.x = localPosition.x + BABYLON.Epsilon;
  11192. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  11193. zero.y = localPosition.y + BABYLON.Epsilon;
  11194. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  11195. zero.z = localPosition.z + BABYLON.Epsilon;
  11196. }
  11197. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  11198. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  11199. BABYLON.Tmp.Matrix[3].invert();
  11200. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  11201. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  11202. }
  11203. // Local world
  11204. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11205. // Parent
  11206. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  11207. this._markSyncedWithParent();
  11208. if (this._meshToBoneReferal) {
  11209. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11210. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11211. }
  11212. else {
  11213. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11214. }
  11215. }
  11216. else {
  11217. this._worldMatrix.copyFrom(this._localWorld);
  11218. }
  11219. // Bounding info
  11220. this._updateBoundingInfo();
  11221. // Absolute position
  11222. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11223. // Callbacks
  11224. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11225. if (!this._poseMatrix) {
  11226. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11227. }
  11228. return this._worldMatrix;
  11229. };
  11230. /**
  11231. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  11232. * @param func: callback function to add
  11233. */
  11234. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11235. this.onAfterWorldMatrixUpdateObservable.add(func);
  11236. };
  11237. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11238. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11239. };
  11240. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11241. this.computeWorldMatrix();
  11242. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11243. };
  11244. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11245. this.computeWorldMatrix();
  11246. var invLocalWorldMatrix = this._localWorld.clone();
  11247. invLocalWorldMatrix.invert();
  11248. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11249. };
  11250. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11251. this.computeWorldMatrix(true);
  11252. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11253. };
  11254. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11255. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11256. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11257. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11258. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11259. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11260. /// <returns>Mesh oriented towards targetMesh</returns>
  11261. if (yawCor === void 0) { yawCor = 0; }
  11262. if (pitchCor === void 0) { pitchCor = 0; }
  11263. if (rollCor === void 0) { rollCor = 0; }
  11264. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11265. var dv = AbstractMesh._lookAtVectorCache;
  11266. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11267. targetPoint.subtractToRef(pos, dv);
  11268. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11269. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11270. var pitch = Math.atan2(dv.y, len);
  11271. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11272. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11273. };
  11274. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11275. this._meshToBoneReferal = affectedMesh;
  11276. this.parent = bone;
  11277. if (bone.getWorldMatrix().determinant() < 0) {
  11278. this.scalingDeterminant *= -1;
  11279. }
  11280. };
  11281. AbstractMesh.prototype.detachFromBone = function () {
  11282. if (this.parent.getWorldMatrix().determinant() < 0) {
  11283. this.scalingDeterminant *= -1;
  11284. }
  11285. this._meshToBoneReferal = null;
  11286. this.parent = null;
  11287. };
  11288. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11289. return this._boundingInfo.isInFrustum(frustumPlanes);
  11290. };
  11291. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11292. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11293. ;
  11294. };
  11295. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11296. if (!this._boundingInfo || !mesh._boundingInfo) {
  11297. return false;
  11298. }
  11299. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11300. };
  11301. AbstractMesh.prototype.intersectsPoint = function (point) {
  11302. if (!this._boundingInfo) {
  11303. return false;
  11304. }
  11305. return this._boundingInfo.intersectsPoint(point);
  11306. };
  11307. // Physics
  11308. /**
  11309. * @Deprecated. Use new PhysicsImpostor instead.
  11310. * */
  11311. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11312. //legacy support
  11313. if (impostor.impostor) {
  11314. options = impostor;
  11315. impostor = impostor.impostor;
  11316. }
  11317. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11318. return this.physicsImpostor.physicsBody;
  11319. };
  11320. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11321. return this.physicsImpostor;
  11322. };
  11323. /**
  11324. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11325. */
  11326. AbstractMesh.prototype.getPhysicsMass = function () {
  11327. return this.physicsImpostor.getParam("mass");
  11328. };
  11329. /**
  11330. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11331. */
  11332. AbstractMesh.prototype.getPhysicsFriction = function () {
  11333. return this.physicsImpostor.getParam("friction");
  11334. };
  11335. /**
  11336. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11337. */
  11338. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11339. return this.physicsImpostor.getParam("restitution");
  11340. };
  11341. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11342. if (!camera) {
  11343. camera = this.getScene().activeCamera;
  11344. }
  11345. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11346. };
  11347. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11348. if (!camera) {
  11349. camera = this.getScene().activeCamera;
  11350. }
  11351. return this.absolutePosition.subtract(camera.position).length();
  11352. };
  11353. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11354. if (!this.physicsImpostor) {
  11355. return;
  11356. }
  11357. this.physicsImpostor.applyImpulse(force, contactPoint);
  11358. };
  11359. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11360. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11361. return;
  11362. }
  11363. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11364. mainPivot: pivot1,
  11365. connectedPivot: pivot2,
  11366. nativeParams: options
  11367. });
  11368. };
  11369. /**
  11370. * @Deprecated
  11371. */
  11372. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11373. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11374. this.updatePhysicsBody();
  11375. };
  11376. /**
  11377. * @Deprecated
  11378. * Calling this function is not needed anymore.
  11379. * The physics engine takes care of transofmration automatically.
  11380. */
  11381. AbstractMesh.prototype.updatePhysicsBody = function () {
  11382. //Unneeded
  11383. };
  11384. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11385. // Collisions
  11386. get: function () {
  11387. return this._checkCollisions;
  11388. },
  11389. set: function (collisionEnabled) {
  11390. this._checkCollisions = collisionEnabled;
  11391. if (this.getScene().workerCollisions) {
  11392. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11393. }
  11394. },
  11395. enumerable: true,
  11396. configurable: true
  11397. });
  11398. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11399. var globalPosition = this.getAbsolutePosition();
  11400. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11401. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11402. this._collider.radius = this.ellipsoid;
  11403. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11404. };
  11405. // Submeshes octree
  11406. /**
  11407. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11408. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11409. */
  11410. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11411. if (maxCapacity === void 0) { maxCapacity = 64; }
  11412. if (maxDepth === void 0) { maxDepth = 2; }
  11413. if (!this._submeshesOctree) {
  11414. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11415. }
  11416. this.computeWorldMatrix(true);
  11417. // Update octree
  11418. var bbox = this.getBoundingInfo().boundingBox;
  11419. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11420. return this._submeshesOctree;
  11421. };
  11422. // Collisions
  11423. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11424. this._generatePointsArray();
  11425. // Transformation
  11426. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11427. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11428. subMesh._lastColliderWorldVertices = [];
  11429. subMesh._trianglePlanes = [];
  11430. var start = subMesh.verticesStart;
  11431. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11432. for (var i = start; i < end; i++) {
  11433. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11434. }
  11435. }
  11436. // Collide
  11437. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11438. if (collider.collisionFound) {
  11439. collider.collidedMesh = this;
  11440. }
  11441. };
  11442. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11443. var subMeshes;
  11444. var len;
  11445. // Octrees
  11446. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11447. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11448. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11449. len = intersections.length;
  11450. subMeshes = intersections.data;
  11451. }
  11452. else {
  11453. subMeshes = this.subMeshes;
  11454. len = subMeshes.length;
  11455. }
  11456. for (var index = 0; index < len; index++) {
  11457. var subMesh = subMeshes[index];
  11458. // Bounding test
  11459. if (len > 1 && !subMesh._checkCollision(collider))
  11460. continue;
  11461. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11462. }
  11463. };
  11464. AbstractMesh.prototype._checkCollision = function (collider) {
  11465. // Bounding box test
  11466. if (!this._boundingInfo._checkCollision(collider))
  11467. return;
  11468. // Transformation matrix
  11469. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11470. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11471. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11472. };
  11473. // Picking
  11474. AbstractMesh.prototype._generatePointsArray = function () {
  11475. return false;
  11476. };
  11477. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11478. var pickingInfo = new BABYLON.PickingInfo();
  11479. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11480. return pickingInfo;
  11481. }
  11482. if (!this._generatePointsArray()) {
  11483. return pickingInfo;
  11484. }
  11485. var intersectInfo = null;
  11486. // Octrees
  11487. var subMeshes;
  11488. var len;
  11489. if (this._submeshesOctree && this.useOctreeForPicking) {
  11490. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11491. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11492. len = intersections.length;
  11493. subMeshes = intersections.data;
  11494. }
  11495. else {
  11496. subMeshes = this.subMeshes;
  11497. len = subMeshes.length;
  11498. }
  11499. for (var index = 0; index < len; index++) {
  11500. var subMesh = subMeshes[index];
  11501. // Bounding test
  11502. if (len > 1 && !subMesh.canIntersects(ray))
  11503. continue;
  11504. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11505. if (currentIntersectInfo) {
  11506. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11507. intersectInfo = currentIntersectInfo;
  11508. intersectInfo.subMeshId = index;
  11509. if (fastCheck) {
  11510. break;
  11511. }
  11512. }
  11513. }
  11514. }
  11515. if (intersectInfo) {
  11516. // Get picked point
  11517. var world = this.getWorldMatrix();
  11518. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11519. var direction = ray.direction.clone();
  11520. direction = direction.scale(intersectInfo.distance);
  11521. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11522. var pickedPoint = worldOrigin.add(worldDirection);
  11523. // Return result
  11524. pickingInfo.hit = true;
  11525. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11526. pickingInfo.pickedPoint = pickedPoint;
  11527. pickingInfo.pickedMesh = this;
  11528. pickingInfo.bu = intersectInfo.bu;
  11529. pickingInfo.bv = intersectInfo.bv;
  11530. pickingInfo.faceId = intersectInfo.faceId;
  11531. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11532. return pickingInfo;
  11533. }
  11534. return pickingInfo;
  11535. };
  11536. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11537. return null;
  11538. };
  11539. AbstractMesh.prototype.releaseSubMeshes = function () {
  11540. if (this.subMeshes) {
  11541. while (this.subMeshes.length) {
  11542. this.subMeshes[0].dispose();
  11543. }
  11544. }
  11545. else {
  11546. this.subMeshes = new Array();
  11547. }
  11548. };
  11549. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11550. var _this = this;
  11551. var index;
  11552. // Action manager
  11553. if (this.actionManager) {
  11554. this.actionManager.dispose();
  11555. this.actionManager = null;
  11556. }
  11557. // Skeleton
  11558. this.skeleton = null;
  11559. // Animations
  11560. this.getScene().stopAnimation(this);
  11561. // Physics
  11562. if (this.physicsImpostor) {
  11563. this.physicsImpostor.dispose();
  11564. }
  11565. // Intersections in progress
  11566. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11567. var other = this._intersectionsInProgress[index];
  11568. var pos = other._intersectionsInProgress.indexOf(this);
  11569. other._intersectionsInProgress.splice(pos, 1);
  11570. }
  11571. this._intersectionsInProgress = [];
  11572. // Lights
  11573. var lights = this.getScene().lights;
  11574. lights.forEach(function (light) {
  11575. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11576. if (meshIndex !== -1) {
  11577. light.includedOnlyMeshes.splice(meshIndex, 1);
  11578. }
  11579. meshIndex = light.excludedMeshes.indexOf(_this);
  11580. if (meshIndex !== -1) {
  11581. light.excludedMeshes.splice(meshIndex, 1);
  11582. }
  11583. // Shadow generators
  11584. var generator = light.getShadowGenerator();
  11585. if (generator) {
  11586. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11587. if (meshIndex !== -1) {
  11588. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11589. }
  11590. }
  11591. });
  11592. // Edges
  11593. if (this._edgesRenderer) {
  11594. this._edgesRenderer.dispose();
  11595. this._edgesRenderer = null;
  11596. }
  11597. // SubMeshes
  11598. if (this.getClassName() !== "InstancedMesh") {
  11599. this.releaseSubMeshes();
  11600. }
  11601. // Engine
  11602. this.getScene().getEngine().wipeCaches();
  11603. // Remove from scene
  11604. this.getScene().removeMesh(this);
  11605. if (!doNotRecurse) {
  11606. // Particles
  11607. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11608. if (this.getScene().particleSystems[index].emitter === this) {
  11609. this.getScene().particleSystems[index].dispose();
  11610. index--;
  11611. }
  11612. }
  11613. // Children
  11614. var objects = this.getDescendants(true);
  11615. for (index = 0; index < objects.length; index++) {
  11616. objects[index].dispose();
  11617. }
  11618. }
  11619. else {
  11620. var childMeshes = this.getChildMeshes(true);
  11621. for (index = 0; index < childMeshes.length; index++) {
  11622. var child = childMeshes[index];
  11623. child.parent = null;
  11624. child.computeWorldMatrix(true);
  11625. }
  11626. }
  11627. // facet data
  11628. if (this._facetDataEnabled) {
  11629. this.disableFacetData();
  11630. }
  11631. this.onAfterWorldMatrixUpdateObservable.clear();
  11632. this.onCollideObservable.clear();
  11633. this.onCollisionPositionChangeObservable.clear();
  11634. this._isDisposed = true;
  11635. _super.prototype.dispose.call(this);
  11636. };
  11637. AbstractMesh.prototype.getDirection = function (localAxis) {
  11638. var result = BABYLON.Vector3.Zero();
  11639. this.getDirectionToRef(localAxis, result);
  11640. return result;
  11641. };
  11642. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11643. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11644. };
  11645. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11647. if (this.getScene().getRenderId() == 0) {
  11648. this.computeWorldMatrix(true);
  11649. }
  11650. var wm = this.getWorldMatrix();
  11651. if (space == BABYLON.Space.WORLD) {
  11652. var tmat = BABYLON.Tmp.Matrix[0];
  11653. wm.invertToRef(tmat);
  11654. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11655. }
  11656. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11657. this._pivotMatrix.m[12] = -point.x;
  11658. this._pivotMatrix.m[13] = -point.y;
  11659. this._pivotMatrix.m[14] = -point.z;
  11660. this._cache.pivotMatrixUpdated = true;
  11661. };
  11662. AbstractMesh.prototype.getPivotPoint = function () {
  11663. var point = BABYLON.Vector3.Zero();
  11664. this.getPivotPointToRef(point);
  11665. return point;
  11666. };
  11667. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11668. result.x = -this._pivotMatrix.m[12];
  11669. result.y = -this._pivotMatrix.m[13];
  11670. result.z = -this._pivotMatrix.m[14];
  11671. };
  11672. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11673. var point = BABYLON.Vector3.Zero();
  11674. this.getAbsolutePivotPointToRef(point);
  11675. return point;
  11676. };
  11677. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  11678. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11679. var child = this;
  11680. var parent = mesh;
  11681. if (mesh == null) {
  11682. if (child.parent && keepWorldPositionRotation) {
  11683. var rotation = BABYLON.Tmp.Quaternion[0];
  11684. var position = BABYLON.Tmp.Vector3[0];
  11685. var scale = BABYLON.Tmp.Vector3[1];
  11686. child.getWorldMatrix().decompose(scale, rotation, position);
  11687. if (child.rotationQuaternion) {
  11688. child.rotationQuaternion.copyFrom(rotation);
  11689. }
  11690. else {
  11691. rotation.toEulerAnglesToRef(child.rotation);
  11692. }
  11693. child.position.x = position.x;
  11694. child.position.y = position.y;
  11695. child.position.z = position.z;
  11696. }
  11697. }
  11698. else {
  11699. if (keepWorldPositionRotation) {
  11700. var rotation = BABYLON.Tmp.Quaternion[0];
  11701. var position = BABYLON.Tmp.Vector3[0];
  11702. var scale = BABYLON.Tmp.Vector3[1];
  11703. var m1 = BABYLON.Tmp.Matrix[0];
  11704. var m2 = BABYLON.Tmp.Matrix[1];
  11705. parent.getWorldMatrix().decompose(scale, rotation, position);
  11706. rotation.toRotationMatrix(m1);
  11707. m2.setTranslation(position);
  11708. m2.multiplyToRef(m1, m1);
  11709. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  11710. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11711. m.decompose(scale, rotation, position);
  11712. if (child.rotationQuaternion) {
  11713. child.rotationQuaternion.copyFrom(rotation);
  11714. }
  11715. else {
  11716. rotation.toEulerAnglesToRef(child.rotation);
  11717. }
  11718. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  11719. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11720. m.decompose(scale, rotation, position);
  11721. child.position.x = position.x;
  11722. child.position.y = position.y;
  11723. child.position.z = position.z;
  11724. }
  11725. }
  11726. child.parent = parent;
  11727. };
  11728. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  11729. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11730. mesh.setParent(this, keepWorldPositionRotation);
  11731. };
  11732. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  11733. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11734. mesh.setParent(null, keepWorldPositionRotation);
  11735. };
  11736. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11737. result.x = this._pivotMatrix.m[12];
  11738. result.y = this._pivotMatrix.m[13];
  11739. result.z = this._pivotMatrix.m[14];
  11740. this.getPivotPointToRef(result);
  11741. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11742. };
  11743. // Facet data
  11744. /**
  11745. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning
  11746. */
  11747. AbstractMesh.prototype._initFacetData = function () {
  11748. if (!this._facetNormals) {
  11749. this._facetNormals = new Array();
  11750. }
  11751. if (!this._facetPositions) {
  11752. this._facetPositions = new Array();
  11753. }
  11754. if (!this._facetPartitioning) {
  11755. this._facetPartitioning = new Array();
  11756. }
  11757. this._facetNb = this.getIndices().length / 3;
  11758. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  11759. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  11760. for (var f = 0; f < this._facetNb; f++) {
  11761. this._facetNormals[f] = BABYLON.Vector3.Zero();
  11762. this._facetPositions[f] = BABYLON.Vector3.Zero();
  11763. }
  11764. this._facetDataEnabled = true;
  11765. return this;
  11766. };
  11767. /**
  11768. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  11769. * This method can be called within the render loop.
  11770. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  11771. */
  11772. AbstractMesh.prototype.updateFacetData = function () {
  11773. if (!this._facetDataEnabled) {
  11774. this._initFacetData();
  11775. }
  11776. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11777. var indices = this.getIndices();
  11778. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11779. var bInfo = this.getBoundingInfo();
  11780. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  11781. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  11782. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  11783. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  11784. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  11785. this._subDiv.max = this._partitioningSubdivisions;
  11786. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  11787. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  11788. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  11789. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  11790. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  11791. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  11792. // set the parameters for ComputeNormals()
  11793. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  11794. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  11795. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  11796. this._facetParameters.bInfo = bInfo;
  11797. this._facetParameters.bbSize = this._bbSize;
  11798. this._facetParameters.subDiv = this._subDiv;
  11799. this._facetParameters.ratio = this.partitioningBBoxRatio;
  11800. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  11801. return this;
  11802. };
  11803. /**
  11804. * Returns the facetLocalNormals array.
  11805. * The normals are expressed in the mesh local space.
  11806. */
  11807. AbstractMesh.prototype.getFacetLocalNormals = function () {
  11808. if (!this._facetNormals) {
  11809. this.updateFacetData();
  11810. }
  11811. return this._facetNormals;
  11812. };
  11813. /**
  11814. * Returns the facetLocalPositions array.
  11815. * The facet positions are expressed in the mesh local space.
  11816. */
  11817. AbstractMesh.prototype.getFacetLocalPositions = function () {
  11818. if (!this._facetPositions) {
  11819. this.updateFacetData();
  11820. }
  11821. return this._facetPositions;
  11822. };
  11823. /**
  11824. * Returns the facetLocalPartioning array
  11825. */
  11826. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  11827. if (!this._facetPartitioning) {
  11828. this.updateFacetData();
  11829. }
  11830. return this._facetPartitioning;
  11831. };
  11832. /**
  11833. * Returns the i-th facet position in the world system.
  11834. * This method allocates a new Vector3 per call.
  11835. */
  11836. AbstractMesh.prototype.getFacetPosition = function (i) {
  11837. var pos = BABYLON.Vector3.Zero();
  11838. this.getFacetPositionToRef(i, pos);
  11839. return pos;
  11840. };
  11841. /**
  11842. * Sets the reference Vector3 with the i-th facet position in the world system.
  11843. * Returns the mesh.
  11844. */
  11845. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  11846. var localPos = (this.getFacetLocalPositions())[i];
  11847. var world = this.getWorldMatrix();
  11848. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  11849. return this;
  11850. };
  11851. /**
  11852. * Returns the i-th facet normal in the world system.
  11853. * This method allocates a new Vector3 per call.
  11854. */
  11855. AbstractMesh.prototype.getFacetNormal = function (i) {
  11856. var norm = BABYLON.Vector3.Zero();
  11857. this.getFacetNormalToRef(i, norm);
  11858. return norm;
  11859. };
  11860. /**
  11861. * Sets the reference Vector3 with the i-th facet normal in the world system.
  11862. * Returns the mesh.
  11863. */
  11864. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  11865. var localNorm = (this.getFacetLocalNormals())[i];
  11866. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  11867. return this;
  11868. };
  11869. /**
  11870. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  11871. */
  11872. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  11873. var bInfo = this.getBoundingInfo();
  11874. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  11875. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  11876. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  11877. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  11878. return null;
  11879. }
  11880. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  11881. };
  11882. /**
  11883. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  11884. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  11885. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  11886. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  11887. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  11888. */
  11889. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  11890. if (checkFace === void 0) { checkFace = false; }
  11891. if (facing === void 0) { facing = true; }
  11892. var world = this.getWorldMatrix();
  11893. var invMat = BABYLON.Tmp.Matrix[5];
  11894. world.invertToRef(invMat);
  11895. var invVect = BABYLON.Tmp.Vector3[8];
  11896. var closest = null;
  11897. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  11898. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  11899. if (projected) {
  11900. // tranform the local computed projected vector to world coordinates
  11901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  11902. }
  11903. return closest;
  11904. };
  11905. /**
  11906. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  11907. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  11908. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  11909. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  11910. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  11911. */
  11912. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  11913. if (checkFace === void 0) { checkFace = false; }
  11914. if (facing === void 0) { facing = true; }
  11915. var closest = null;
  11916. var tmpx = 0.0;
  11917. var tmpy = 0.0;
  11918. var tmpz = 0.0;
  11919. var d = 0.0; // tmp dot facet normal * facet position
  11920. var t0 = 0.0;
  11921. var projx = 0.0;
  11922. var projy = 0.0;
  11923. var projz = 0.0;
  11924. // Get all the facets in the same partitioning block than (x, y, z)
  11925. var facetPositions = this.getFacetLocalPositions();
  11926. var facetNormals = this.getFacetLocalNormals();
  11927. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  11928. if (!facetsInBlock) {
  11929. return null;
  11930. }
  11931. // Get the closest facet to (x, y, z)
  11932. var shortest = Number.MAX_VALUE; // init distance vars
  11933. var tmpDistance = shortest;
  11934. var fib; // current facet in the block
  11935. var norm; // current facet normal
  11936. var p0; // current facet barycenter position
  11937. // loop on all the facets in the current partitioning block
  11938. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  11939. fib = facetsInBlock[idx];
  11940. norm = facetNormals[fib];
  11941. p0 = facetPositions[fib];
  11942. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  11943. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  11944. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  11945. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  11946. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  11947. projx = x + norm.x * t0;
  11948. projy = y + norm.y * t0;
  11949. projz = z + norm.z * t0;
  11950. tmpx = projx - x;
  11951. tmpy = projy - y;
  11952. tmpz = projz - z;
  11953. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  11954. if (tmpDistance < shortest) {
  11955. shortest = tmpDistance;
  11956. closest = fib;
  11957. if (projected) {
  11958. projected.x = projx;
  11959. projected.y = projy;
  11960. projected.z = projz;
  11961. }
  11962. }
  11963. }
  11964. }
  11965. return closest;
  11966. };
  11967. /**
  11968. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  11969. */
  11970. AbstractMesh.prototype.getFacetDataParameters = function () {
  11971. return this._facetParameters;
  11972. };
  11973. /**
  11974. * Disables the feature FacetData and frees the related memory.
  11975. * Returns the mesh.
  11976. */
  11977. AbstractMesh.prototype.disableFacetData = function () {
  11978. if (this._facetDataEnabled) {
  11979. this._facetDataEnabled = false;
  11980. this._facetPositions = null;
  11981. this._facetNormals = null;
  11982. this._facetPartitioning = null;
  11983. this._facetParameters = null;
  11984. }
  11985. return this;
  11986. };
  11987. return AbstractMesh;
  11988. }(BABYLON.Node));
  11989. // Statics
  11990. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11991. AbstractMesh._BILLBOARDMODE_X = 1;
  11992. AbstractMesh._BILLBOARDMODE_Y = 2;
  11993. AbstractMesh._BILLBOARDMODE_Z = 4;
  11994. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11995. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11996. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11997. BABYLON.AbstractMesh = AbstractMesh;
  11998. })(BABYLON || (BABYLON = {}));
  11999. //# sourceMappingURL=babylon.abstractMesh.js.map
  12000. var BABYLON;
  12001. (function (BABYLON) {
  12002. var Light = (function (_super) {
  12003. __extends(Light, _super);
  12004. function Light(name, scene) {
  12005. var _this = _super.call(this, name, scene) || this;
  12006. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12007. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12008. _this.intensity = 1.0;
  12009. _this.range = Number.MAX_VALUE;
  12010. _this.includeOnlyWithLayerMask = 0;
  12011. _this.includedOnlyMeshes = new Array();
  12012. _this.excludedMeshes = new Array();
  12013. _this.excludeWithLayerMask = 0;
  12014. _this.lightmapMode = 0;
  12015. // PBR Properties.
  12016. _this.radius = 0.00001;
  12017. _this._excludedMeshesIds = new Array();
  12018. _this._includedOnlyMeshesIds = new Array();
  12019. scene.addLight(_this);
  12020. return _this;
  12021. }
  12022. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12023. /**
  12024. * If every light affecting the material is in this lightmapMode,
  12025. * material.lightmapTexture adds or multiplies
  12026. * (depends on material.useLightmapAsShadowmap)
  12027. * after every other light calculations.
  12028. */
  12029. get: function () {
  12030. return Light._LIGHTMAP_DEFAULT;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12036. /**
  12037. * material.lightmapTexture as only diffuse lighting from this light
  12038. * adds pnly specular lighting from this light
  12039. * adds dynamic shadows
  12040. */
  12041. get: function () {
  12042. return Light._LIGHTMAP_SPECULAR;
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12048. /**
  12049. * material.lightmapTexture as only lighting
  12050. * no light calculation from this light
  12051. * only adds dynamic shadows from this light
  12052. */
  12053. get: function () {
  12054. return Light._LIGHTMAP_SHADOWSONLY;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Light.prototype.getClassName = function () {
  12060. return "Light";
  12061. };
  12062. /**
  12063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12064. */
  12065. Light.prototype.toString = function (fullDetails) {
  12066. var ret = "Name: " + this.name;
  12067. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12068. if (this.animations) {
  12069. for (var i = 0; i < this.animations.length; i++) {
  12070. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12071. }
  12072. }
  12073. if (fullDetails) {
  12074. }
  12075. return ret;
  12076. };
  12077. Light.prototype.getShadowGenerator = function () {
  12078. return this._shadowGenerator;
  12079. };
  12080. Light.prototype.getAbsolutePosition = function () {
  12081. return BABYLON.Vector3.Zero();
  12082. };
  12083. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  12084. };
  12085. Light.prototype._getWorldMatrix = function () {
  12086. return BABYLON.Matrix.Identity();
  12087. };
  12088. Light.prototype.canAffectMesh = function (mesh) {
  12089. if (!mesh) {
  12090. return true;
  12091. }
  12092. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12093. return false;
  12094. }
  12095. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12096. return false;
  12097. }
  12098. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12099. return false;
  12100. }
  12101. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12102. return false;
  12103. }
  12104. return true;
  12105. };
  12106. Light.prototype.getWorldMatrix = function () {
  12107. this._currentRenderId = this.getScene().getRenderId();
  12108. var worldMatrix = this._getWorldMatrix();
  12109. if (this.parent && this.parent.getWorldMatrix) {
  12110. if (!this._parentedWorldMatrix) {
  12111. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12112. }
  12113. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12114. this._markSyncedWithParent();
  12115. return this._parentedWorldMatrix;
  12116. }
  12117. return worldMatrix;
  12118. };
  12119. Light.prototype.dispose = function () {
  12120. if (this._shadowGenerator) {
  12121. this._shadowGenerator.dispose();
  12122. this._shadowGenerator = null;
  12123. }
  12124. // Animations
  12125. this.getScene().stopAnimation(this);
  12126. // Remove from scene
  12127. this.getScene().removeLight(this);
  12128. _super.prototype.dispose.call(this);
  12129. };
  12130. Light.prototype.getTypeID = function () {
  12131. return 0;
  12132. };
  12133. Light.prototype.clone = function (name) {
  12134. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12135. };
  12136. Light.prototype.serialize = function () {
  12137. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12138. // Type
  12139. serializationObject.type = this.getTypeID();
  12140. // Parent
  12141. if (this.parent) {
  12142. serializationObject.parentId = this.parent.id;
  12143. }
  12144. // Inclusion / exclusions
  12145. if (this.excludedMeshes.length > 0) {
  12146. serializationObject.excludedMeshesIds = [];
  12147. this.excludedMeshes.forEach(function (mesh) {
  12148. serializationObject.excludedMeshesIds.push(mesh.id);
  12149. });
  12150. }
  12151. if (this.includedOnlyMeshes.length > 0) {
  12152. serializationObject.includedOnlyMeshesIds = [];
  12153. this.includedOnlyMeshes.forEach(function (mesh) {
  12154. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12155. });
  12156. }
  12157. // Animations
  12158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12159. serializationObject.ranges = this.serializeAnimationRanges();
  12160. return serializationObject;
  12161. };
  12162. Light.GetConstructorFromName = function (type, name, scene) {
  12163. switch (type) {
  12164. case 0:
  12165. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12166. case 1:
  12167. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12168. case 2:
  12169. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12170. case 3:
  12171. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12172. }
  12173. };
  12174. Light.Parse = function (parsedLight, scene) {
  12175. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12176. // Inclusion / exclusions
  12177. if (parsedLight.excludedMeshesIds) {
  12178. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12179. }
  12180. if (parsedLight.includedOnlyMeshesIds) {
  12181. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12182. }
  12183. // Parent
  12184. if (parsedLight.parentId) {
  12185. light._waitingParentId = parsedLight.parentId;
  12186. }
  12187. // Animations
  12188. if (parsedLight.animations) {
  12189. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12190. var parsedAnimation = parsedLight.animations[animationIndex];
  12191. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12192. }
  12193. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12194. }
  12195. if (parsedLight.autoAnimate) {
  12196. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12197. }
  12198. return light;
  12199. };
  12200. return Light;
  12201. }(BABYLON.Node));
  12202. //lightmapMode Consts
  12203. Light._LIGHTMAP_DEFAULT = 0;
  12204. Light._LIGHTMAP_SPECULAR = 1;
  12205. Light._LIGHTMAP_SHADOWSONLY = 2;
  12206. __decorate([
  12207. BABYLON.serializeAsColor3()
  12208. ], Light.prototype, "diffuse", void 0);
  12209. __decorate([
  12210. BABYLON.serializeAsColor3()
  12211. ], Light.prototype, "specular", void 0);
  12212. __decorate([
  12213. BABYLON.serialize()
  12214. ], Light.prototype, "intensity", void 0);
  12215. __decorate([
  12216. BABYLON.serialize()
  12217. ], Light.prototype, "range", void 0);
  12218. __decorate([
  12219. BABYLON.serialize()
  12220. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  12221. __decorate([
  12222. BABYLON.serialize()
  12223. ], Light.prototype, "excludeWithLayerMask", void 0);
  12224. __decorate([
  12225. BABYLON.serialize()
  12226. ], Light.prototype, "lightmapMode", void 0);
  12227. __decorate([
  12228. BABYLON.serialize()
  12229. ], Light.prototype, "radius", void 0);
  12230. BABYLON.Light = Light;
  12231. })(BABYLON || (BABYLON = {}));
  12232. //# sourceMappingURL=babylon.light.js.map
  12233. var BABYLON;
  12234. (function (BABYLON) {
  12235. var PointLight = (function (_super) {
  12236. __extends(PointLight, _super);
  12237. function PointLight(name, position, scene) {
  12238. var _this = _super.call(this, name, scene) || this;
  12239. _this.position = position;
  12240. return _this;
  12241. }
  12242. PointLight.prototype.getClassName = function () {
  12243. return "PointLight";
  12244. };
  12245. PointLight.prototype.getAbsolutePosition = function () {
  12246. return this.transformedPosition ? this.transformedPosition : this.position;
  12247. };
  12248. PointLight.prototype.computeTransformedPosition = function () {
  12249. if (this.parent && this.parent.getWorldMatrix) {
  12250. if (!this.transformedPosition) {
  12251. this.transformedPosition = BABYLON.Vector3.Zero();
  12252. }
  12253. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12254. return true;
  12255. }
  12256. return false;
  12257. };
  12258. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  12259. if (this.parent && this.parent.getWorldMatrix) {
  12260. this.computeTransformedPosition();
  12261. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  12262. return;
  12263. }
  12264. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  12265. };
  12266. PointLight.prototype.needCube = function () {
  12267. return true;
  12268. };
  12269. PointLight.prototype.supportsVSM = function () {
  12270. return false;
  12271. };
  12272. PointLight.prototype.needRefreshPerFrame = function () {
  12273. return false;
  12274. };
  12275. PointLight.prototype.getShadowDirection = function (faceIndex) {
  12276. switch (faceIndex) {
  12277. case 0:
  12278. return new BABYLON.Vector3(1, 0, 0);
  12279. case 1:
  12280. return new BABYLON.Vector3(-1, 0, 0);
  12281. case 2:
  12282. return new BABYLON.Vector3(0, -1, 0);
  12283. case 3:
  12284. return new BABYLON.Vector3(0, 1, 0);
  12285. case 4:
  12286. return new BABYLON.Vector3(0, 0, 1);
  12287. case 5:
  12288. return new BABYLON.Vector3(0, 0, -1);
  12289. }
  12290. return BABYLON.Vector3.Zero();
  12291. };
  12292. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12293. var activeCamera = this.getScene().activeCamera;
  12294. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12295. };
  12296. PointLight.prototype._getWorldMatrix = function () {
  12297. if (!this._worldMatrix) {
  12298. this._worldMatrix = BABYLON.Matrix.Identity();
  12299. }
  12300. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12301. return this._worldMatrix;
  12302. };
  12303. PointLight.prototype.getTypeID = function () {
  12304. return 0;
  12305. };
  12306. return PointLight;
  12307. }(BABYLON.Light));
  12308. __decorate([
  12309. BABYLON.serializeAsVector3()
  12310. ], PointLight.prototype, "position", void 0);
  12311. BABYLON.PointLight = PointLight;
  12312. })(BABYLON || (BABYLON = {}));
  12313. //# sourceMappingURL=babylon.pointLight.js.map
  12314. var BABYLON;
  12315. (function (BABYLON) {
  12316. var SpotLight = (function (_super) {
  12317. __extends(SpotLight, _super);
  12318. function SpotLight(name, position, direction, angle, exponent, scene) {
  12319. var _this = _super.call(this, name, scene) || this;
  12320. _this.position = position;
  12321. _this.direction = direction;
  12322. _this.angle = angle;
  12323. _this.exponent = exponent;
  12324. return _this;
  12325. }
  12326. SpotLight.prototype.getClassName = function () {
  12327. return "SpotLight";
  12328. };
  12329. SpotLight.prototype.getAbsolutePosition = function () {
  12330. return this.transformedPosition ? this.transformedPosition : this.position;
  12331. };
  12332. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12333. var activeCamera = this.getScene().activeCamera;
  12334. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12335. };
  12336. SpotLight.prototype.needCube = function () {
  12337. return false;
  12338. };
  12339. SpotLight.prototype.supportsVSM = function () {
  12340. return true;
  12341. };
  12342. SpotLight.prototype.needRefreshPerFrame = function () {
  12343. return false;
  12344. };
  12345. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  12346. return this.direction;
  12347. };
  12348. SpotLight.prototype.setDirectionToTarget = function (target) {
  12349. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12350. return this.direction;
  12351. };
  12352. SpotLight.prototype.computeTransformedPosition = function () {
  12353. if (this.parent && this.parent.getWorldMatrix) {
  12354. if (!this.transformedPosition) {
  12355. this.transformedPosition = BABYLON.Vector3.Zero();
  12356. }
  12357. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12358. return true;
  12359. }
  12360. return false;
  12361. };
  12362. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  12363. var normalizeDirection;
  12364. if (this.parent && this.parent.getWorldMatrix) {
  12365. if (!this._transformedDirection) {
  12366. this._transformedDirection = BABYLON.Vector3.Zero();
  12367. }
  12368. this.computeTransformedPosition();
  12369. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12370. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  12371. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  12372. }
  12373. else {
  12374. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  12375. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12376. }
  12377. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  12378. };
  12379. SpotLight.prototype._getWorldMatrix = function () {
  12380. if (!this._worldMatrix) {
  12381. this._worldMatrix = BABYLON.Matrix.Identity();
  12382. }
  12383. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12384. return this._worldMatrix;
  12385. };
  12386. SpotLight.prototype.getTypeID = function () {
  12387. return 2;
  12388. };
  12389. SpotLight.prototype.getRotation = function () {
  12390. this.direction.normalize();
  12391. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  12392. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  12393. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  12394. };
  12395. return SpotLight;
  12396. }(BABYLON.Light));
  12397. __decorate([
  12398. BABYLON.serializeAsVector3()
  12399. ], SpotLight.prototype, "position", void 0);
  12400. __decorate([
  12401. BABYLON.serializeAsVector3()
  12402. ], SpotLight.prototype, "direction", void 0);
  12403. __decorate([
  12404. BABYLON.serialize()
  12405. ], SpotLight.prototype, "angle", void 0);
  12406. __decorate([
  12407. BABYLON.serialize()
  12408. ], SpotLight.prototype, "exponent", void 0);
  12409. BABYLON.SpotLight = SpotLight;
  12410. })(BABYLON || (BABYLON = {}));
  12411. //# sourceMappingURL=babylon.spotLight.js.map
  12412. var BABYLON;
  12413. (function (BABYLON) {
  12414. var HemisphericLight = (function (_super) {
  12415. __extends(HemisphericLight, _super);
  12416. function HemisphericLight(name, direction, scene) {
  12417. var _this = _super.call(this, name, scene) || this;
  12418. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  12419. _this.direction = direction;
  12420. return _this;
  12421. }
  12422. HemisphericLight.prototype.getClassName = function () {
  12423. return "HemisphericLight";
  12424. };
  12425. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  12426. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  12427. return this.direction;
  12428. };
  12429. HemisphericLight.prototype.getShadowGenerator = function () {
  12430. return null;
  12431. };
  12432. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  12433. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12434. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  12435. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  12436. };
  12437. HemisphericLight.prototype._getWorldMatrix = function () {
  12438. if (!this._worldMatrix) {
  12439. this._worldMatrix = BABYLON.Matrix.Identity();
  12440. }
  12441. return this._worldMatrix;
  12442. };
  12443. HemisphericLight.prototype.getTypeID = function () {
  12444. return 3;
  12445. };
  12446. return HemisphericLight;
  12447. }(BABYLON.Light));
  12448. __decorate([
  12449. BABYLON.serializeAsColor3()
  12450. ], HemisphericLight.prototype, "groundColor", void 0);
  12451. __decorate([
  12452. BABYLON.serializeAsVector3()
  12453. ], HemisphericLight.prototype, "direction", void 0);
  12454. BABYLON.HemisphericLight = HemisphericLight;
  12455. })(BABYLON || (BABYLON = {}));
  12456. //# sourceMappingURL=babylon.hemisphericLight.js.map
  12457. var BABYLON;
  12458. (function (BABYLON) {
  12459. var DirectionalLight = (function (_super) {
  12460. __extends(DirectionalLight, _super);
  12461. function DirectionalLight(name, direction, scene) {
  12462. var _this = _super.call(this, name, scene) || this;
  12463. _this.shadowOrthoScale = 0.5;
  12464. _this.autoUpdateExtends = true;
  12465. // Cache
  12466. _this._orthoLeft = Number.MAX_VALUE;
  12467. _this._orthoRight = Number.MIN_VALUE;
  12468. _this._orthoTop = Number.MIN_VALUE;
  12469. _this._orthoBottom = Number.MAX_VALUE;
  12470. _this.position = direction.scale(-1);
  12471. _this.direction = direction;
  12472. return _this;
  12473. }
  12474. DirectionalLight.prototype.getClassName = function () {
  12475. return "DirectionalLight";
  12476. };
  12477. DirectionalLight.prototype.getAbsolutePosition = function () {
  12478. return this.transformedPosition ? this.transformedPosition : this.position;
  12479. };
  12480. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  12481. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12482. return this.direction;
  12483. };
  12484. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12485. var activeCamera = this.getScene().activeCamera;
  12486. // Check extends
  12487. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  12488. var tempVector3 = BABYLON.Vector3.Zero();
  12489. this._orthoLeft = Number.MAX_VALUE;
  12490. this._orthoRight = Number.MIN_VALUE;
  12491. this._orthoTop = Number.MIN_VALUE;
  12492. this._orthoBottom = Number.MAX_VALUE;
  12493. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  12494. var mesh = renderList[meshIndex];
  12495. if (!mesh) {
  12496. continue;
  12497. }
  12498. var boundingInfo = mesh.getBoundingInfo();
  12499. if (!boundingInfo) {
  12500. continue;
  12501. }
  12502. var boundingBox = boundingInfo.boundingBox;
  12503. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  12504. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  12505. if (tempVector3.x < this._orthoLeft)
  12506. this._orthoLeft = tempVector3.x;
  12507. if (tempVector3.y < this._orthoBottom)
  12508. this._orthoBottom = tempVector3.y;
  12509. if (tempVector3.x > this._orthoRight)
  12510. this._orthoRight = tempVector3.x;
  12511. if (tempVector3.y > this._orthoTop)
  12512. this._orthoTop = tempVector3.y;
  12513. }
  12514. }
  12515. }
  12516. var xOffset = this._orthoRight - this._orthoLeft;
  12517. var yOffset = this._orthoTop - this._orthoBottom;
  12518. 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);
  12519. };
  12520. DirectionalLight.prototype.supportsVSM = function () {
  12521. return true;
  12522. };
  12523. DirectionalLight.prototype.needRefreshPerFrame = function () {
  12524. return true;
  12525. };
  12526. DirectionalLight.prototype.needCube = function () {
  12527. return false;
  12528. };
  12529. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  12530. return this.direction;
  12531. };
  12532. DirectionalLight.prototype.computeTransformedPosition = function () {
  12533. if (this.parent && this.parent.getWorldMatrix) {
  12534. if (!this.transformedPosition) {
  12535. this.transformedPosition = BABYLON.Vector3.Zero();
  12536. }
  12537. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12538. return true;
  12539. }
  12540. return false;
  12541. };
  12542. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  12543. if (this.parent && this.parent.getWorldMatrix) {
  12544. if (!this._transformedDirection) {
  12545. this._transformedDirection = BABYLON.Vector3.Zero();
  12546. }
  12547. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12548. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  12549. return;
  12550. }
  12551. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  12552. };
  12553. DirectionalLight.prototype._getWorldMatrix = function () {
  12554. if (!this._worldMatrix) {
  12555. this._worldMatrix = BABYLON.Matrix.Identity();
  12556. }
  12557. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12558. return this._worldMatrix;
  12559. };
  12560. DirectionalLight.prototype.getTypeID = function () {
  12561. return 1;
  12562. };
  12563. return DirectionalLight;
  12564. }(BABYLON.Light));
  12565. __decorate([
  12566. BABYLON.serializeAsVector3()
  12567. ], DirectionalLight.prototype, "position", void 0);
  12568. __decorate([
  12569. BABYLON.serializeAsVector3()
  12570. ], DirectionalLight.prototype, "direction", void 0);
  12571. __decorate([
  12572. BABYLON.serialize()
  12573. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  12574. __decorate([
  12575. BABYLON.serialize()
  12576. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  12577. BABYLON.DirectionalLight = DirectionalLight;
  12578. })(BABYLON || (BABYLON = {}));
  12579. //# sourceMappingURL=babylon.directionalLight.js.map
  12580. var BABYLON;
  12581. (function (BABYLON) {
  12582. var ShadowGenerator = (function () {
  12583. function ShadowGenerator(mapSize, light) {
  12584. var _this = this;
  12585. // Members
  12586. this._filter = ShadowGenerator.FILTER_NONE;
  12587. this.blurScale = 2;
  12588. this._blurBoxOffset = 0;
  12589. this._bias = 0.00005;
  12590. this._lightDirection = BABYLON.Vector3.Zero();
  12591. this.forceBackFacesOnly = false;
  12592. this._darkness = 0;
  12593. this._transparencyShadow = false;
  12594. this._viewMatrix = BABYLON.Matrix.Zero();
  12595. this._projectionMatrix = BABYLON.Matrix.Zero();
  12596. this._transformMatrix = BABYLON.Matrix.Zero();
  12597. this._worldViewProjection = BABYLON.Matrix.Zero();
  12598. this._currentFaceIndex = 0;
  12599. this._currentFaceIndexCache = 0;
  12600. this._useFullFloat = true;
  12601. this._light = light;
  12602. this._scene = light.getScene();
  12603. this._mapSize = mapSize;
  12604. light._shadowGenerator = this;
  12605. // Texture type fallback from float to int if not supported.
  12606. var textureType;
  12607. var caps = this._scene.getEngine().getCaps();
  12608. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12609. this._useFullFloat = true;
  12610. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12611. }
  12612. else {
  12613. this._useFullFloat = false;
  12614. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12615. }
  12616. // Render target
  12617. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12618. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12619. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12620. this._shadowMap.anisotropicFilteringLevel = 1;
  12621. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12622. this._shadowMap.renderParticles = false;
  12623. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12624. _this._currentFaceIndex = faceIndex;
  12625. });
  12626. this._shadowMap.onAfterUnbindObservable.add(function () {
  12627. if (!_this.useBlurVarianceShadowMap) {
  12628. return;
  12629. }
  12630. if (!_this._shadowMap2) {
  12631. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12632. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12633. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12634. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12635. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12636. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12637. effect.setTexture("textureSampler", _this._shadowMap);
  12638. });
  12639. _this.blurBoxOffset = 1;
  12640. }
  12641. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12642. });
  12643. // Custom render function
  12644. var renderSubMesh = function (subMesh) {
  12645. var mesh = subMesh.getRenderingMesh();
  12646. var scene = _this._scene;
  12647. var engine = scene.getEngine();
  12648. // Culling
  12649. engine.setState(subMesh.getMaterial().backFaceCulling);
  12650. // Managing instances
  12651. var batch = mesh._getInstancesRenderList(subMesh._id);
  12652. if (batch.mustReturn) {
  12653. return;
  12654. }
  12655. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12656. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12657. engine.enableEffect(_this._effect);
  12658. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12659. var material = subMesh.getMaterial();
  12660. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12661. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12662. if (_this.getLight().needCube()) {
  12663. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12664. }
  12665. // Alpha test
  12666. if (material && material.needAlphaTesting()) {
  12667. var alphaTexture = material.getAlphaTestTexture();
  12668. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12669. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12670. }
  12671. // Bones
  12672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12673. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12674. }
  12675. if (_this.forceBackFacesOnly) {
  12676. engine.setState(true, 0, false, true);
  12677. }
  12678. // Draw
  12679. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12680. if (_this.forceBackFacesOnly) {
  12681. engine.setState(true, 0, false, false);
  12682. }
  12683. }
  12684. else {
  12685. // Need to reset refresh rate of the shadowMap
  12686. _this._shadowMap.resetRefreshCounter();
  12687. }
  12688. };
  12689. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12690. var index;
  12691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12692. renderSubMesh(opaqueSubMeshes.data[index]);
  12693. }
  12694. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12695. renderSubMesh(alphaTestSubMeshes.data[index]);
  12696. }
  12697. if (_this._transparencyShadow) {
  12698. for (index = 0; index < transparentSubMeshes.length; index++) {
  12699. renderSubMesh(transparentSubMeshes.data[index]);
  12700. }
  12701. }
  12702. };
  12703. this._shadowMap.onClearObservable.add(function (engine) {
  12704. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12705. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12706. }
  12707. else {
  12708. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12709. }
  12710. });
  12711. }
  12712. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12713. // Static
  12714. get: function () {
  12715. return ShadowGenerator._FILTER_NONE;
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12721. get: function () {
  12722. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12728. get: function () {
  12729. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12730. },
  12731. enumerable: true,
  12732. configurable: true
  12733. });
  12734. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12735. get: function () {
  12736. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12737. },
  12738. enumerable: true,
  12739. configurable: true
  12740. });
  12741. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12742. get: function () {
  12743. return this._bias;
  12744. },
  12745. set: function (bias) {
  12746. this._bias = bias;
  12747. },
  12748. enumerable: true,
  12749. configurable: true
  12750. });
  12751. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12752. get: function () {
  12753. return this._blurBoxOffset;
  12754. },
  12755. set: function (value) {
  12756. var _this = this;
  12757. if (this._blurBoxOffset === value) {
  12758. return;
  12759. }
  12760. this._blurBoxOffset = value;
  12761. if (this._boxBlurPostprocess) {
  12762. this._boxBlurPostprocess.dispose();
  12763. }
  12764. 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);
  12765. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12766. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12767. });
  12768. },
  12769. enumerable: true,
  12770. configurable: true
  12771. });
  12772. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12773. get: function () {
  12774. return this._filter;
  12775. },
  12776. set: function (value) {
  12777. if (this._filter === value) {
  12778. return;
  12779. }
  12780. this._filter = value;
  12781. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12782. this._shadowMap.anisotropicFilteringLevel = 16;
  12783. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12784. }
  12785. else {
  12786. this._shadowMap.anisotropicFilteringLevel = 1;
  12787. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12788. }
  12789. },
  12790. enumerable: true,
  12791. configurable: true
  12792. });
  12793. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12794. get: function () {
  12795. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12796. },
  12797. set: function (value) {
  12798. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12799. },
  12800. enumerable: true,
  12801. configurable: true
  12802. });
  12803. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12804. get: function () {
  12805. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12806. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12807. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12808. },
  12809. set: function (value) {
  12810. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12811. },
  12812. enumerable: true,
  12813. configurable: true
  12814. });
  12815. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12816. get: function () {
  12817. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12818. },
  12819. set: function (value) {
  12820. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12826. var defines = [];
  12827. if (this._useFullFloat) {
  12828. defines.push("#define FULLFLOAT");
  12829. }
  12830. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12831. defines.push("#define VSM");
  12832. }
  12833. if (this.getLight().needCube()) {
  12834. defines.push("#define CUBEMAP");
  12835. }
  12836. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12837. var mesh = subMesh.getMesh();
  12838. var material = subMesh.getMaterial();
  12839. // Alpha test
  12840. if (material && material.needAlphaTesting()) {
  12841. defines.push("#define ALPHATEST");
  12842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12843. attribs.push(BABYLON.VertexBuffer.UVKind);
  12844. defines.push("#define UV1");
  12845. }
  12846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12847. var alphaTexture = material.getAlphaTestTexture();
  12848. if (alphaTexture.coordinatesIndex === 1) {
  12849. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12850. defines.push("#define UV2");
  12851. }
  12852. }
  12853. }
  12854. // Bones
  12855. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12858. if (mesh.numBoneInfluencers > 4) {
  12859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12861. }
  12862. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12863. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12864. }
  12865. else {
  12866. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12867. }
  12868. // Instances
  12869. if (useInstances) {
  12870. defines.push("#define INSTANCES");
  12871. attribs.push("world0");
  12872. attribs.push("world1");
  12873. attribs.push("world2");
  12874. attribs.push("world3");
  12875. }
  12876. // Get correct effect
  12877. var join = defines.join("\n");
  12878. if (this._cachedDefines !== join) {
  12879. this._cachedDefines = join;
  12880. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12881. }
  12882. return this._effect.isReady();
  12883. };
  12884. ShadowGenerator.prototype.getShadowMap = function () {
  12885. return this._shadowMap;
  12886. };
  12887. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12888. if (this._shadowMap2) {
  12889. return this._shadowMap2;
  12890. }
  12891. return this._shadowMap;
  12892. };
  12893. ShadowGenerator.prototype.getLight = function () {
  12894. return this._light;
  12895. };
  12896. // Methods
  12897. ShadowGenerator.prototype.getTransformMatrix = function () {
  12898. var scene = this._scene;
  12899. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12900. return this._transformMatrix;
  12901. }
  12902. this._currentRenderID = scene.getRenderId();
  12903. this._currentFaceIndexCache = this._currentFaceIndex;
  12904. var lightPosition = this._light.position;
  12905. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12906. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12907. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12908. }
  12909. if (this._light.computeTransformedPosition()) {
  12910. lightPosition = this._light.transformedPosition;
  12911. }
  12912. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12913. this._cachedPosition = lightPosition.clone();
  12914. this._cachedDirection = this._lightDirection.clone();
  12915. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12916. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12917. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12918. }
  12919. return this._transformMatrix;
  12920. };
  12921. ShadowGenerator.prototype.getDarkness = function () {
  12922. return this._darkness;
  12923. };
  12924. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12925. if (darkness >= 1.0)
  12926. this._darkness = 1.0;
  12927. else if (darkness <= 0.0)
  12928. this._darkness = 0.0;
  12929. else
  12930. this._darkness = darkness;
  12931. };
  12932. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12933. this._transparencyShadow = hasShadow;
  12934. };
  12935. ShadowGenerator.prototype._packHalf = function (depth) {
  12936. var scale = depth * 255.0;
  12937. var fract = scale - Math.floor(scale);
  12938. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12939. };
  12940. ShadowGenerator.prototype.dispose = function () {
  12941. this._shadowMap.dispose();
  12942. if (this._shadowMap2) {
  12943. this._shadowMap2.dispose();
  12944. }
  12945. if (this._downSamplePostprocess) {
  12946. this._downSamplePostprocess.dispose();
  12947. }
  12948. if (this._boxBlurPostprocess) {
  12949. this._boxBlurPostprocess.dispose();
  12950. }
  12951. this._light._shadowGenerator = null;
  12952. };
  12953. ShadowGenerator.prototype.serialize = function () {
  12954. var serializationObject = {};
  12955. serializationObject.lightId = this._light.id;
  12956. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12957. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12958. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12959. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12960. serializationObject.renderList = [];
  12961. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12962. var mesh = this.getShadowMap().renderList[meshIndex];
  12963. serializationObject.renderList.push(mesh.id);
  12964. }
  12965. return serializationObject;
  12966. };
  12967. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12968. //casting to point light, as light is missing the position attr and typescript complains.
  12969. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12970. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12971. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12972. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12973. meshes.forEach(function (mesh) {
  12974. shadowGenerator.getShadowMap().renderList.push(mesh);
  12975. });
  12976. }
  12977. if (parsedShadowGenerator.usePoissonSampling) {
  12978. shadowGenerator.usePoissonSampling = true;
  12979. }
  12980. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12981. shadowGenerator.useVarianceShadowMap = true;
  12982. }
  12983. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12984. shadowGenerator.useBlurVarianceShadowMap = true;
  12985. if (parsedShadowGenerator.blurScale) {
  12986. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12987. }
  12988. if (parsedShadowGenerator.blurBoxOffset) {
  12989. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12990. }
  12991. }
  12992. if (parsedShadowGenerator.bias !== undefined) {
  12993. shadowGenerator.bias = parsedShadowGenerator.bias;
  12994. }
  12995. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12996. return shadowGenerator;
  12997. };
  12998. return ShadowGenerator;
  12999. }());
  13000. ShadowGenerator._FILTER_NONE = 0;
  13001. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  13002. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  13003. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  13004. BABYLON.ShadowGenerator = ShadowGenerator;
  13005. })(BABYLON || (BABYLON = {}));
  13006. //# sourceMappingURL=babylon.shadowGenerator.js.map
  13007. var BABYLON;
  13008. (function (BABYLON) {
  13009. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  13010. if (boxMin.x > sphereCenter.x + sphereRadius)
  13011. return false;
  13012. if (sphereCenter.x - sphereRadius > boxMax.x)
  13013. return false;
  13014. if (boxMin.y > sphereCenter.y + sphereRadius)
  13015. return false;
  13016. if (sphereCenter.y - sphereRadius > boxMax.y)
  13017. return false;
  13018. if (boxMin.z > sphereCenter.z + sphereRadius)
  13019. return false;
  13020. if (sphereCenter.z - sphereRadius > boxMax.z)
  13021. return false;
  13022. return true;
  13023. };
  13024. var getLowestRoot = (function () {
  13025. var result = { root: 0, found: false };
  13026. return function (a, b, c, maxR) {
  13027. result.root = 0;
  13028. result.found = false;
  13029. var determinant = b * b - 4.0 * a * c;
  13030. if (determinant < 0)
  13031. return result;
  13032. var sqrtD = Math.sqrt(determinant);
  13033. var r1 = (-b - sqrtD) / (2.0 * a);
  13034. var r2 = (-b + sqrtD) / (2.0 * a);
  13035. if (r1 > r2) {
  13036. var temp = r2;
  13037. r2 = r1;
  13038. r1 = temp;
  13039. }
  13040. if (r1 > 0 && r1 < maxR) {
  13041. result.root = r1;
  13042. result.found = true;
  13043. return result;
  13044. }
  13045. if (r2 > 0 && r2 < maxR) {
  13046. result.root = r2;
  13047. result.found = true;
  13048. return result;
  13049. }
  13050. return result;
  13051. };
  13052. })();
  13053. var Collider = (function () {
  13054. function Collider() {
  13055. this.radius = new BABYLON.Vector3(1, 1, 1);
  13056. this.retry = 0;
  13057. this.basePointWorld = BABYLON.Vector3.Zero();
  13058. this.velocityWorld = BABYLON.Vector3.Zero();
  13059. this.normalizedVelocity = BABYLON.Vector3.Zero();
  13060. this._collisionPoint = BABYLON.Vector3.Zero();
  13061. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  13062. this._tempVector = BABYLON.Vector3.Zero();
  13063. this._tempVector2 = BABYLON.Vector3.Zero();
  13064. this._tempVector3 = BABYLON.Vector3.Zero();
  13065. this._tempVector4 = BABYLON.Vector3.Zero();
  13066. this._edge = BABYLON.Vector3.Zero();
  13067. this._baseToVertex = BABYLON.Vector3.Zero();
  13068. this._destinationPoint = BABYLON.Vector3.Zero();
  13069. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  13070. this._displacementVector = BABYLON.Vector3.Zero();
  13071. }
  13072. // Methods
  13073. Collider.prototype._initialize = function (source, dir, e) {
  13074. this.velocity = dir;
  13075. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  13076. this.basePoint = source;
  13077. source.multiplyToRef(this.radius, this.basePointWorld);
  13078. dir.multiplyToRef(this.radius, this.velocityWorld);
  13079. this.velocityWorldLength = this.velocityWorld.length();
  13080. this.epsilon = e;
  13081. this.collisionFound = false;
  13082. };
  13083. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  13084. pa.subtractToRef(point, this._tempVector);
  13085. pb.subtractToRef(point, this._tempVector2);
  13086. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  13087. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13088. if (d < 0)
  13089. return false;
  13090. pc.subtractToRef(point, this._tempVector3);
  13091. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  13092. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13093. if (d < 0)
  13094. return false;
  13095. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  13096. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13097. return d >= 0;
  13098. };
  13099. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  13100. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  13101. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  13102. if (distance > this.velocityWorldLength + max + sphereRadius) {
  13103. return false;
  13104. }
  13105. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  13106. return false;
  13107. return true;
  13108. };
  13109. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  13110. var t0;
  13111. var embeddedInPlane = false;
  13112. //defensive programming, actually not needed.
  13113. if (!trianglePlaneArray) {
  13114. trianglePlaneArray = [];
  13115. }
  13116. if (!trianglePlaneArray[faceIndex]) {
  13117. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  13118. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  13119. }
  13120. var trianglePlane = trianglePlaneArray[faceIndex];
  13121. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  13122. return;
  13123. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  13124. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  13125. if (normalDotVelocity == 0) {
  13126. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  13127. return;
  13128. embeddedInPlane = true;
  13129. t0 = 0;
  13130. }
  13131. else {
  13132. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13133. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13134. if (t0 > t1) {
  13135. var temp = t1;
  13136. t1 = t0;
  13137. t0 = temp;
  13138. }
  13139. if (t0 > 1.0 || t1 < 0.0)
  13140. return;
  13141. if (t0 < 0)
  13142. t0 = 0;
  13143. if (t0 > 1.0)
  13144. t0 = 1.0;
  13145. }
  13146. this._collisionPoint.copyFromFloats(0, 0, 0);
  13147. var found = false;
  13148. var t = 1.0;
  13149. if (!embeddedInPlane) {
  13150. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  13151. this.velocity.scaleToRef(t0, this._tempVector);
  13152. this._planeIntersectionPoint.addInPlace(this._tempVector);
  13153. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  13154. found = true;
  13155. t = t0;
  13156. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  13157. }
  13158. }
  13159. if (!found) {
  13160. var velocitySquaredLength = this.velocity.lengthSquared();
  13161. var a = velocitySquaredLength;
  13162. this.basePoint.subtractToRef(p1, this._tempVector);
  13163. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13164. var c = this._tempVector.lengthSquared() - 1.0;
  13165. var lowestRoot = getLowestRoot(a, b, c, t);
  13166. if (lowestRoot.found) {
  13167. t = lowestRoot.root;
  13168. found = true;
  13169. this._collisionPoint.copyFrom(p1);
  13170. }
  13171. this.basePoint.subtractToRef(p2, this._tempVector);
  13172. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13173. c = this._tempVector.lengthSquared() - 1.0;
  13174. lowestRoot = getLowestRoot(a, b, c, t);
  13175. if (lowestRoot.found) {
  13176. t = lowestRoot.root;
  13177. found = true;
  13178. this._collisionPoint.copyFrom(p2);
  13179. }
  13180. this.basePoint.subtractToRef(p3, this._tempVector);
  13181. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13182. c = this._tempVector.lengthSquared() - 1.0;
  13183. lowestRoot = getLowestRoot(a, b, c, t);
  13184. if (lowestRoot.found) {
  13185. t = lowestRoot.root;
  13186. found = true;
  13187. this._collisionPoint.copyFrom(p3);
  13188. }
  13189. p2.subtractToRef(p1, this._edge);
  13190. p1.subtractToRef(this.basePoint, this._baseToVertex);
  13191. var edgeSquaredLength = this._edge.lengthSquared();
  13192. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13193. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13194. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13195. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13196. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13197. lowestRoot = getLowestRoot(a, b, c, t);
  13198. if (lowestRoot.found) {
  13199. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13200. if (f >= 0.0 && f <= 1.0) {
  13201. t = lowestRoot.root;
  13202. found = true;
  13203. this._edge.scaleInPlace(f);
  13204. p1.addToRef(this._edge, this._collisionPoint);
  13205. }
  13206. }
  13207. p3.subtractToRef(p2, this._edge);
  13208. p2.subtractToRef(this.basePoint, this._baseToVertex);
  13209. edgeSquaredLength = this._edge.lengthSquared();
  13210. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13211. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13212. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13213. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13214. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13215. lowestRoot = getLowestRoot(a, b, c, t);
  13216. if (lowestRoot.found) {
  13217. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13218. if (f >= 0.0 && f <= 1.0) {
  13219. t = lowestRoot.root;
  13220. found = true;
  13221. this._edge.scaleInPlace(f);
  13222. p2.addToRef(this._edge, this._collisionPoint);
  13223. }
  13224. }
  13225. p1.subtractToRef(p3, this._edge);
  13226. p3.subtractToRef(this.basePoint, this._baseToVertex);
  13227. edgeSquaredLength = this._edge.lengthSquared();
  13228. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13229. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13230. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13231. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13232. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13233. lowestRoot = getLowestRoot(a, b, c, t);
  13234. if (lowestRoot.found) {
  13235. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13236. if (f >= 0.0 && f <= 1.0) {
  13237. t = lowestRoot.root;
  13238. found = true;
  13239. this._edge.scaleInPlace(f);
  13240. p3.addToRef(this._edge, this._collisionPoint);
  13241. }
  13242. }
  13243. }
  13244. if (found) {
  13245. var distToCollision = t * this.velocity.length();
  13246. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  13247. if (!this.intersectionPoint) {
  13248. this.intersectionPoint = this._collisionPoint.clone();
  13249. }
  13250. else {
  13251. this.intersectionPoint.copyFrom(this._collisionPoint);
  13252. }
  13253. this.nearestDistance = distToCollision;
  13254. this.collisionFound = true;
  13255. }
  13256. }
  13257. };
  13258. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  13259. for (var i = indexStart; i < indexEnd; i += 3) {
  13260. var p1 = pts[indices[i] - decal];
  13261. var p2 = pts[indices[i + 1] - decal];
  13262. var p3 = pts[indices[i + 2] - decal];
  13263. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  13264. }
  13265. };
  13266. Collider.prototype._getResponse = function (pos, vel) {
  13267. pos.addToRef(vel, this._destinationPoint);
  13268. vel.scaleInPlace((this.nearestDistance / vel.length()));
  13269. this.basePoint.addToRef(vel, pos);
  13270. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  13271. this._slidePlaneNormal.normalize();
  13272. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  13273. pos.addInPlace(this._displacementVector);
  13274. this.intersectionPoint.addInPlace(this._displacementVector);
  13275. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  13276. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  13277. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  13278. };
  13279. return Collider;
  13280. }());
  13281. BABYLON.Collider = Collider;
  13282. })(BABYLON || (BABYLON = {}));
  13283. //# sourceMappingURL=babylon.collider.js.map
  13284. var BABYLON;
  13285. (function (BABYLON) {
  13286. //WebWorker code will be inserted to this variable.
  13287. BABYLON.CollisionWorker = "";
  13288. var WorkerTaskType;
  13289. (function (WorkerTaskType) {
  13290. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  13291. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  13292. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  13293. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  13294. var WorkerReplyType;
  13295. (function (WorkerReplyType) {
  13296. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  13297. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  13298. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  13299. var CollisionCoordinatorWorker = (function () {
  13300. function CollisionCoordinatorWorker() {
  13301. var _this = this;
  13302. this._scaledPosition = BABYLON.Vector3.Zero();
  13303. this._scaledVelocity = BABYLON.Vector3.Zero();
  13304. this.onMeshUpdated = function (mesh) {
  13305. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  13306. };
  13307. this.onGeometryUpdated = function (geometry) {
  13308. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  13309. };
  13310. this._afterRender = function () {
  13311. if (!_this._init)
  13312. return;
  13313. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  13314. return;
  13315. }
  13316. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  13317. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  13318. if (_this._runningUpdated > 4) {
  13319. return;
  13320. }
  13321. ++_this._runningUpdated;
  13322. var payload = {
  13323. updatedMeshes: _this._addUpdateMeshesList,
  13324. updatedGeometries: _this._addUpdateGeometriesList,
  13325. removedGeometries: _this._toRemoveGeometryArray,
  13326. removedMeshes: _this._toRemoveMeshesArray
  13327. };
  13328. var message = {
  13329. payload: payload,
  13330. taskType: WorkerTaskType.UPDATE
  13331. };
  13332. var serializable = [];
  13333. for (var id in payload.updatedGeometries) {
  13334. if (payload.updatedGeometries.hasOwnProperty(id)) {
  13335. //prepare transferables
  13336. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  13337. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  13338. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  13339. }
  13340. }
  13341. _this._worker.postMessage(message, serializable);
  13342. _this._addUpdateMeshesList = {};
  13343. _this._addUpdateGeometriesList = {};
  13344. _this._toRemoveGeometryArray = [];
  13345. _this._toRemoveMeshesArray = [];
  13346. };
  13347. this._onMessageFromWorker = function (e) {
  13348. var returnData = e.data;
  13349. if (returnData.error != WorkerReplyType.SUCCESS) {
  13350. //TODO what errors can be returned from the worker?
  13351. BABYLON.Tools.Warn("error returned from worker!");
  13352. return;
  13353. }
  13354. switch (returnData.taskType) {
  13355. case WorkerTaskType.INIT:
  13356. _this._init = true;
  13357. //Update the worked with ALL of the scene's current state
  13358. _this._scene.meshes.forEach(function (mesh) {
  13359. _this.onMeshAdded(mesh);
  13360. });
  13361. _this._scene.getGeometries().forEach(function (geometry) {
  13362. _this.onGeometryAdded(geometry);
  13363. });
  13364. break;
  13365. case WorkerTaskType.UPDATE:
  13366. _this._runningUpdated--;
  13367. break;
  13368. case WorkerTaskType.COLLIDE:
  13369. _this._runningCollisionTask = false;
  13370. var returnPayload = returnData.payload;
  13371. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  13372. return;
  13373. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  13374. //cleanup
  13375. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  13376. break;
  13377. }
  13378. };
  13379. this._collisionsCallbackArray = [];
  13380. this._init = false;
  13381. this._runningUpdated = 0;
  13382. this._runningCollisionTask = false;
  13383. this._addUpdateMeshesList = {};
  13384. this._addUpdateGeometriesList = {};
  13385. this._toRemoveGeometryArray = [];
  13386. this._toRemoveMeshesArray = [];
  13387. }
  13388. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13389. if (!this._init)
  13390. return;
  13391. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  13392. return;
  13393. position.divideToRef(collider.radius, this._scaledPosition);
  13394. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13395. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  13396. var payload = {
  13397. collider: {
  13398. position: this._scaledPosition.asArray(),
  13399. velocity: this._scaledVelocity.asArray(),
  13400. radius: collider.radius.asArray()
  13401. },
  13402. collisionId: collisionIndex,
  13403. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  13404. maximumRetry: maximumRetry
  13405. };
  13406. var message = {
  13407. payload: payload,
  13408. taskType: WorkerTaskType.COLLIDE
  13409. };
  13410. this._worker.postMessage(message);
  13411. };
  13412. CollisionCoordinatorWorker.prototype.init = function (scene) {
  13413. this._scene = scene;
  13414. this._scene.registerAfterRender(this._afterRender);
  13415. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  13416. this._worker = new Worker(workerUrl);
  13417. this._worker.onmessage = this._onMessageFromWorker;
  13418. var message = {
  13419. payload: {},
  13420. taskType: WorkerTaskType.INIT
  13421. };
  13422. this._worker.postMessage(message);
  13423. };
  13424. CollisionCoordinatorWorker.prototype.destroy = function () {
  13425. this._scene.unregisterAfterRender(this._afterRender);
  13426. this._worker.terminate();
  13427. };
  13428. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  13429. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  13430. this.onMeshUpdated(mesh);
  13431. };
  13432. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  13433. this._toRemoveMeshesArray.push(mesh.uniqueId);
  13434. };
  13435. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  13436. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  13437. geometry.onGeometryUpdated = this.onGeometryUpdated;
  13438. this.onGeometryUpdated(geometry);
  13439. };
  13440. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  13441. this._toRemoveGeometryArray.push(geometry.id);
  13442. };
  13443. return CollisionCoordinatorWorker;
  13444. }());
  13445. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  13446. var submeshes = [];
  13447. if (mesh.subMeshes) {
  13448. submeshes = mesh.subMeshes.map(function (sm, idx) {
  13449. return {
  13450. position: idx,
  13451. verticesStart: sm.verticesStart,
  13452. verticesCount: sm.verticesCount,
  13453. indexStart: sm.indexStart,
  13454. indexCount: sm.indexCount,
  13455. hasMaterial: !!sm.getMaterial(),
  13456. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13457. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  13458. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13459. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  13460. };
  13461. });
  13462. }
  13463. var geometryId = null;
  13464. if (mesh instanceof BABYLON.Mesh) {
  13465. geometryId = mesh.geometry ? mesh.geometry.id : null;
  13466. }
  13467. else if (mesh instanceof BABYLON.InstancedMesh) {
  13468. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  13469. }
  13470. return {
  13471. uniqueId: mesh.uniqueId,
  13472. id: mesh.id,
  13473. name: mesh.name,
  13474. geometryId: geometryId,
  13475. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13476. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  13477. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13478. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  13479. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  13480. subMeshes: submeshes,
  13481. checkCollisions: mesh.checkCollisions
  13482. };
  13483. };
  13484. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  13485. return {
  13486. id: geometry.id,
  13487. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  13488. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  13489. indices: new Uint32Array(geometry.getIndices() || []),
  13490. };
  13491. };
  13492. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  13493. var CollisionCoordinatorLegacy = (function () {
  13494. function CollisionCoordinatorLegacy() {
  13495. this._scaledPosition = BABYLON.Vector3.Zero();
  13496. this._scaledVelocity = BABYLON.Vector3.Zero();
  13497. this._finalPosition = BABYLON.Vector3.Zero();
  13498. }
  13499. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13500. position.divideToRef(collider.radius, this._scaledPosition);
  13501. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13502. collider.collidedMesh = null;
  13503. collider.retry = 0;
  13504. collider.initialVelocity = this._scaledVelocity;
  13505. collider.initialPosition = this._scaledPosition;
  13506. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  13507. this._finalPosition.multiplyInPlace(collider.radius);
  13508. //run the callback
  13509. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  13510. };
  13511. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  13512. this._scene = scene;
  13513. };
  13514. CollisionCoordinatorLegacy.prototype.destroy = function () {
  13515. //Legacy need no destruction method.
  13516. };
  13517. //No update in legacy mode
  13518. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  13519. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  13520. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  13521. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  13522. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  13523. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  13524. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  13525. if (excludedMesh === void 0) { excludedMesh = null; }
  13526. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  13527. if (collider.retry >= maximumRetry) {
  13528. finalPosition.copyFrom(position);
  13529. return;
  13530. }
  13531. collider._initialize(position, velocity, closeDistance);
  13532. // Check all meshes
  13533. for (var index = 0; index < this._scene.meshes.length; index++) {
  13534. var mesh = this._scene.meshes[index];
  13535. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  13536. mesh._checkCollision(collider);
  13537. }
  13538. }
  13539. if (!collider.collisionFound) {
  13540. position.addToRef(velocity, finalPosition);
  13541. return;
  13542. }
  13543. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  13544. collider._getResponse(position, velocity);
  13545. }
  13546. if (velocity.length() <= closeDistance) {
  13547. finalPosition.copyFrom(position);
  13548. return;
  13549. }
  13550. collider.retry++;
  13551. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  13552. };
  13553. return CollisionCoordinatorLegacy;
  13554. }());
  13555. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  13556. })(BABYLON || (BABYLON = {}));
  13557. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  13558. var BABYLON;
  13559. (function (BABYLON) {
  13560. var Camera = (function (_super) {
  13561. __extends(Camera, _super);
  13562. function Camera(name, position, scene) {
  13563. var _this = _super.call(this, name, scene) || this;
  13564. _this.upVector = BABYLON.Vector3.Up();
  13565. _this.orthoLeft = null;
  13566. _this.orthoRight = null;
  13567. _this.orthoBottom = null;
  13568. _this.orthoTop = null;
  13569. _this.fov = 0.8;
  13570. _this.minZ = 1.0;
  13571. _this.maxZ = 10000.0;
  13572. _this.inertia = 0.9;
  13573. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13574. _this.isIntermediate = false;
  13575. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13576. _this.layerMask = 0x0FFFFFFF;
  13577. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13578. // Camera rig members
  13579. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13580. _this._rigCameras = new Array();
  13581. // Cache
  13582. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13583. _this._projectionMatrix = new BABYLON.Matrix();
  13584. _this._doNotComputeProjectionMatrix = false;
  13585. _this._postProcesses = new Array();
  13586. _this._transformMatrix = BABYLON.Matrix.Zero();
  13587. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13588. _this._activeMeshes = new BABYLON.SmartArray(256);
  13589. _this._globalPosition = BABYLON.Vector3.Zero();
  13590. _this._refreshFrustumPlanes = true;
  13591. scene.addCamera(_this);
  13592. if (!scene.activeCamera) {
  13593. scene.activeCamera = _this;
  13594. }
  13595. _this.position = position;
  13596. return _this;
  13597. }
  13598. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13599. get: function () {
  13600. return Camera._PERSPECTIVE_CAMERA;
  13601. },
  13602. enumerable: true,
  13603. configurable: true
  13604. });
  13605. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13606. get: function () {
  13607. return Camera._ORTHOGRAPHIC_CAMERA;
  13608. },
  13609. enumerable: true,
  13610. configurable: true
  13611. });
  13612. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13613. get: function () {
  13614. return Camera._FOVMODE_VERTICAL_FIXED;
  13615. },
  13616. enumerable: true,
  13617. configurable: true
  13618. });
  13619. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13620. get: function () {
  13621. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13622. },
  13623. enumerable: true,
  13624. configurable: true
  13625. });
  13626. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13627. get: function () {
  13628. return Camera._RIG_MODE_NONE;
  13629. },
  13630. enumerable: true,
  13631. configurable: true
  13632. });
  13633. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13634. get: function () {
  13635. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13636. },
  13637. enumerable: true,
  13638. configurable: true
  13639. });
  13640. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13641. get: function () {
  13642. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13643. },
  13644. enumerable: true,
  13645. configurable: true
  13646. });
  13647. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13648. get: function () {
  13649. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13650. },
  13651. enumerable: true,
  13652. configurable: true
  13653. });
  13654. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13655. get: function () {
  13656. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13657. },
  13658. enumerable: true,
  13659. configurable: true
  13660. });
  13661. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13662. get: function () {
  13663. return Camera._RIG_MODE_VR;
  13664. },
  13665. enumerable: true,
  13666. configurable: true
  13667. });
  13668. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13669. get: function () {
  13670. return Camera._RIG_MODE_WEBVR;
  13671. },
  13672. enumerable: true,
  13673. configurable: true
  13674. });
  13675. Camera.prototype.getClassName = function () {
  13676. return "Camera";
  13677. };
  13678. /**
  13679. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13680. */
  13681. Camera.prototype.toString = function (fullDetails) {
  13682. var ret = "Name: " + this.name;
  13683. ret += ", type: " + this.getClassName();
  13684. if (this.animations) {
  13685. for (var i = 0; i < this.animations.length; i++) {
  13686. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13687. }
  13688. }
  13689. if (fullDetails) {
  13690. }
  13691. return ret;
  13692. };
  13693. Object.defineProperty(Camera.prototype, "globalPosition", {
  13694. get: function () {
  13695. return this._globalPosition;
  13696. },
  13697. enumerable: true,
  13698. configurable: true
  13699. });
  13700. Camera.prototype.getActiveMeshes = function () {
  13701. return this._activeMeshes;
  13702. };
  13703. Camera.prototype.isActiveMesh = function (mesh) {
  13704. return (this._activeMeshes.indexOf(mesh) !== -1);
  13705. };
  13706. //Cache
  13707. Camera.prototype._initCache = function () {
  13708. _super.prototype._initCache.call(this);
  13709. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13710. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13711. this._cache.mode = undefined;
  13712. this._cache.minZ = undefined;
  13713. this._cache.maxZ = undefined;
  13714. this._cache.fov = undefined;
  13715. this._cache.fovMode = undefined;
  13716. this._cache.aspectRatio = undefined;
  13717. this._cache.orthoLeft = undefined;
  13718. this._cache.orthoRight = undefined;
  13719. this._cache.orthoBottom = undefined;
  13720. this._cache.orthoTop = undefined;
  13721. this._cache.renderWidth = undefined;
  13722. this._cache.renderHeight = undefined;
  13723. };
  13724. Camera.prototype._updateCache = function (ignoreParentClass) {
  13725. if (!ignoreParentClass) {
  13726. _super.prototype._updateCache.call(this);
  13727. }
  13728. var engine = this.getEngine();
  13729. this._cache.position.copyFrom(this.position);
  13730. this._cache.upVector.copyFrom(this.upVector);
  13731. this._cache.mode = this.mode;
  13732. this._cache.minZ = this.minZ;
  13733. this._cache.maxZ = this.maxZ;
  13734. this._cache.fov = this.fov;
  13735. this._cache.fovMode = this.fovMode;
  13736. this._cache.aspectRatio = engine.getAspectRatio(this);
  13737. this._cache.orthoLeft = this.orthoLeft;
  13738. this._cache.orthoRight = this.orthoRight;
  13739. this._cache.orthoBottom = this.orthoBottom;
  13740. this._cache.orthoTop = this.orthoTop;
  13741. this._cache.renderWidth = engine.getRenderWidth();
  13742. this._cache.renderHeight = engine.getRenderHeight();
  13743. };
  13744. Camera.prototype._updateFromScene = function () {
  13745. this.updateCache();
  13746. this.update();
  13747. };
  13748. // Synchronized
  13749. Camera.prototype._isSynchronized = function () {
  13750. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13751. };
  13752. Camera.prototype._isSynchronizedViewMatrix = function () {
  13753. if (!_super.prototype._isSynchronized.call(this))
  13754. return false;
  13755. return this._cache.position.equals(this.position)
  13756. && this._cache.upVector.equals(this.upVector)
  13757. && this.isSynchronizedWithParent();
  13758. };
  13759. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13760. var check = this._cache.mode === this.mode
  13761. && this._cache.minZ === this.minZ
  13762. && this._cache.maxZ === this.maxZ;
  13763. if (!check) {
  13764. return false;
  13765. }
  13766. var engine = this.getEngine();
  13767. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13768. check = this._cache.fov === this.fov
  13769. && this._cache.fovMode === this.fovMode
  13770. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13771. }
  13772. else {
  13773. check = this._cache.orthoLeft === this.orthoLeft
  13774. && this._cache.orthoRight === this.orthoRight
  13775. && this._cache.orthoBottom === this.orthoBottom
  13776. && this._cache.orthoTop === this.orthoTop
  13777. && this._cache.renderWidth === engine.getRenderWidth()
  13778. && this._cache.renderHeight === engine.getRenderHeight();
  13779. }
  13780. return check;
  13781. };
  13782. // Controls
  13783. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13784. };
  13785. Camera.prototype.detachControl = function (element) {
  13786. };
  13787. Camera.prototype.update = function () {
  13788. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13789. this._updateRigCameras();
  13790. }
  13791. this._checkInputs();
  13792. };
  13793. Camera.prototype._checkInputs = function () {
  13794. };
  13795. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13796. // invalidate framebuffer
  13797. if (this._postProcesses.length > 0) {
  13798. this._postProcesses[0].markTextureDirty();
  13799. }
  13800. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13801. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13802. var cam = this._rigCameras[i];
  13803. var rigPostProcess = cam._rigPostProcess;
  13804. // for VR rig, there does not have to be a post process
  13805. if (rigPostProcess) {
  13806. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13807. if (isPass) {
  13808. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13809. cam.isIntermediate = this._postProcesses.length === 0;
  13810. }
  13811. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13812. rigPostProcess.markTextureDirty();
  13813. }
  13814. else {
  13815. cam._postProcesses = this._postProcesses.slice(0);
  13816. }
  13817. }
  13818. };
  13819. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13820. if (insertAt === void 0) { insertAt = null; }
  13821. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13822. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13823. return 0;
  13824. }
  13825. if (insertAt == null || insertAt < 0) {
  13826. this._postProcesses.push(postProcess);
  13827. }
  13828. else {
  13829. this._postProcesses.splice(insertAt, 0, postProcess);
  13830. }
  13831. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13832. return this._postProcesses.indexOf(postProcess);
  13833. };
  13834. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13835. if (atIndices === void 0) { atIndices = null; }
  13836. var result = [];
  13837. var i;
  13838. var index;
  13839. if (!atIndices) {
  13840. var idx = this._postProcesses.indexOf(postProcess);
  13841. if (idx !== -1) {
  13842. this._postProcesses.splice(idx, 1);
  13843. }
  13844. }
  13845. else {
  13846. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13847. // iterate descending, so can just splice as we go
  13848. for (i = atIndices.length - 1; i >= 0; i--) {
  13849. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13850. result.push(i);
  13851. continue;
  13852. }
  13853. index = atIndices[i];
  13854. this._postProcesses.splice(index, 1);
  13855. }
  13856. }
  13857. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13858. return result;
  13859. };
  13860. Camera.prototype.getWorldMatrix = function () {
  13861. if (!this._worldMatrix) {
  13862. this._worldMatrix = BABYLON.Matrix.Identity();
  13863. }
  13864. var viewMatrix = this.getViewMatrix();
  13865. viewMatrix.invertToRef(this._worldMatrix);
  13866. return this._worldMatrix;
  13867. };
  13868. Camera.prototype._getViewMatrix = function () {
  13869. return BABYLON.Matrix.Identity();
  13870. };
  13871. Camera.prototype.getViewMatrix = function (force) {
  13872. this._computedViewMatrix = this._computeViewMatrix(force);
  13873. if (!force && this._isSynchronizedViewMatrix()) {
  13874. return this._computedViewMatrix;
  13875. }
  13876. this._refreshFrustumPlanes = true;
  13877. if (!this.parent || !this.parent.getWorldMatrix) {
  13878. this._globalPosition.copyFrom(this.position);
  13879. }
  13880. else {
  13881. if (!this._worldMatrix) {
  13882. this._worldMatrix = BABYLON.Matrix.Identity();
  13883. }
  13884. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13885. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13886. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13887. this._computedViewMatrix.invert();
  13888. this._markSyncedWithParent();
  13889. }
  13890. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13891. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13892. }
  13893. this._currentRenderId = this.getScene().getRenderId();
  13894. return this._computedViewMatrix;
  13895. };
  13896. Camera.prototype._computeViewMatrix = function (force) {
  13897. if (!force && this._isSynchronizedViewMatrix()) {
  13898. return this._computedViewMatrix;
  13899. }
  13900. this._computedViewMatrix = this._getViewMatrix();
  13901. this._currentRenderId = this.getScene().getRenderId();
  13902. return this._computedViewMatrix;
  13903. };
  13904. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13905. this._doNotComputeProjectionMatrix = true;
  13906. if (projection !== undefined) {
  13907. this._projectionMatrix = projection;
  13908. }
  13909. };
  13910. ;
  13911. Camera.prototype.unfreezeProjectionMatrix = function () {
  13912. this._doNotComputeProjectionMatrix = false;
  13913. };
  13914. ;
  13915. Camera.prototype.getProjectionMatrix = function (force) {
  13916. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13917. return this._projectionMatrix;
  13918. }
  13919. this._refreshFrustumPlanes = true;
  13920. var engine = this.getEngine();
  13921. var scene = this.getScene();
  13922. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13923. if (this.minZ <= 0) {
  13924. this.minZ = 0.1;
  13925. }
  13926. if (scene.useRightHandedSystem) {
  13927. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13928. }
  13929. else {
  13930. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13931. }
  13932. return this._projectionMatrix;
  13933. }
  13934. var halfWidth = engine.getRenderWidth() / 2.0;
  13935. var halfHeight = engine.getRenderHeight() / 2.0;
  13936. if (scene.useRightHandedSystem) {
  13937. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13938. }
  13939. else {
  13940. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13941. }
  13942. return this._projectionMatrix;
  13943. };
  13944. Camera.prototype.getTranformationMatrix = function () {
  13945. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13946. return this._transformMatrix;
  13947. };
  13948. Camera.prototype.updateFrustumPlanes = function () {
  13949. if (!this._refreshFrustumPlanes) {
  13950. return;
  13951. }
  13952. this.getTranformationMatrix();
  13953. if (!this._frustumPlanes) {
  13954. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13955. }
  13956. else {
  13957. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13958. }
  13959. this._refreshFrustumPlanes = false;
  13960. };
  13961. Camera.prototype.isInFrustum = function (target) {
  13962. this.updateFrustumPlanes();
  13963. return target.isInFrustum(this._frustumPlanes);
  13964. };
  13965. Camera.prototype.isCompletelyInFrustum = function (target) {
  13966. this.updateFrustumPlanes();
  13967. return target.isCompletelyInFrustum(this._frustumPlanes);
  13968. };
  13969. Camera.prototype.dispose = function () {
  13970. // Animations
  13971. this.getScene().stopAnimation(this);
  13972. // Remove from scene
  13973. this.getScene().removeCamera(this);
  13974. while (this._rigCameras.length > 0) {
  13975. this._rigCameras.pop().dispose();
  13976. }
  13977. // Postprocesses
  13978. var i = this._postProcesses.length;
  13979. while (--i >= 0) {
  13980. this._postProcesses[i].dispose(this);
  13981. }
  13982. _super.prototype.dispose.call(this);
  13983. };
  13984. // ---- Camera rigs section ----
  13985. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13986. while (this._rigCameras.length > 0) {
  13987. this._rigCameras.pop().dispose();
  13988. }
  13989. this.cameraRigMode = mode;
  13990. this._cameraRigParams = {};
  13991. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13992. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13993. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13994. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13995. // create the rig cameras, unless none
  13996. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13997. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13998. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13999. }
  14000. switch (this.cameraRigMode) {
  14001. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14002. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14003. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14004. break;
  14005. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14006. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14007. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14008. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14009. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14010. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14011. break;
  14012. case Camera.RIG_MODE_VR:
  14013. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14014. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14015. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14016. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14017. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14018. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14019. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14020. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14021. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14022. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14023. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14024. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14025. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14026. if (metrics.compensateDistortion) {
  14027. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14028. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14029. }
  14030. break;
  14031. case Camera.RIG_MODE_WEBVR:
  14032. if (rigParams.vrDisplay) {
  14033. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14034. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14035. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14036. this._rigCameras[0].setCameraRigParameter("left", true);
  14037. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14038. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  14039. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14040. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14041. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14042. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14043. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14044. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  14045. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14046. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14047. }
  14048. break;
  14049. }
  14050. this._cascadePostProcessesToRigCams();
  14051. this.
  14052. update();
  14053. };
  14054. Camera.prototype._getVRProjectionMatrix = function () {
  14055. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14056. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14057. return this._projectionMatrix;
  14058. };
  14059. Camera.prototype._getWebVRProjectionMatrix = function () {
  14060. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  14061. //babylon compatible matrix
  14062. [8, 9, 10, 11].forEach(function (num) {
  14063. projectionArray[num] *= -1;
  14064. });
  14065. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  14066. return this._projectionMatrix;
  14067. };
  14068. //Can be used, but we'll use the free camera's view matrix calculation
  14069. Camera.prototype._getWebVRViewMatrix = function () {
  14070. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  14071. //babylon compatible matrix
  14072. [8, 9, 10, 11].forEach(function (num) {
  14073. projectionArray[num] *= -1;
  14074. });
  14075. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  14076. return this._webvrViewMatrix;
  14077. };
  14078. Camera.prototype.setCameraRigParameter = function (name, value) {
  14079. if (!this._cameraRigParams) {
  14080. this._cameraRigParams = {};
  14081. }
  14082. this._cameraRigParams[name] = value;
  14083. //provisionnally:
  14084. if (name === "interaxialDistance") {
  14085. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14086. }
  14087. };
  14088. /**
  14089. * needs to be overridden by children so sub has required properties to be copied
  14090. */
  14091. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14092. return null;
  14093. };
  14094. /**
  14095. * May need to be overridden by children
  14096. */
  14097. Camera.prototype._updateRigCameras = function () {
  14098. for (var i = 0; i < this._rigCameras.length; i++) {
  14099. this._rigCameras[i].minZ = this.minZ;
  14100. this._rigCameras[i].maxZ = this.maxZ;
  14101. this._rigCameras[i].fov = this.fov;
  14102. }
  14103. // only update viewport when ANAGLYPH
  14104. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14105. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14106. }
  14107. };
  14108. Camera.prototype._setupInputs = function () {
  14109. };
  14110. Camera.prototype.serialize = function () {
  14111. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14112. // Type
  14113. serializationObject.type = this.getClassName();
  14114. // Parent
  14115. if (this.parent) {
  14116. serializationObject.parentId = this.parent.id;
  14117. }
  14118. if (this.inputs) {
  14119. this.inputs.serialize(serializationObject);
  14120. }
  14121. // Animations
  14122. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14123. serializationObject.ranges = this.serializeAnimationRanges();
  14124. return serializationObject;
  14125. };
  14126. Camera.prototype.clone = function (name) {
  14127. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14128. };
  14129. Camera.prototype.getDirection = function (localAxis) {
  14130. var result = BABYLON.Vector3.Zero();
  14131. this.getDirectionToRef(localAxis, result);
  14132. return result;
  14133. };
  14134. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14135. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14136. };
  14137. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14138. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14139. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14140. switch (type) {
  14141. case "ArcRotateCamera":
  14142. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14143. case "DeviceOrientationCamera":
  14144. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14145. case "FollowCamera":
  14146. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14147. case "ArcFollowCamera":
  14148. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14149. case "GamepadCamera":
  14150. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14151. case "TouchCamera":
  14152. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14153. case "VirtualJoysticksCamera":
  14154. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14155. case "HolographicCamera":
  14156. return function () { return new BABYLON.HolographicCamera(name, scene); };
  14157. case "WebVRFreeCamera":
  14158. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14159. case "VRDeviceOrientationFreeCamera":
  14160. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14161. case "VRDeviceOrientationGamepadCamera":
  14162. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14163. case "AnaglyphArcRotateCamera":
  14164. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14165. case "AnaglyphFreeCamera":
  14166. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14167. case "AnaglyphGamepadCamera":
  14168. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14169. case "AnaglyphUniversalCamera":
  14170. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14171. case "StereoscopicArcRotateCamera":
  14172. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14173. case "StereoscopicFreeCamera":
  14174. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14175. case "StereoscopicGamepadCamera":
  14176. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14177. case "StereoscopicUniversalCamera":
  14178. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14179. case "FreeCamera":
  14180. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14181. default:
  14182. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14183. }
  14184. };
  14185. Camera.Parse = function (parsedCamera, scene) {
  14186. var type = parsedCamera.type;
  14187. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14188. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14189. // Parent
  14190. if (parsedCamera.parentId) {
  14191. camera._waitingParentId = parsedCamera.parentId;
  14192. }
  14193. //If camera has an input manager, let it parse inputs settings
  14194. if (camera.inputs) {
  14195. camera.inputs.parse(parsedCamera);
  14196. camera._setupInputs();
  14197. }
  14198. // Target
  14199. if (parsedCamera.target) {
  14200. if (camera.setTarget) {
  14201. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14202. }
  14203. }
  14204. // Apply 3d rig, when found
  14205. if (parsedCamera.cameraRigMode) {
  14206. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14207. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14208. }
  14209. // Animations
  14210. if (parsedCamera.animations) {
  14211. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14212. var parsedAnimation = parsedCamera.animations[animationIndex];
  14213. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14214. }
  14215. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14216. }
  14217. if (parsedCamera.autoAnimate) {
  14218. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14219. }
  14220. return camera;
  14221. };
  14222. return Camera;
  14223. }(BABYLON.Node));
  14224. // Statics
  14225. Camera._PERSPECTIVE_CAMERA = 0;
  14226. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14227. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14228. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14229. Camera._RIG_MODE_NONE = 0;
  14230. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14231. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14232. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14233. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14234. Camera._RIG_MODE_VR = 20;
  14235. Camera._RIG_MODE_WEBVR = 21;
  14236. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14237. __decorate([
  14238. BABYLON.serializeAsVector3()
  14239. ], Camera.prototype, "position", void 0);
  14240. __decorate([
  14241. BABYLON.serializeAsVector3()
  14242. ], Camera.prototype, "upVector", void 0);
  14243. __decorate([
  14244. BABYLON.serialize()
  14245. ], Camera.prototype, "orthoLeft", void 0);
  14246. __decorate([
  14247. BABYLON.serialize()
  14248. ], Camera.prototype, "orthoRight", void 0);
  14249. __decorate([
  14250. BABYLON.serialize()
  14251. ], Camera.prototype, "orthoBottom", void 0);
  14252. __decorate([
  14253. BABYLON.serialize()
  14254. ], Camera.prototype, "orthoTop", void 0);
  14255. __decorate([
  14256. BABYLON.serialize()
  14257. ], Camera.prototype, "fov", void 0);
  14258. __decorate([
  14259. BABYLON.serialize()
  14260. ], Camera.prototype, "minZ", void 0);
  14261. __decorate([
  14262. BABYLON.serialize()
  14263. ], Camera.prototype, "maxZ", void 0);
  14264. __decorate([
  14265. BABYLON.serialize()
  14266. ], Camera.prototype, "inertia", void 0);
  14267. __decorate([
  14268. BABYLON.serialize()
  14269. ], Camera.prototype, "mode", void 0);
  14270. __decorate([
  14271. BABYLON.serialize()
  14272. ], Camera.prototype, "layerMask", void 0);
  14273. __decorate([
  14274. BABYLON.serialize()
  14275. ], Camera.prototype, "fovMode", void 0);
  14276. __decorate([
  14277. BABYLON.serialize()
  14278. ], Camera.prototype, "cameraRigMode", void 0);
  14279. __decorate([
  14280. BABYLON.serialize()
  14281. ], Camera.prototype, "interaxialDistance", void 0);
  14282. __decorate([
  14283. BABYLON.serialize()
  14284. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14285. BABYLON.Camera = Camera;
  14286. })(BABYLON || (BABYLON = {}));
  14287. //# sourceMappingURL=babylon.camera.js.map
  14288. var BABYLON;
  14289. (function (BABYLON) {
  14290. BABYLON.CameraInputTypes = {};
  14291. var CameraInputsManager = (function () {
  14292. function CameraInputsManager(camera) {
  14293. this.attached = {};
  14294. this.camera = camera;
  14295. this.checkInputs = function () { };
  14296. }
  14297. CameraInputsManager.prototype.add = function (input) {
  14298. var type = input.getSimpleName();
  14299. if (this.attached[type]) {
  14300. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  14301. return;
  14302. }
  14303. this.attached[type] = input;
  14304. input.camera = this.camera;
  14305. //for checkInputs, we are dynamically creating a function
  14306. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  14307. if (input.checkInputs) {
  14308. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14309. }
  14310. if (this.attachedElement) {
  14311. input.attachControl(this.attachedElement);
  14312. }
  14313. };
  14314. CameraInputsManager.prototype.remove = function (inputToRemove) {
  14315. for (var cam in this.attached) {
  14316. var input = this.attached[cam];
  14317. if (input === inputToRemove) {
  14318. input.detachControl(this.attachedElement);
  14319. delete this.attached[cam];
  14320. this.rebuildInputCheck();
  14321. }
  14322. }
  14323. };
  14324. CameraInputsManager.prototype.removeByType = function (inputType) {
  14325. for (var cam in this.attached) {
  14326. var input = this.attached[cam];
  14327. if (input.getTypeName() === inputType) {
  14328. input.detachControl(this.attachedElement);
  14329. delete this.attached[cam];
  14330. this.rebuildInputCheck();
  14331. }
  14332. }
  14333. };
  14334. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  14335. var current = this.checkInputs;
  14336. return function () {
  14337. current();
  14338. fn();
  14339. };
  14340. };
  14341. CameraInputsManager.prototype.attachInput = function (input) {
  14342. input.attachControl(this.attachedElement, this.noPreventDefault);
  14343. };
  14344. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  14345. if (this.attachedElement) {
  14346. return;
  14347. }
  14348. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  14349. this.attachedElement = element;
  14350. this.noPreventDefault = noPreventDefault;
  14351. for (var cam in this.attached) {
  14352. var input = this.attached[cam];
  14353. this.attached[cam].attachControl(element, noPreventDefault);
  14354. }
  14355. };
  14356. CameraInputsManager.prototype.detachElement = function (element) {
  14357. if (this.attachedElement !== element) {
  14358. return;
  14359. }
  14360. for (var cam in this.attached) {
  14361. var input = this.attached[cam];
  14362. this.attached[cam].detachControl(element);
  14363. }
  14364. this.attachedElement = null;
  14365. };
  14366. CameraInputsManager.prototype.rebuildInputCheck = function () {
  14367. this.checkInputs = function () { };
  14368. for (var cam in this.attached) {
  14369. var input = this.attached[cam];
  14370. if (input.checkInputs) {
  14371. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14372. }
  14373. }
  14374. };
  14375. CameraInputsManager.prototype.clear = function () {
  14376. if (this.attachedElement) {
  14377. this.detachElement(this.attachedElement);
  14378. }
  14379. this.attached = {};
  14380. this.attachedElement = null;
  14381. this.checkInputs = function () { };
  14382. };
  14383. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  14384. var inputs = {};
  14385. for (var cam in this.attached) {
  14386. var input = this.attached[cam];
  14387. var res = BABYLON.SerializationHelper.Serialize(input);
  14388. inputs[input.getTypeName()] = res;
  14389. }
  14390. serializedCamera.inputsmgr = inputs;
  14391. };
  14392. CameraInputsManager.prototype.parse = function (parsedCamera) {
  14393. var parsedInputs = parsedCamera.inputsmgr;
  14394. if (parsedInputs) {
  14395. this.clear();
  14396. for (var n in parsedInputs) {
  14397. var construct = BABYLON.CameraInputTypes[n];
  14398. if (construct) {
  14399. var parsedinput = parsedInputs[n];
  14400. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  14401. this.add(input);
  14402. }
  14403. }
  14404. }
  14405. else {
  14406. //2016-03-08 this part is for managing backward compatibility
  14407. for (var n in this.attached) {
  14408. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  14409. if (construct) {
  14410. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  14411. this.remove(this.attached[n]);
  14412. this.add(input);
  14413. }
  14414. }
  14415. }
  14416. };
  14417. return CameraInputsManager;
  14418. }());
  14419. BABYLON.CameraInputsManager = CameraInputsManager;
  14420. })(BABYLON || (BABYLON = {}));
  14421. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  14422. var BABYLON;
  14423. (function (BABYLON) {
  14424. var FreeCameraMouseInput = (function () {
  14425. function FreeCameraMouseInput(touchEnabled) {
  14426. if (touchEnabled === void 0) { touchEnabled = true; }
  14427. this.touchEnabled = touchEnabled;
  14428. this.buttons = [0, 1, 2];
  14429. this.angularSensibility = 2000.0;
  14430. }
  14431. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  14432. var _this = this;
  14433. var engine = this.camera.getEngine();
  14434. if (!this._pointerInput) {
  14435. this._pointerInput = function (p, s) {
  14436. var evt = p.event;
  14437. if (!_this.touchEnabled && evt.pointerType === "touch") {
  14438. return;
  14439. }
  14440. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14441. return;
  14442. }
  14443. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14444. try {
  14445. evt.srcElement.setPointerCapture(evt.pointerId);
  14446. }
  14447. catch (e) {
  14448. }
  14449. _this.previousPosition = {
  14450. x: evt.clientX,
  14451. y: evt.clientY
  14452. };
  14453. if (!noPreventDefault) {
  14454. evt.preventDefault();
  14455. element.focus();
  14456. }
  14457. }
  14458. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14459. try {
  14460. evt.srcElement.releasePointerCapture(evt.pointerId);
  14461. }
  14462. catch (e) {
  14463. }
  14464. _this.previousPosition = null;
  14465. if (!noPreventDefault) {
  14466. evt.preventDefault();
  14467. }
  14468. }
  14469. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14470. if (!_this.previousPosition || engine.isPointerLock) {
  14471. return;
  14472. }
  14473. var offsetX = evt.clientX - _this.previousPosition.x;
  14474. var offsetY = evt.clientY - _this.previousPosition.y;
  14475. if (_this.camera.getScene().useRightHandedSystem) {
  14476. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14477. }
  14478. else {
  14479. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14480. }
  14481. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14482. _this.previousPosition = {
  14483. x: evt.clientX,
  14484. y: evt.clientY
  14485. };
  14486. if (!noPreventDefault) {
  14487. evt.preventDefault();
  14488. }
  14489. }
  14490. };
  14491. }
  14492. this._onMouseMove = function (evt) {
  14493. if (!engine.isPointerLock) {
  14494. return;
  14495. }
  14496. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14497. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14498. if (_this.camera.getScene().useRightHandedSystem) {
  14499. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14500. }
  14501. else {
  14502. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14503. }
  14504. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14505. _this.previousPosition = null;
  14506. if (!noPreventDefault) {
  14507. evt.preventDefault();
  14508. }
  14509. };
  14510. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14511. element.addEventListener("mousemove", this._onMouseMove, false);
  14512. };
  14513. FreeCameraMouseInput.prototype.detachControl = function (element) {
  14514. if (this._observer && element) {
  14515. this.camera.getScene().onPointerObservable.remove(this._observer);
  14516. element.removeEventListener("mousemove", this._onMouseMove);
  14517. this._observer = null;
  14518. this._onMouseMove = null;
  14519. this.previousPosition = null;
  14520. }
  14521. };
  14522. FreeCameraMouseInput.prototype.getTypeName = function () {
  14523. return "FreeCameraMouseInput";
  14524. };
  14525. FreeCameraMouseInput.prototype.getSimpleName = function () {
  14526. return "mouse";
  14527. };
  14528. return FreeCameraMouseInput;
  14529. }());
  14530. __decorate([
  14531. BABYLON.serialize()
  14532. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  14533. __decorate([
  14534. BABYLON.serialize()
  14535. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  14536. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  14537. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  14538. })(BABYLON || (BABYLON = {}));
  14539. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  14540. var BABYLON;
  14541. (function (BABYLON) {
  14542. var FreeCameraKeyboardMoveInput = (function () {
  14543. function FreeCameraKeyboardMoveInput() {
  14544. this._keys = [];
  14545. this.keysUp = [38];
  14546. this.keysDown = [40];
  14547. this.keysLeft = [37];
  14548. this.keysRight = [39];
  14549. }
  14550. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14551. var _this = this;
  14552. if (!this._onKeyDown) {
  14553. element.tabIndex = 1;
  14554. this._onKeyDown = function (evt) {
  14555. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14556. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14557. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14558. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14559. var index = _this._keys.indexOf(evt.keyCode);
  14560. if (index === -1) {
  14561. _this._keys.push(evt.keyCode);
  14562. }
  14563. if (!noPreventDefault) {
  14564. evt.preventDefault();
  14565. }
  14566. }
  14567. };
  14568. this._onKeyUp = function (evt) {
  14569. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14570. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14571. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14572. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14573. var index = _this._keys.indexOf(evt.keyCode);
  14574. if (index >= 0) {
  14575. _this._keys.splice(index, 1);
  14576. }
  14577. if (!noPreventDefault) {
  14578. evt.preventDefault();
  14579. }
  14580. }
  14581. };
  14582. element.addEventListener("keydown", this._onKeyDown, false);
  14583. element.addEventListener("keyup", this._onKeyUp, false);
  14584. BABYLON.Tools.RegisterTopRootEvents([
  14585. { name: "blur", handler: this._onLostFocus }
  14586. ]);
  14587. }
  14588. };
  14589. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14590. if (this._onKeyDown) {
  14591. element.removeEventListener("keydown", this._onKeyDown);
  14592. element.removeEventListener("keyup", this._onKeyUp);
  14593. BABYLON.Tools.UnregisterTopRootEvents([
  14594. { name: "blur", handler: this._onLostFocus }
  14595. ]);
  14596. this._keys = [];
  14597. this._onKeyDown = null;
  14598. this._onKeyUp = null;
  14599. }
  14600. };
  14601. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14602. if (this._onKeyDown) {
  14603. var camera = this.camera;
  14604. // Keyboard
  14605. for (var index = 0; index < this._keys.length; index++) {
  14606. var keyCode = this._keys[index];
  14607. var speed = camera._computeLocalCameraSpeed();
  14608. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14609. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14610. }
  14611. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14612. camera._localDirection.copyFromFloats(0, 0, speed);
  14613. }
  14614. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14615. camera._localDirection.copyFromFloats(speed, 0, 0);
  14616. }
  14617. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14618. camera._localDirection.copyFromFloats(0, 0, -speed);
  14619. }
  14620. if (camera.getScene().useRightHandedSystem) {
  14621. camera._localDirection.z *= -1;
  14622. }
  14623. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14624. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14625. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14626. }
  14627. }
  14628. };
  14629. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14630. return "FreeCameraKeyboardMoveInput";
  14631. };
  14632. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14633. this._keys = [];
  14634. };
  14635. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14636. return "keyboard";
  14637. };
  14638. return FreeCameraKeyboardMoveInput;
  14639. }());
  14640. __decorate([
  14641. BABYLON.serialize()
  14642. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14643. __decorate([
  14644. BABYLON.serialize()
  14645. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14646. __decorate([
  14647. BABYLON.serialize()
  14648. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14649. __decorate([
  14650. BABYLON.serialize()
  14651. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14652. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14653. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14654. })(BABYLON || (BABYLON = {}));
  14655. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14656. var BABYLON;
  14657. (function (BABYLON) {
  14658. var FreeCameraTouchInput = (function () {
  14659. function FreeCameraTouchInput() {
  14660. this._offsetX = null;
  14661. this._offsetY = null;
  14662. this._pointerCount = 0;
  14663. this._pointerPressed = [];
  14664. this.touchAngularSensibility = 200000.0;
  14665. this.touchMoveSensibility = 250.0;
  14666. }
  14667. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14668. var _this = this;
  14669. var previousPosition;
  14670. if (this._pointerInput === undefined) {
  14671. this._onLostFocus = function (evt) {
  14672. _this._offsetX = null;
  14673. _this._offsetY = null;
  14674. };
  14675. this._pointerInput = function (p, s) {
  14676. var evt = p.event;
  14677. if (evt.pointerType === "mouse") {
  14678. return;
  14679. }
  14680. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14681. if (!noPreventDefault) {
  14682. evt.preventDefault();
  14683. }
  14684. _this._pointerPressed.push(evt.pointerId);
  14685. if (_this._pointerPressed.length !== 1) {
  14686. return;
  14687. }
  14688. previousPosition = {
  14689. x: evt.clientX,
  14690. y: evt.clientY
  14691. };
  14692. }
  14693. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14694. if (!noPreventDefault) {
  14695. evt.preventDefault();
  14696. }
  14697. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14698. if (index === -1) {
  14699. return;
  14700. }
  14701. _this._pointerPressed.splice(index, 1);
  14702. if (index != 0) {
  14703. return;
  14704. }
  14705. previousPosition = null;
  14706. _this._offsetX = null;
  14707. _this._offsetY = null;
  14708. }
  14709. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14710. if (!noPreventDefault) {
  14711. evt.preventDefault();
  14712. }
  14713. if (!previousPosition) {
  14714. return;
  14715. }
  14716. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14717. if (index != 0) {
  14718. return;
  14719. }
  14720. _this._offsetX = evt.clientX - previousPosition.x;
  14721. _this._offsetY = -(evt.clientY - previousPosition.y);
  14722. }
  14723. };
  14724. }
  14725. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14726. element.addEventListener("blur", this._onLostFocus);
  14727. };
  14728. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14729. if (this._pointerInput && element) {
  14730. this.camera.getScene().onPointerObservable.remove(this._observer);
  14731. this._observer = null;
  14732. element.removeEventListener("blur", this._onLostFocus);
  14733. this._onLostFocus = null;
  14734. this._pointerPressed = [];
  14735. this._offsetX = null;
  14736. this._offsetY = null;
  14737. this._pointerCount = 0;
  14738. }
  14739. };
  14740. FreeCameraTouchInput.prototype.checkInputs = function () {
  14741. if (this._offsetX) {
  14742. var camera = this.camera;
  14743. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14744. if (this._pointerPressed.length > 1) {
  14745. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14746. }
  14747. else {
  14748. var speed = camera._computeLocalCameraSpeed();
  14749. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14750. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14751. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14752. }
  14753. }
  14754. };
  14755. FreeCameraTouchInput.prototype.getTypeName = function () {
  14756. return "FreeCameraTouchInput";
  14757. };
  14758. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14759. return "touch";
  14760. };
  14761. return FreeCameraTouchInput;
  14762. }());
  14763. __decorate([
  14764. BABYLON.serialize()
  14765. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14766. __decorate([
  14767. BABYLON.serialize()
  14768. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14769. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14770. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14771. })(BABYLON || (BABYLON = {}));
  14772. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14773. var BABYLON;
  14774. (function (BABYLON) {
  14775. var FreeCameraDeviceOrientationInput = (function () {
  14776. function FreeCameraDeviceOrientationInput() {
  14777. var _this = this;
  14778. this._screenOrientationAngle = 0;
  14779. this._screenQuaternion = new BABYLON.Quaternion();
  14780. this._alpha = 0;
  14781. this._beta = 0;
  14782. this._gamma = 0;
  14783. this._orientationChanged = function () {
  14784. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14785. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14786. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14787. };
  14788. this._deviceOrientation = function (evt) {
  14789. _this._alpha = evt.alpha;
  14790. _this._beta = evt.beta;
  14791. _this._gamma = evt.gamma;
  14792. };
  14793. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14794. this._orientationChanged();
  14795. }
  14796. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14797. get: function () {
  14798. return this._camera;
  14799. },
  14800. set: function (camera) {
  14801. this._camera = camera;
  14802. if (!this._camera.rotationQuaternion)
  14803. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14804. },
  14805. enumerable: true,
  14806. configurable: true
  14807. });
  14808. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14809. window.addEventListener("orientationchange", this._orientationChanged);
  14810. window.addEventListener("deviceorientation", this._deviceOrientation);
  14811. //In certain cases, the attach control is called AFTER orientation was changed,
  14812. //So this is needed.
  14813. this._orientationChanged();
  14814. };
  14815. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14816. window.removeEventListener("orientationchange", this._orientationChanged);
  14817. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14818. };
  14819. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14820. //if no device orientation provided, don't update the rotation.
  14821. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14822. if (!this._alpha)
  14823. return;
  14824. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14825. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14826. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14827. //Mirror on XY Plane
  14828. this._camera.rotationQuaternion.z *= -1;
  14829. this._camera.rotationQuaternion.w *= -1;
  14830. };
  14831. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14832. return "FreeCameraDeviceOrientationInput";
  14833. };
  14834. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14835. return "deviceOrientation";
  14836. };
  14837. return FreeCameraDeviceOrientationInput;
  14838. }());
  14839. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14840. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14841. })(BABYLON || (BABYLON = {}));
  14842. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14843. var BABYLON;
  14844. (function (BABYLON) {
  14845. var FreeCameraGamepadInput = (function () {
  14846. function FreeCameraGamepadInput() {
  14847. this.gamepadAngularSensibility = 200;
  14848. this.gamepadMoveSensibility = 40;
  14849. }
  14850. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14851. var _this = this;
  14852. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14853. };
  14854. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14855. if (this._gamepads) {
  14856. this._gamepads.dispose();
  14857. }
  14858. this.gamepad = null;
  14859. };
  14860. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14861. if (this.gamepad) {
  14862. var camera = this.camera;
  14863. var LSValues = this.gamepad.leftStick;
  14864. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14865. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14866. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14867. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14868. var RSValues = this.gamepad.rightStick;
  14869. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14870. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14871. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14872. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14873. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14874. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14875. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14876. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14877. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14878. }
  14879. };
  14880. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14881. // Only the first gamepad can control the camera
  14882. if (gamepad.index === 0) {
  14883. this.gamepad = gamepad;
  14884. }
  14885. };
  14886. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14887. return "FreeCameraGamepadInput";
  14888. };
  14889. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14890. return "gamepad";
  14891. };
  14892. return FreeCameraGamepadInput;
  14893. }());
  14894. __decorate([
  14895. BABYLON.serialize()
  14896. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14897. __decorate([
  14898. BABYLON.serialize()
  14899. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14900. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14901. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14902. })(BABYLON || (BABYLON = {}));
  14903. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14904. var BABYLON;
  14905. (function (BABYLON) {
  14906. var ArcRotateCameraKeyboardMoveInput = (function () {
  14907. function ArcRotateCameraKeyboardMoveInput() {
  14908. this._keys = [];
  14909. this.keysUp = [38];
  14910. this.keysDown = [40];
  14911. this.keysLeft = [37];
  14912. this.keysRight = [39];
  14913. }
  14914. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14915. var _this = this;
  14916. element.tabIndex = 1;
  14917. this._onKeyDown = function (evt) {
  14918. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14919. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14920. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14921. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14922. var index = _this._keys.indexOf(evt.keyCode);
  14923. if (index === -1) {
  14924. _this._keys.push(evt.keyCode);
  14925. }
  14926. if (evt.preventDefault) {
  14927. if (!noPreventDefault) {
  14928. evt.preventDefault();
  14929. }
  14930. }
  14931. }
  14932. };
  14933. this._onKeyUp = function (evt) {
  14934. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14935. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14936. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14937. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14938. var index = _this._keys.indexOf(evt.keyCode);
  14939. if (index >= 0) {
  14940. _this._keys.splice(index, 1);
  14941. }
  14942. if (evt.preventDefault) {
  14943. if (!noPreventDefault) {
  14944. evt.preventDefault();
  14945. }
  14946. }
  14947. }
  14948. };
  14949. this._onLostFocus = function () {
  14950. _this._keys = [];
  14951. };
  14952. element.addEventListener("keydown", this._onKeyDown, false);
  14953. element.addEventListener("keyup", this._onKeyUp, false);
  14954. BABYLON.Tools.RegisterTopRootEvents([
  14955. { name: "blur", handler: this._onLostFocus }
  14956. ]);
  14957. };
  14958. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14959. if (element) {
  14960. element.removeEventListener("keydown", this._onKeyDown);
  14961. element.removeEventListener("keyup", this._onKeyUp);
  14962. }
  14963. BABYLON.Tools.UnregisterTopRootEvents([
  14964. { name: "blur", handler: this._onLostFocus }
  14965. ]);
  14966. this._keys = [];
  14967. this._onKeyDown = null;
  14968. this._onKeyUp = null;
  14969. this._onLostFocus = null;
  14970. };
  14971. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14972. if (this._onKeyDown) {
  14973. var camera = this.camera;
  14974. for (var index = 0; index < this._keys.length; index++) {
  14975. var keyCode = this._keys[index];
  14976. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14977. camera.inertialAlphaOffset -= 0.01;
  14978. }
  14979. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14980. camera.inertialBetaOffset -= 0.01;
  14981. }
  14982. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14983. camera.inertialAlphaOffset += 0.01;
  14984. }
  14985. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14986. camera.inertialBetaOffset += 0.01;
  14987. }
  14988. }
  14989. }
  14990. };
  14991. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14992. return "ArcRotateCameraKeyboardMoveInput";
  14993. };
  14994. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14995. return "keyboard";
  14996. };
  14997. return ArcRotateCameraKeyboardMoveInput;
  14998. }());
  14999. __decorate([
  15000. BABYLON.serialize()
  15001. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  15002. __decorate([
  15003. BABYLON.serialize()
  15004. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  15005. __decorate([
  15006. BABYLON.serialize()
  15007. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  15008. __decorate([
  15009. BABYLON.serialize()
  15010. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  15011. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  15012. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  15013. })(BABYLON || (BABYLON = {}));
  15014. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  15015. var BABYLON;
  15016. (function (BABYLON) {
  15017. var ArcRotateCameraMouseWheelInput = (function () {
  15018. function ArcRotateCameraMouseWheelInput() {
  15019. this.wheelPrecision = 3.0;
  15020. }
  15021. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  15022. var _this = this;
  15023. this._wheel = function (p, s) {
  15024. //sanity check - this should be a PointerWheel event.
  15025. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  15026. return;
  15027. var event = p.event;
  15028. var delta = 0;
  15029. if (event.wheelDelta) {
  15030. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  15031. }
  15032. else if (event.detail) {
  15033. delta = -event.detail / _this.wheelPrecision;
  15034. }
  15035. if (delta)
  15036. _this.camera.inertialRadiusOffset += delta;
  15037. if (event.preventDefault) {
  15038. if (!noPreventDefault) {
  15039. event.preventDefault();
  15040. }
  15041. }
  15042. };
  15043. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  15044. };
  15045. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  15046. if (this._observer && element) {
  15047. this.camera.getScene().onPointerObservable.remove(this._observer);
  15048. this._observer = null;
  15049. this._wheel = null;
  15050. }
  15051. };
  15052. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  15053. return "ArcRotateCameraMouseWheelInput";
  15054. };
  15055. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  15056. return "mousewheel";
  15057. };
  15058. return ArcRotateCameraMouseWheelInput;
  15059. }());
  15060. __decorate([
  15061. BABYLON.serialize()
  15062. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  15063. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  15064. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  15065. })(BABYLON || (BABYLON = {}));
  15066. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  15067. var BABYLON;
  15068. (function (BABYLON) {
  15069. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15070. var ArcRotateCameraPointersInput = (function () {
  15071. function ArcRotateCameraPointersInput() {
  15072. this.buttons = [0, 1, 2];
  15073. this.angularSensibilityX = 1000.0;
  15074. this.angularSensibilityY = 1000.0;
  15075. this.pinchPrecision = 6.0;
  15076. this.panningSensibility = 50.0;
  15077. this._isPanClick = false;
  15078. this.pinchInwards = true;
  15079. }
  15080. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  15081. var _this = this;
  15082. var engine = this.camera.getEngine();
  15083. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  15084. var pointA, pointB;
  15085. var previousPinchDistance = 0;
  15086. this._pointerInput = function (p, s) {
  15087. var evt = p.event;
  15088. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  15089. return;
  15090. }
  15091. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15092. try {
  15093. evt.srcElement.setPointerCapture(evt.pointerId);
  15094. }
  15095. catch (e) {
  15096. }
  15097. // Manage panning with pan button click
  15098. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  15099. // manage pointers
  15100. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  15101. if (pointA === undefined) {
  15102. pointA = cacheSoloPointer;
  15103. }
  15104. else if (pointB === undefined) {
  15105. pointB = cacheSoloPointer;
  15106. }
  15107. if (!noPreventDefault) {
  15108. evt.preventDefault();
  15109. element.focus();
  15110. }
  15111. }
  15112. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  15113. try {
  15114. evt.srcElement.releasePointerCapture(evt.pointerId);
  15115. }
  15116. catch (e) {
  15117. }
  15118. cacheSoloPointer = null;
  15119. previousPinchDistance = 0;
  15120. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  15121. //but emptying completly pointers collection is required to fix a bug on iPhone :
  15122. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  15123. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  15124. pointA = pointB = undefined;
  15125. if (!noPreventDefault) {
  15126. evt.preventDefault();
  15127. }
  15128. }
  15129. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15130. if (!noPreventDefault) {
  15131. evt.preventDefault();
  15132. }
  15133. // One button down
  15134. if (pointA && pointB === undefined) {
  15135. if (_this.panningSensibility !== 0 &&
  15136. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  15137. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  15138. _this.camera
  15139. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  15140. _this.camera
  15141. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  15142. }
  15143. else {
  15144. var offsetX = evt.clientX - cacheSoloPointer.x;
  15145. var offsetY = evt.clientY - cacheSoloPointer.y;
  15146. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15147. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15148. }
  15149. cacheSoloPointer.x = evt.clientX;
  15150. cacheSoloPointer.y = evt.clientY;
  15151. }
  15152. else if (pointA && pointB) {
  15153. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  15154. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  15155. ed.x = evt.clientX;
  15156. ed.y = evt.clientY;
  15157. var direction = _this.pinchInwards ? 1 : -1;
  15158. var distX = pointA.x - pointB.x;
  15159. var distY = pointA.y - pointB.y;
  15160. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  15161. if (previousPinchDistance === 0) {
  15162. previousPinchDistance = pinchSquaredDistance;
  15163. return;
  15164. }
  15165. if (pinchSquaredDistance !== previousPinchDistance) {
  15166. _this.camera
  15167. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  15168. (_this.pinchPrecision *
  15169. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  15170. direction);
  15171. previousPinchDistance = pinchSquaredDistance;
  15172. }
  15173. }
  15174. }
  15175. };
  15176. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  15177. this._onContextMenu = function (evt) {
  15178. evt.preventDefault();
  15179. };
  15180. if (!this.camera._useCtrlForPanning) {
  15181. element.addEventListener("contextmenu", this._onContextMenu, false);
  15182. }
  15183. this._onLostFocus = function () {
  15184. //this._keys = [];
  15185. pointA = pointB = undefined;
  15186. previousPinchDistance = 0;
  15187. cacheSoloPointer = null;
  15188. };
  15189. this._onMouseMove = function (evt) {
  15190. if (!engine.isPointerLock) {
  15191. return;
  15192. }
  15193. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  15194. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  15195. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15196. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15197. if (!noPreventDefault) {
  15198. evt.preventDefault();
  15199. }
  15200. };
  15201. this._onGestureStart = function (e) {
  15202. if (window.MSGesture === undefined) {
  15203. return;
  15204. }
  15205. if (!_this._MSGestureHandler) {
  15206. _this._MSGestureHandler = new MSGesture();
  15207. _this._MSGestureHandler.target = element;
  15208. }
  15209. _this._MSGestureHandler.addPointer(e.pointerId);
  15210. };
  15211. this._onGesture = function (e) {
  15212. _this.camera.radius *= e.scale;
  15213. if (e.preventDefault) {
  15214. if (!noPreventDefault) {
  15215. e.stopPropagation();
  15216. e.preventDefault();
  15217. }
  15218. }
  15219. };
  15220. element.addEventListener("mousemove", this._onMouseMove, false);
  15221. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  15222. element.addEventListener("MSGestureChange", this._onGesture, false);
  15223. element.addEventListener("keydown", this._onKeyDown, false);
  15224. element.addEventListener("keyup", this._onKeyUp, false);
  15225. BABYLON.Tools.RegisterTopRootEvents([
  15226. { name: "blur", handler: this._onLostFocus }
  15227. ]);
  15228. };
  15229. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  15230. if (element && this._observer) {
  15231. this.camera.getScene().onPointerObservable.remove(this._observer);
  15232. this._observer = null;
  15233. element.removeEventListener("contextmenu", this._onContextMenu);
  15234. element.removeEventListener("mousemove", this._onMouseMove);
  15235. element.removeEventListener("MSPointerDown", this._onGestureStart);
  15236. element.removeEventListener("MSGestureChange", this._onGesture);
  15237. element.removeEventListener("keydown", this._onKeyDown);
  15238. element.removeEventListener("keyup", this._onKeyUp);
  15239. this._isPanClick = false;
  15240. this.pinchInwards = true;
  15241. this._onKeyDown = null;
  15242. this._onKeyUp = null;
  15243. this._onMouseMove = null;
  15244. this._onGestureStart = null;
  15245. this._onGesture = null;
  15246. this._MSGestureHandler = null;
  15247. this._onLostFocus = null;
  15248. this._onContextMenu = null;
  15249. }
  15250. BABYLON.Tools.UnregisterTopRootEvents([
  15251. { name: "blur", handler: this._onLostFocus }
  15252. ]);
  15253. };
  15254. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  15255. return "ArcRotateCameraPointersInput";
  15256. };
  15257. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  15258. return "pointers";
  15259. };
  15260. return ArcRotateCameraPointersInput;
  15261. }());
  15262. __decorate([
  15263. BABYLON.serialize()
  15264. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  15265. __decorate([
  15266. BABYLON.serialize()
  15267. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  15268. __decorate([
  15269. BABYLON.serialize()
  15270. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  15271. __decorate([
  15272. BABYLON.serialize()
  15273. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  15274. __decorate([
  15275. BABYLON.serialize()
  15276. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  15277. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  15278. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  15279. })(BABYLON || (BABYLON = {}));
  15280. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  15281. var BABYLON;
  15282. (function (BABYLON) {
  15283. var ArcRotateCameraGamepadInput = (function () {
  15284. function ArcRotateCameraGamepadInput() {
  15285. this.gamepadRotationSensibility = 80;
  15286. this.gamepadMoveSensibility = 40;
  15287. }
  15288. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  15289. var _this = this;
  15290. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  15291. };
  15292. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  15293. if (this._gamepads) {
  15294. this._gamepads.dispose();
  15295. }
  15296. this.gamepad = null;
  15297. };
  15298. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  15299. if (this.gamepad) {
  15300. var camera = this.camera;
  15301. var RSValues = this.gamepad.rightStick;
  15302. if (RSValues.x != 0) {
  15303. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  15304. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  15305. camera.inertialAlphaOffset += normalizedRX;
  15306. }
  15307. }
  15308. if (RSValues.y != 0) {
  15309. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  15310. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  15311. camera.inertialBetaOffset += normalizedRY;
  15312. }
  15313. }
  15314. var LSValues = this.gamepad.leftStick;
  15315. if (LSValues.y != 0) {
  15316. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  15317. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  15318. this.camera.inertialRadiusOffset -= normalizedLY;
  15319. }
  15320. }
  15321. }
  15322. };
  15323. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15324. // Only the first gamepad can control the camera
  15325. if (gamepad.index === 0) {
  15326. this.gamepad = gamepad;
  15327. }
  15328. };
  15329. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  15330. return "ArcRotateCameraGamepadInput";
  15331. };
  15332. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  15333. return "gamepad";
  15334. };
  15335. return ArcRotateCameraGamepadInput;
  15336. }());
  15337. __decorate([
  15338. BABYLON.serialize()
  15339. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  15340. __decorate([
  15341. BABYLON.serialize()
  15342. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15343. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  15344. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  15345. })(BABYLON || (BABYLON = {}));
  15346. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  15347. var BABYLON;
  15348. (function (BABYLON) {
  15349. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  15350. function ArcRotateCameraVRDeviceOrientationInput() {
  15351. this.alphaCorrection = 1;
  15352. this.betaCorrection = 1;
  15353. this.gammaCorrection = 1;
  15354. this._alpha = 0;
  15355. this._beta = 0;
  15356. this._gamma = 0;
  15357. this._dirty = false;
  15358. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15359. }
  15360. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  15361. this.camera.attachControl(element, noPreventDefault);
  15362. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15363. };
  15364. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  15365. var camera = this.camera;
  15366. this._alpha = +evt.alpha | 0;
  15367. this._beta = +evt.beta | 0;
  15368. this._gamma = +evt.gamma | 0;
  15369. this._dirty = true;
  15370. };
  15371. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  15372. if (this._dirty) {
  15373. this._dirty = false;
  15374. if (this._gamma < 0) {
  15375. this._gamma = 180 + this._gamma;
  15376. }
  15377. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  15378. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  15379. }
  15380. };
  15381. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  15382. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15383. };
  15384. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  15385. return "ArcRotateCameraVRDeviceOrientationInput";
  15386. };
  15387. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  15388. return "VRDeviceOrientation";
  15389. };
  15390. return ArcRotateCameraVRDeviceOrientationInput;
  15391. }());
  15392. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  15393. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  15394. })(BABYLON || (BABYLON = {}));
  15395. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  15396. var BABYLON;
  15397. (function (BABYLON) {
  15398. var TargetCamera = (function (_super) {
  15399. __extends(TargetCamera, _super);
  15400. function TargetCamera(name, position, scene) {
  15401. var _this = _super.call(this, name, position, scene) || this;
  15402. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15403. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  15404. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  15405. _this.speed = 2.0;
  15406. _this.noRotationConstraint = false;
  15407. _this.lockedTarget = null;
  15408. _this._currentTarget = BABYLON.Vector3.Zero();
  15409. _this._viewMatrix = BABYLON.Matrix.Zero();
  15410. _this._camMatrix = BABYLON.Matrix.Zero();
  15411. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  15412. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  15413. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  15414. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  15415. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  15416. _this._lookAtTemp = BABYLON.Matrix.Zero();
  15417. _this._tempMatrix = BABYLON.Matrix.Zero();
  15418. return _this;
  15419. }
  15420. TargetCamera.prototype.getFrontPosition = function (distance) {
  15421. var direction = this.getTarget().subtract(this.position);
  15422. direction.normalize();
  15423. direction.scaleInPlace(distance);
  15424. return this.globalPosition.add(direction);
  15425. };
  15426. TargetCamera.prototype._getLockedTargetPosition = function () {
  15427. if (!this.lockedTarget) {
  15428. return null;
  15429. }
  15430. if (this.lockedTarget.absolutePosition) {
  15431. this.lockedTarget.computeWorldMatrix();
  15432. }
  15433. return this.lockedTarget.absolutePosition || this.lockedTarget;
  15434. };
  15435. // Cache
  15436. TargetCamera.prototype._initCache = function () {
  15437. _super.prototype._initCache.call(this);
  15438. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15439. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15440. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15441. };
  15442. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  15443. if (!ignoreParentClass) {
  15444. _super.prototype._updateCache.call(this);
  15445. }
  15446. var lockedTargetPosition = this._getLockedTargetPosition();
  15447. if (!lockedTargetPosition) {
  15448. this._cache.lockedTarget = null;
  15449. }
  15450. else {
  15451. if (!this._cache.lockedTarget) {
  15452. this._cache.lockedTarget = lockedTargetPosition.clone();
  15453. }
  15454. else {
  15455. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  15456. }
  15457. }
  15458. this._cache.rotation.copyFrom(this.rotation);
  15459. if (this.rotationQuaternion)
  15460. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15461. };
  15462. // Synchronized
  15463. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  15464. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  15465. return false;
  15466. }
  15467. var lockedTargetPosition = this._getLockedTargetPosition();
  15468. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  15469. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  15470. };
  15471. // Methods
  15472. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  15473. var engine = this.getEngine();
  15474. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  15475. };
  15476. // Target
  15477. TargetCamera.prototype.setTarget = function (target) {
  15478. this.upVector.normalize();
  15479. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  15480. this._camMatrix.invert();
  15481. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  15482. var vDir = target.subtract(this.position);
  15483. if (vDir.x >= 0.0) {
  15484. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  15485. }
  15486. else {
  15487. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  15488. }
  15489. this.rotation.z = 0;
  15490. if (isNaN(this.rotation.x)) {
  15491. this.rotation.x = 0;
  15492. }
  15493. if (isNaN(this.rotation.y)) {
  15494. this.rotation.y = 0;
  15495. }
  15496. if (isNaN(this.rotation.z)) {
  15497. this.rotation.z = 0;
  15498. }
  15499. if (this.rotationQuaternion) {
  15500. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  15501. }
  15502. };
  15503. TargetCamera.prototype.getTarget = function () {
  15504. return this._currentTarget;
  15505. };
  15506. TargetCamera.prototype._decideIfNeedsToMove = function () {
  15507. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15508. };
  15509. TargetCamera.prototype._updatePosition = function () {
  15510. this.position.addInPlace(this.cameraDirection);
  15511. };
  15512. TargetCamera.prototype._checkInputs = function () {
  15513. var needToMove = this._decideIfNeedsToMove();
  15514. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  15515. // Move
  15516. if (needToMove) {
  15517. this._updatePosition();
  15518. }
  15519. // Rotate
  15520. if (needToRotate) {
  15521. this.rotation.x += this.cameraRotation.x;
  15522. this.rotation.y += this.cameraRotation.y;
  15523. if (!this.noRotationConstraint) {
  15524. var limit = (Math.PI / 2) * 0.95;
  15525. if (this.rotation.x > limit)
  15526. this.rotation.x = limit;
  15527. if (this.rotation.x < -limit)
  15528. this.rotation.x = -limit;
  15529. }
  15530. }
  15531. // Inertia
  15532. if (needToMove) {
  15533. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  15534. this.cameraDirection.x = 0;
  15535. }
  15536. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  15537. this.cameraDirection.y = 0;
  15538. }
  15539. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  15540. this.cameraDirection.z = 0;
  15541. }
  15542. this.cameraDirection.scaleInPlace(this.inertia);
  15543. }
  15544. if (needToRotate) {
  15545. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  15546. this.cameraRotation.x = 0;
  15547. }
  15548. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  15549. this.cameraRotation.y = 0;
  15550. }
  15551. this.cameraRotation.scaleInPlace(this.inertia);
  15552. }
  15553. _super.prototype._checkInputs.call(this);
  15554. };
  15555. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  15556. if (this.rotationQuaternion) {
  15557. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  15558. //update the up vector!
  15559. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  15560. }
  15561. else {
  15562. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15563. }
  15564. };
  15565. TargetCamera.prototype._getViewMatrix = function () {
  15566. if (!this.lockedTarget) {
  15567. // Compute
  15568. this._updateCameraRotationMatrix();
  15569. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15570. // Computing target and final matrix
  15571. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15572. }
  15573. else {
  15574. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  15575. }
  15576. if (this.getScene().useRightHandedSystem) {
  15577. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15578. }
  15579. else {
  15580. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15581. }
  15582. return this._viewMatrix;
  15583. };
  15584. /**
  15585. * @override
  15586. * Override Camera.createRigCamera
  15587. */
  15588. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15589. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  15590. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  15591. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  15592. if (!this.rotationQuaternion) {
  15593. this.rotationQuaternion = new BABYLON.Quaternion();
  15594. }
  15595. rigCamera._cameraRigParams = {};
  15596. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15597. }
  15598. return rigCamera;
  15599. }
  15600. return null;
  15601. };
  15602. /**
  15603. * @override
  15604. * Override Camera._updateRigCameras
  15605. */
  15606. TargetCamera.prototype._updateRigCameras = function () {
  15607. var camLeft = this._rigCameras[0];
  15608. var camRight = this._rigCameras[1];
  15609. switch (this.cameraRigMode) {
  15610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15611. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15612. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15614. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15615. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15616. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15617. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15618. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15619. camLeft.setTarget(this.getTarget());
  15620. camRight.setTarget(this.getTarget());
  15621. break;
  15622. case BABYLON.Camera.RIG_MODE_VR:
  15623. case BABYLON.Camera.RIG_MODE_WEBVR:
  15624. if (camLeft.rotationQuaternion) {
  15625. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15626. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15627. }
  15628. else {
  15629. camLeft.rotation.copyFrom(this.rotation);
  15630. camRight.rotation.copyFrom(this.rotation);
  15631. }
  15632. camLeft.position.copyFrom(this.position);
  15633. camRight.position.copyFrom(this.position);
  15634. break;
  15635. }
  15636. _super.prototype._updateRigCameras.call(this);
  15637. };
  15638. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15639. if (!this._rigCamTransformMatrix) {
  15640. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15641. }
  15642. var target = this.getTarget();
  15643. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15644. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15645. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15646. };
  15647. TargetCamera.prototype.getClassName = function () {
  15648. return "TargetCamera";
  15649. };
  15650. return TargetCamera;
  15651. }(BABYLON.Camera));
  15652. __decorate([
  15653. BABYLON.serializeAsVector3()
  15654. ], TargetCamera.prototype, "rotation", void 0);
  15655. __decorate([
  15656. BABYLON.serialize()
  15657. ], TargetCamera.prototype, "speed", void 0);
  15658. __decorate([
  15659. BABYLON.serializeAsMeshReference("lockedTargetId")
  15660. ], TargetCamera.prototype, "lockedTarget", void 0);
  15661. BABYLON.TargetCamera = TargetCamera;
  15662. })(BABYLON || (BABYLON = {}));
  15663. //# sourceMappingURL=babylon.targetCamera.js.map
  15664. var BABYLON;
  15665. (function (BABYLON) {
  15666. var FreeCamera = (function (_super) {
  15667. __extends(FreeCamera, _super);
  15668. function FreeCamera(name, position, scene) {
  15669. var _this = _super.call(this, name, position, scene) || this;
  15670. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15671. _this.checkCollisions = false;
  15672. _this.applyGravity = false;
  15673. _this._collider = new BABYLON.Collider();
  15674. _this._needMoveForGravity = false;
  15675. _this._oldPosition = BABYLON.Vector3.Zero();
  15676. _this._diffPosition = BABYLON.Vector3.Zero();
  15677. _this._newPosition = BABYLON.Vector3.Zero();
  15678. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15679. if (collidedMesh === void 0) { collidedMesh = null; }
  15680. //TODO move this to the collision coordinator!
  15681. if (_this.getScene().workerCollisions)
  15682. newPosition.multiplyInPlace(_this._collider.radius);
  15683. var updatePosition = function (newPos) {
  15684. _this._newPosition.copyFrom(newPos);
  15685. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15686. var oldPosition = _this.position.clone();
  15687. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15688. _this.position.addInPlace(_this._diffPosition);
  15689. if (_this.onCollide && collidedMesh) {
  15690. _this.onCollide(collidedMesh);
  15691. }
  15692. }
  15693. };
  15694. updatePosition(newPosition);
  15695. };
  15696. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15697. _this.inputs.addKeyboard().addMouse();
  15698. return _this;
  15699. }
  15700. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15701. //-- begin properties for backward compatibility for inputs
  15702. get: function () {
  15703. var mouse = this.inputs.attached["mouse"];
  15704. if (mouse)
  15705. return mouse.angularSensibility;
  15706. },
  15707. set: function (value) {
  15708. var mouse = this.inputs.attached["mouse"];
  15709. if (mouse)
  15710. mouse.angularSensibility = value;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15716. get: function () {
  15717. var keyboard = this.inputs.attached["keyboard"];
  15718. if (keyboard)
  15719. return keyboard.keysUp;
  15720. },
  15721. set: function (value) {
  15722. var keyboard = this.inputs.attached["keyboard"];
  15723. if (keyboard)
  15724. keyboard.keysUp = value;
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15730. get: function () {
  15731. var keyboard = this.inputs.attached["keyboard"];
  15732. if (keyboard)
  15733. return keyboard.keysDown;
  15734. },
  15735. set: function (value) {
  15736. var keyboard = this.inputs.attached["keyboard"];
  15737. if (keyboard)
  15738. keyboard.keysDown = value;
  15739. },
  15740. enumerable: true,
  15741. configurable: true
  15742. });
  15743. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15744. get: function () {
  15745. var keyboard = this.inputs.attached["keyboard"];
  15746. if (keyboard)
  15747. return keyboard.keysLeft;
  15748. },
  15749. set: function (value) {
  15750. var keyboard = this.inputs.attached["keyboard"];
  15751. if (keyboard)
  15752. keyboard.keysLeft = value;
  15753. },
  15754. enumerable: true,
  15755. configurable: true
  15756. });
  15757. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15758. get: function () {
  15759. var keyboard = this.inputs.attached["keyboard"];
  15760. if (keyboard)
  15761. return keyboard.keysRight;
  15762. },
  15763. set: function (value) {
  15764. var keyboard = this.inputs.attached["keyboard"];
  15765. if (keyboard)
  15766. keyboard.keysRight = value;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. // Controls
  15772. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15773. this.inputs.attachElement(element, noPreventDefault);
  15774. };
  15775. FreeCamera.prototype.detachControl = function (element) {
  15776. this.inputs.detachElement(element);
  15777. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15778. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15779. };
  15780. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15781. var globalPosition;
  15782. if (this.parent) {
  15783. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15784. }
  15785. else {
  15786. globalPosition = this.position;
  15787. }
  15788. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15789. this._collider.radius = this.ellipsoid;
  15790. //no need for clone, as long as gravity is not on.
  15791. var actualVelocity = velocity;
  15792. //add gravity to the velocity to prevent the dual-collision checking
  15793. if (this.applyGravity) {
  15794. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15795. actualVelocity = velocity.add(this.getScene().gravity);
  15796. }
  15797. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15798. };
  15799. FreeCamera.prototype._checkInputs = function () {
  15800. if (!this._localDirection) {
  15801. this._localDirection = BABYLON.Vector3.Zero();
  15802. this._transformedDirection = BABYLON.Vector3.Zero();
  15803. }
  15804. this.inputs.checkInputs();
  15805. _super.prototype._checkInputs.call(this);
  15806. };
  15807. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15808. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15809. };
  15810. FreeCamera.prototype._updatePosition = function () {
  15811. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15812. this._collideWithWorld(this.cameraDirection);
  15813. }
  15814. else {
  15815. this.position.addInPlace(this.cameraDirection);
  15816. }
  15817. };
  15818. FreeCamera.prototype.dispose = function () {
  15819. this.inputs.clear();
  15820. _super.prototype.dispose.call(this);
  15821. };
  15822. FreeCamera.prototype.getClassName = function () {
  15823. return "FreeCamera";
  15824. };
  15825. return FreeCamera;
  15826. }(BABYLON.TargetCamera));
  15827. __decorate([
  15828. BABYLON.serializeAsVector3()
  15829. ], FreeCamera.prototype, "ellipsoid", void 0);
  15830. __decorate([
  15831. BABYLON.serialize()
  15832. ], FreeCamera.prototype, "checkCollisions", void 0);
  15833. __decorate([
  15834. BABYLON.serialize()
  15835. ], FreeCamera.prototype, "applyGravity", void 0);
  15836. BABYLON.FreeCamera = FreeCamera;
  15837. })(BABYLON || (BABYLON = {}));
  15838. //# sourceMappingURL=babylon.freeCamera.js.map
  15839. var BABYLON;
  15840. (function (BABYLON) {
  15841. var FreeCameraInputsManager = (function (_super) {
  15842. __extends(FreeCameraInputsManager, _super);
  15843. function FreeCameraInputsManager(camera) {
  15844. return _super.call(this, camera) || this;
  15845. }
  15846. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15847. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15848. return this;
  15849. };
  15850. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15851. if (touchEnabled === void 0) { touchEnabled = true; }
  15852. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15853. return this;
  15854. };
  15855. FreeCameraInputsManager.prototype.addGamepad = function () {
  15856. this.add(new BABYLON.FreeCameraGamepadInput());
  15857. return this;
  15858. };
  15859. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15860. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15861. return this;
  15862. };
  15863. FreeCameraInputsManager.prototype.addTouch = function () {
  15864. this.add(new BABYLON.FreeCameraTouchInput());
  15865. return this;
  15866. };
  15867. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15868. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15869. return this;
  15870. };
  15871. return FreeCameraInputsManager;
  15872. }(BABYLON.CameraInputsManager));
  15873. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15874. })(BABYLON || (BABYLON = {}));
  15875. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15876. var BABYLON;
  15877. (function (BABYLON) {
  15878. var FollowCamera = (function (_super) {
  15879. __extends(FollowCamera, _super);
  15880. function FollowCamera(name, position, scene, lockedTarget) {
  15881. var _this = _super.call(this, name, position, scene) || this;
  15882. _this.radius = 12;
  15883. _this.rotationOffset = 0;
  15884. _this.heightOffset = 4;
  15885. _this.cameraAcceleration = 0.05;
  15886. _this.maxCameraSpeed = 20;
  15887. _this.lockedTarget = lockedTarget;
  15888. return _this;
  15889. }
  15890. FollowCamera.prototype.getRadians = function (degrees) {
  15891. return degrees * Math.PI / 180;
  15892. };
  15893. FollowCamera.prototype.follow = function (cameraTarget) {
  15894. if (!cameraTarget)
  15895. return;
  15896. var yRotation;
  15897. if (cameraTarget.rotationQuaternion) {
  15898. var rotMatrix = new BABYLON.Matrix();
  15899. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15900. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15901. }
  15902. else {
  15903. yRotation = cameraTarget.rotation.y;
  15904. }
  15905. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15906. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15907. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15908. var dx = targetX - this.position.x;
  15909. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15910. var dz = (targetZ) - this.position.z;
  15911. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15912. var vy = dy * this.cameraAcceleration;
  15913. var vz = dz * this.cameraAcceleration * 2;
  15914. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15915. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15916. }
  15917. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15918. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15919. }
  15920. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15921. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15922. }
  15923. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15924. this.setTarget(cameraTarget.position);
  15925. };
  15926. FollowCamera.prototype._checkInputs = function () {
  15927. _super.prototype._checkInputs.call(this);
  15928. this.follow(this.lockedTarget);
  15929. };
  15930. FollowCamera.prototype.getClassName = function () {
  15931. return "FollowCamera";
  15932. };
  15933. return FollowCamera;
  15934. }(BABYLON.TargetCamera));
  15935. __decorate([
  15936. BABYLON.serialize()
  15937. ], FollowCamera.prototype, "radius", void 0);
  15938. __decorate([
  15939. BABYLON.serialize()
  15940. ], FollowCamera.prototype, "rotationOffset", void 0);
  15941. __decorate([
  15942. BABYLON.serialize()
  15943. ], FollowCamera.prototype, "heightOffset", void 0);
  15944. __decorate([
  15945. BABYLON.serialize()
  15946. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15947. __decorate([
  15948. BABYLON.serialize()
  15949. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15950. __decorate([
  15951. BABYLON.serializeAsMeshReference("lockedTargetId")
  15952. ], FollowCamera.prototype, "lockedTarget", void 0);
  15953. BABYLON.FollowCamera = FollowCamera;
  15954. var ArcFollowCamera = (function (_super) {
  15955. __extends(ArcFollowCamera, _super);
  15956. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15957. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15958. _this.alpha = alpha;
  15959. _this.beta = beta;
  15960. _this.radius = radius;
  15961. _this.target = target;
  15962. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15963. _this.follow();
  15964. return _this;
  15965. }
  15966. ArcFollowCamera.prototype.follow = function () {
  15967. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15968. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15969. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15970. this.position = this.target.position.add(this._cartesianCoordinates);
  15971. this.setTarget(this.target.position);
  15972. };
  15973. ArcFollowCamera.prototype._checkInputs = function () {
  15974. _super.prototype._checkInputs.call(this);
  15975. this.follow();
  15976. };
  15977. ArcFollowCamera.prototype.getClassName = function () {
  15978. return "ArcFollowCamera";
  15979. };
  15980. return ArcFollowCamera;
  15981. }(BABYLON.TargetCamera));
  15982. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15983. })(BABYLON || (BABYLON = {}));
  15984. //# sourceMappingURL=babylon.followCamera.js.map
  15985. var BABYLON;
  15986. (function (BABYLON) {
  15987. // We're mainly based on the logic defined into the FreeCamera code
  15988. var TouchCamera = (function (_super) {
  15989. __extends(TouchCamera, _super);
  15990. //-- end properties for backward compatibility for inputs
  15991. function TouchCamera(name, position, scene) {
  15992. var _this = _super.call(this, name, position, scene) || this;
  15993. _this.inputs.addTouch();
  15994. _this._setupInputs();
  15995. return _this;
  15996. }
  15997. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15998. //-- Begin properties for backward compatibility for inputs
  15999. get: function () {
  16000. var touch = this.inputs.attached["touch"];
  16001. if (touch)
  16002. return touch.touchAngularSensibility;
  16003. },
  16004. set: function (value) {
  16005. var touch = this.inputs.attached["touch"];
  16006. if (touch)
  16007. touch.touchAngularSensibility = value;
  16008. },
  16009. enumerable: true,
  16010. configurable: true
  16011. });
  16012. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  16013. get: function () {
  16014. var touch = this.inputs.attached["touch"];
  16015. if (touch)
  16016. return touch.touchMoveSensibility;
  16017. },
  16018. set: function (value) {
  16019. var touch = this.inputs.attached["touch"];
  16020. if (touch)
  16021. touch.touchMoveSensibility = value;
  16022. },
  16023. enumerable: true,
  16024. configurable: true
  16025. });
  16026. TouchCamera.prototype.getClassName = function () {
  16027. return "TouchCamera";
  16028. };
  16029. TouchCamera.prototype._setupInputs = function () {
  16030. var mouse = this.inputs.attached["mouse"];
  16031. if (mouse) {
  16032. mouse.touchEnabled = false;
  16033. }
  16034. };
  16035. return TouchCamera;
  16036. }(BABYLON.FreeCamera));
  16037. BABYLON.TouchCamera = TouchCamera;
  16038. })(BABYLON || (BABYLON = {}));
  16039. //# sourceMappingURL=babylon.touchCamera.js.map
  16040. var BABYLON;
  16041. (function (BABYLON) {
  16042. var ArcRotateCamera = (function (_super) {
  16043. __extends(ArcRotateCamera, _super);
  16044. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  16045. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  16046. _this.inertialAlphaOffset = 0;
  16047. _this.inertialBetaOffset = 0;
  16048. _this.inertialRadiusOffset = 0;
  16049. _this.lowerAlphaLimit = null;
  16050. _this.upperAlphaLimit = null;
  16051. _this.lowerBetaLimit = 0.01;
  16052. _this.upperBetaLimit = Math.PI;
  16053. _this.lowerRadiusLimit = null;
  16054. _this.upperRadiusLimit = null;
  16055. _this.inertialPanningX = 0;
  16056. _this.inertialPanningY = 0;
  16057. //-- end properties for backward compatibility for inputs
  16058. _this.zoomOnFactor = 1;
  16059. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  16060. _this.allowUpsideDown = true;
  16061. _this._viewMatrix = new BABYLON.Matrix();
  16062. // Panning
  16063. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  16064. _this.checkCollisions = false;
  16065. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16066. _this._collider = new BABYLON.Collider();
  16067. _this._previousPosition = BABYLON.Vector3.Zero();
  16068. _this._collisionVelocity = BABYLON.Vector3.Zero();
  16069. _this._newPosition = BABYLON.Vector3.Zero();
  16070. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16071. if (collidedMesh === void 0) { collidedMesh = null; }
  16072. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  16073. newPosition.multiplyInPlace(_this._collider.radius);
  16074. }
  16075. if (!collidedMesh) {
  16076. _this._previousPosition.copyFrom(_this.position);
  16077. }
  16078. else {
  16079. _this.setPosition(newPosition);
  16080. if (_this.onCollide) {
  16081. _this.onCollide(collidedMesh);
  16082. }
  16083. }
  16084. // Recompute because of constraints
  16085. var cosa = Math.cos(_this.alpha);
  16086. var sina = Math.sin(_this.alpha);
  16087. var cosb = Math.cos(_this.beta);
  16088. var sinb = Math.sin(_this.beta);
  16089. if (sinb === 0) {
  16090. sinb = 0.0001;
  16091. }
  16092. var target = _this._getTargetPosition();
  16093. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  16094. _this.position.copyFrom(_this._newPosition);
  16095. var up = _this.upVector;
  16096. if (_this.allowUpsideDown && _this.beta < 0) {
  16097. up = up.clone();
  16098. up = up.negate();
  16099. }
  16100. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  16101. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  16102. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  16103. _this._collisionTriggered = false;
  16104. };
  16105. if (!target) {
  16106. _this.target = BABYLON.Vector3.Zero();
  16107. }
  16108. else {
  16109. _this.target = target;
  16110. }
  16111. _this.alpha = alpha;
  16112. _this.beta = beta;
  16113. _this.radius = radius;
  16114. _this.getViewMatrix();
  16115. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  16116. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  16117. return _this;
  16118. }
  16119. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  16120. //-- begin properties for backward compatibility for inputs
  16121. get: function () {
  16122. var pointers = this.inputs.attached["pointers"];
  16123. if (pointers)
  16124. return pointers.angularSensibilityX;
  16125. },
  16126. set: function (value) {
  16127. var pointers = this.inputs.attached["pointers"];
  16128. if (pointers) {
  16129. pointers.angularSensibilityX = value;
  16130. }
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  16136. get: function () {
  16137. var pointers = this.inputs.attached["pointers"];
  16138. if (pointers)
  16139. return pointers.angularSensibilityY;
  16140. },
  16141. set: function (value) {
  16142. var pointers = this.inputs.attached["pointers"];
  16143. if (pointers) {
  16144. pointers.angularSensibilityY = value;
  16145. }
  16146. },
  16147. enumerable: true,
  16148. configurable: true
  16149. });
  16150. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  16151. get: function () {
  16152. var pointers = this.inputs.attached["pointers"];
  16153. if (pointers)
  16154. return pointers.pinchPrecision;
  16155. },
  16156. set: function (value) {
  16157. var pointers = this.inputs.attached["pointers"];
  16158. if (pointers) {
  16159. pointers.pinchPrecision = value;
  16160. }
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  16166. get: function () {
  16167. var pointers = this.inputs.attached["pointers"];
  16168. if (pointers)
  16169. return pointers.panningSensibility;
  16170. },
  16171. set: function (value) {
  16172. var pointers = this.inputs.attached["pointers"];
  16173. if (pointers) {
  16174. pointers.panningSensibility = value;
  16175. }
  16176. },
  16177. enumerable: true,
  16178. configurable: true
  16179. });
  16180. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  16181. get: function () {
  16182. var keyboard = this.inputs.attached["keyboard"];
  16183. if (keyboard)
  16184. return keyboard.keysUp;
  16185. },
  16186. set: function (value) {
  16187. var keyboard = this.inputs.attached["keyboard"];
  16188. if (keyboard)
  16189. keyboard.keysUp = value;
  16190. },
  16191. enumerable: true,
  16192. configurable: true
  16193. });
  16194. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  16195. get: function () {
  16196. var keyboard = this.inputs.attached["keyboard"];
  16197. if (keyboard)
  16198. return keyboard.keysDown;
  16199. },
  16200. set: function (value) {
  16201. var keyboard = this.inputs.attached["keyboard"];
  16202. if (keyboard)
  16203. keyboard.keysDown = value;
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  16209. get: function () {
  16210. var keyboard = this.inputs.attached["keyboard"];
  16211. if (keyboard)
  16212. return keyboard.keysLeft;
  16213. },
  16214. set: function (value) {
  16215. var keyboard = this.inputs.attached["keyboard"];
  16216. if (keyboard)
  16217. keyboard.keysLeft = value;
  16218. },
  16219. enumerable: true,
  16220. configurable: true
  16221. });
  16222. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  16223. get: function () {
  16224. var keyboard = this.inputs.attached["keyboard"];
  16225. if (keyboard)
  16226. return keyboard.keysRight;
  16227. },
  16228. set: function (value) {
  16229. var keyboard = this.inputs.attached["keyboard"];
  16230. if (keyboard)
  16231. keyboard.keysRight = value;
  16232. },
  16233. enumerable: true,
  16234. configurable: true
  16235. });
  16236. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  16237. get: function () {
  16238. var mousewheel = this.inputs.attached["mousewheel"];
  16239. if (mousewheel)
  16240. return mousewheel.wheelPrecision;
  16241. },
  16242. set: function (value) {
  16243. var mousewheel = this.inputs.attached["mousewheel"];
  16244. if (mousewheel)
  16245. mousewheel.wheelPrecision = value;
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. // Cache
  16251. ArcRotateCamera.prototype._initCache = function () {
  16252. _super.prototype._initCache.call(this);
  16253. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16254. this._cache.alpha = undefined;
  16255. this._cache.beta = undefined;
  16256. this._cache.radius = undefined;
  16257. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  16258. };
  16259. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  16260. if (!ignoreParentClass) {
  16261. _super.prototype._updateCache.call(this);
  16262. }
  16263. this._cache.target.copyFrom(this._getTargetPosition());
  16264. this._cache.alpha = this.alpha;
  16265. this._cache.beta = this.beta;
  16266. this._cache.radius = this.radius;
  16267. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  16268. };
  16269. ArcRotateCamera.prototype._getTargetPosition = function () {
  16270. if (this.target.getAbsolutePosition) {
  16271. var pos = this.target.getAbsolutePosition();
  16272. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  16273. }
  16274. return this.target;
  16275. };
  16276. // Synchronized
  16277. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  16278. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  16279. return false;
  16280. return this._cache.target.equals(this.target)
  16281. && this._cache.alpha === this.alpha
  16282. && this._cache.beta === this.beta
  16283. && this._cache.radius === this.radius
  16284. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  16285. };
  16286. // Methods
  16287. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  16288. var _this = this;
  16289. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  16290. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  16291. this._useCtrlForPanning = useCtrlForPanning;
  16292. this._panningMouseButton = panningMouseButton;
  16293. this.inputs.attachElement(element, noPreventDefault);
  16294. this._reset = function () {
  16295. _this.inertialAlphaOffset = 0;
  16296. _this.inertialBetaOffset = 0;
  16297. _this.inertialRadiusOffset = 0;
  16298. };
  16299. };
  16300. ArcRotateCamera.prototype.detachControl = function (element) {
  16301. this.inputs.detachElement(element);
  16302. if (this._reset) {
  16303. this._reset();
  16304. }
  16305. };
  16306. ArcRotateCamera.prototype._checkInputs = function () {
  16307. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  16308. if (this._collisionTriggered) {
  16309. return;
  16310. }
  16311. this.inputs.checkInputs();
  16312. // Inertia
  16313. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  16314. if (this.getScene().useRightHandedSystem) {
  16315. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16316. }
  16317. else {
  16318. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16319. }
  16320. this.beta += this.inertialBetaOffset;
  16321. this.radius -= this.inertialRadiusOffset;
  16322. this.inertialAlphaOffset *= this.inertia;
  16323. this.inertialBetaOffset *= this.inertia;
  16324. this.inertialRadiusOffset *= this.inertia;
  16325. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  16326. this.inertialAlphaOffset = 0;
  16327. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  16328. this.inertialBetaOffset = 0;
  16329. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  16330. this.inertialRadiusOffset = 0;
  16331. }
  16332. // Panning inertia
  16333. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  16334. if (!this._localDirection) {
  16335. this._localDirection = BABYLON.Vector3.Zero();
  16336. this._transformedDirection = BABYLON.Vector3.Zero();
  16337. }
  16338. this.inertialPanningX *= this.inertia;
  16339. this.inertialPanningY *= this.inertia;
  16340. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  16341. this.inertialPanningX = 0;
  16342. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  16343. this.inertialPanningY = 0;
  16344. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  16345. this._localDirection.multiplyInPlace(this.panningAxis);
  16346. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  16347. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  16348. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  16349. if (!this.panningAxis.y) {
  16350. this._transformedDirection.y = 0;
  16351. }
  16352. if (!this.target.getAbsolutePosition) {
  16353. this.target.addInPlace(this._transformedDirection);
  16354. }
  16355. }
  16356. // Limits
  16357. this._checkLimits();
  16358. _super.prototype._checkInputs.call(this);
  16359. };
  16360. ArcRotateCamera.prototype._checkLimits = function () {
  16361. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  16362. if (this.allowUpsideDown && this.beta > Math.PI) {
  16363. this.beta = this.beta - (2 * Math.PI);
  16364. }
  16365. }
  16366. else {
  16367. if (this.beta < this.lowerBetaLimit) {
  16368. this.beta = this.lowerBetaLimit;
  16369. }
  16370. }
  16371. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  16372. if (this.allowUpsideDown && this.beta < -Math.PI) {
  16373. this.beta = this.beta + (2 * Math.PI);
  16374. }
  16375. }
  16376. else {
  16377. if (this.beta > this.upperBetaLimit) {
  16378. this.beta = this.upperBetaLimit;
  16379. }
  16380. }
  16381. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  16382. this.alpha = this.lowerAlphaLimit;
  16383. }
  16384. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  16385. this.alpha = this.upperAlphaLimit;
  16386. }
  16387. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  16388. this.radius = this.lowerRadiusLimit;
  16389. }
  16390. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  16391. this.radius = this.upperRadiusLimit;
  16392. }
  16393. };
  16394. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  16395. var radiusv3 = this.position.subtract(this._getTargetPosition());
  16396. this.radius = radiusv3.length();
  16397. // Alpha
  16398. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  16399. if (radiusv3.z < 0) {
  16400. this.alpha = 2 * Math.PI - this.alpha;
  16401. }
  16402. // Beta
  16403. this.beta = Math.acos(radiusv3.y / this.radius);
  16404. this._checkLimits();
  16405. };
  16406. ArcRotateCamera.prototype.setPosition = function (position) {
  16407. if (this.position.equals(position)) {
  16408. return;
  16409. }
  16410. this.position.copyFrom(position);
  16411. this.rebuildAnglesAndRadius();
  16412. };
  16413. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  16414. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  16415. if (this._getTargetPosition().equals(target)) {
  16416. return;
  16417. }
  16418. if (toBoundingCenter && target.getBoundingInfo) {
  16419. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  16420. }
  16421. else {
  16422. this._targetBoundingCenter = null;
  16423. }
  16424. this.target = target;
  16425. this.rebuildAnglesAndRadius();
  16426. };
  16427. ArcRotateCamera.prototype._getViewMatrix = function () {
  16428. // Compute
  16429. var cosa = Math.cos(this.alpha);
  16430. var sina = Math.sin(this.alpha);
  16431. var cosb = Math.cos(this.beta);
  16432. var sinb = Math.sin(this.beta);
  16433. if (sinb === 0) {
  16434. sinb = 0.0001;
  16435. }
  16436. var target = this._getTargetPosition();
  16437. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  16438. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  16439. this._collider.radius = this.collisionRadius;
  16440. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  16441. this._collisionTriggered = true;
  16442. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  16443. }
  16444. else {
  16445. this.position.copyFrom(this._newPosition);
  16446. var up = this.upVector;
  16447. if (this.allowUpsideDown && this.beta < 0) {
  16448. up = up.clone();
  16449. up = up.negate();
  16450. }
  16451. if (this.getScene().useRightHandedSystem) {
  16452. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  16453. }
  16454. else {
  16455. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  16456. }
  16457. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  16458. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  16459. }
  16460. this._currentTarget = target;
  16461. return this._viewMatrix;
  16462. };
  16463. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  16464. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16465. meshes = meshes || this.getScene().meshes;
  16466. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  16467. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  16468. this.radius = distance * this.zoomOnFactor;
  16469. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  16470. };
  16471. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  16472. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16473. var meshesOrMinMaxVector;
  16474. var distance;
  16475. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  16476. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  16477. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  16478. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  16479. }
  16480. else {
  16481. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  16482. distance = meshesOrMinMaxVectorAndDistance.distance;
  16483. }
  16484. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  16485. if (!doNotUpdateMaxZ) {
  16486. this.maxZ = distance * 2;
  16487. }
  16488. };
  16489. /**
  16490. * @override
  16491. * Override Camera.createRigCamera
  16492. */
  16493. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  16494. var alphaShift;
  16495. switch (this.cameraRigMode) {
  16496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16499. case BABYLON.Camera.RIG_MODE_VR:
  16500. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  16501. break;
  16502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16503. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  16504. break;
  16505. }
  16506. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  16507. rigCam._cameraRigParams = {};
  16508. return rigCam;
  16509. };
  16510. /**
  16511. * @override
  16512. * Override Camera._updateRigCameras
  16513. */
  16514. ArcRotateCamera.prototype._updateRigCameras = function () {
  16515. var camLeft = this._rigCameras[0];
  16516. var camRight = this._rigCameras[1];
  16517. camLeft.beta = camRight.beta = this.beta;
  16518. camLeft.radius = camRight.radius = this.radius;
  16519. switch (this.cameraRigMode) {
  16520. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16521. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16522. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16523. case BABYLON.Camera.RIG_MODE_VR:
  16524. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16525. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16526. break;
  16527. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16528. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16529. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16530. break;
  16531. }
  16532. _super.prototype._updateRigCameras.call(this);
  16533. };
  16534. ArcRotateCamera.prototype.dispose = function () {
  16535. this.inputs.clear();
  16536. _super.prototype.dispose.call(this);
  16537. };
  16538. ArcRotateCamera.prototype.getClassName = function () {
  16539. return "ArcRotateCamera";
  16540. };
  16541. return ArcRotateCamera;
  16542. }(BABYLON.TargetCamera));
  16543. __decorate([
  16544. BABYLON.serialize()
  16545. ], ArcRotateCamera.prototype, "alpha", void 0);
  16546. __decorate([
  16547. BABYLON.serialize()
  16548. ], ArcRotateCamera.prototype, "beta", void 0);
  16549. __decorate([
  16550. BABYLON.serialize()
  16551. ], ArcRotateCamera.prototype, "radius", void 0);
  16552. __decorate([
  16553. BABYLON.serializeAsVector3()
  16554. ], ArcRotateCamera.prototype, "target", void 0);
  16555. __decorate([
  16556. BABYLON.serialize()
  16557. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  16558. __decorate([
  16559. BABYLON.serialize()
  16560. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  16561. __decorate([
  16562. BABYLON.serialize()
  16563. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  16564. __decorate([
  16565. BABYLON.serialize()
  16566. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  16567. __decorate([
  16568. BABYLON.serialize()
  16569. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  16570. __decorate([
  16571. BABYLON.serialize()
  16572. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  16573. __decorate([
  16574. BABYLON.serialize()
  16575. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  16576. __decorate([
  16577. BABYLON.serialize()
  16578. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  16579. __decorate([
  16580. BABYLON.serialize()
  16581. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  16582. __decorate([
  16583. BABYLON.serialize()
  16584. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  16585. __decorate([
  16586. BABYLON.serialize()
  16587. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  16588. __decorate([
  16589. BABYLON.serialize()
  16590. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  16591. __decorate([
  16592. BABYLON.serialize()
  16593. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16594. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16595. })(BABYLON || (BABYLON = {}));
  16596. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16597. var BABYLON;
  16598. (function (BABYLON) {
  16599. var ArcRotateCameraInputsManager = (function (_super) {
  16600. __extends(ArcRotateCameraInputsManager, _super);
  16601. function ArcRotateCameraInputsManager(camera) {
  16602. return _super.call(this, camera) || this;
  16603. }
  16604. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16605. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16606. return this;
  16607. };
  16608. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16609. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16610. return this;
  16611. };
  16612. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16613. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16614. return this;
  16615. };
  16616. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16617. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16618. return this;
  16619. };
  16620. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16621. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16622. return this;
  16623. };
  16624. return ArcRotateCameraInputsManager;
  16625. }(BABYLON.CameraInputsManager));
  16626. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16627. })(BABYLON || (BABYLON = {}));
  16628. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16629. var BABYLON;
  16630. (function (BABYLON) {
  16631. var RenderingManager = (function () {
  16632. function RenderingManager(scene) {
  16633. this._renderingGroups = new Array();
  16634. this._autoClearDepthStencil = {};
  16635. this._customOpaqueSortCompareFn = {};
  16636. this._customAlphaTestSortCompareFn = {};
  16637. this._customTransparentSortCompareFn = {};
  16638. this._renderinGroupInfo = null;
  16639. this._scene = scene;
  16640. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16641. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16642. }
  16643. }
  16644. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16645. if (depth === void 0) { depth = true; }
  16646. if (stencil === void 0) { stencil = true; }
  16647. if (this._depthStencilBufferAlreadyCleaned) {
  16648. return;
  16649. }
  16650. this._scene.getEngine().clear(null, false, depth, stencil);
  16651. this._depthStencilBufferAlreadyCleaned = true;
  16652. };
  16653. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16654. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16655. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16656. var info = null;
  16657. if (observable) {
  16658. if (!this._renderinGroupInfo) {
  16659. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16660. }
  16661. info = this._renderinGroupInfo;
  16662. info.scene = this._scene;
  16663. info.camera = this._scene.activeCamera;
  16664. }
  16665. // Dispatch sprites
  16666. if (renderSprites) {
  16667. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16668. var manager = this._scene.spriteManagers[index];
  16669. this.dispatchSprites(manager);
  16670. }
  16671. }
  16672. // Render
  16673. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16674. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16675. var renderingGroup = this._renderingGroups[index];
  16676. if (!renderingGroup && !observable)
  16677. continue;
  16678. this._currentIndex = index;
  16679. var renderingGroupMask = 0;
  16680. // Fire PRECLEAR stage
  16681. if (observable) {
  16682. renderingGroupMask = Math.pow(2, index);
  16683. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16684. info.renderingGroupId = index;
  16685. observable.notifyObservers(info, renderingGroupMask);
  16686. }
  16687. // Clear depth/stencil if needed
  16688. var autoClear = this._autoClearDepthStencil[index];
  16689. if (autoClear && autoClear.autoClear) {
  16690. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16691. }
  16692. if (observable) {
  16693. // Fire PREOPAQUE stage
  16694. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16695. observable.notifyObservers(info, renderingGroupMask);
  16696. // Fire PRETRANSPARENT stage
  16697. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16698. observable.notifyObservers(info, renderingGroupMask);
  16699. }
  16700. if (renderingGroup)
  16701. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16702. // Fire POSTTRANSPARENT stage
  16703. if (observable) {
  16704. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16705. observable.notifyObservers(info, renderingGroupMask);
  16706. }
  16707. }
  16708. };
  16709. RenderingManager.prototype.reset = function () {
  16710. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16711. var renderingGroup = this._renderingGroups[index];
  16712. if (renderingGroup) {
  16713. renderingGroup.prepare();
  16714. }
  16715. }
  16716. };
  16717. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16718. if (!this._renderingGroups[renderingGroupId]) {
  16719. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16720. }
  16721. };
  16722. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16723. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16724. this._prepareRenderingGroup(renderingGroupId);
  16725. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16726. };
  16727. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16728. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16729. this._prepareRenderingGroup(renderingGroupId);
  16730. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16731. };
  16732. RenderingManager.prototype.dispatch = function (subMesh) {
  16733. var mesh = subMesh.getMesh();
  16734. var renderingGroupId = mesh.renderingGroupId || 0;
  16735. this._prepareRenderingGroup(renderingGroupId);
  16736. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16737. };
  16738. /**
  16739. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16740. * This allowed control for front to back rendering or reversly depending of the special needs.
  16741. *
  16742. * @param renderingGroupId The rendering group id corresponding to its index
  16743. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16744. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16745. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16746. */
  16747. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16748. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16749. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16750. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16751. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16752. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16753. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16754. if (this._renderingGroups[renderingGroupId]) {
  16755. var group = this._renderingGroups[renderingGroupId];
  16756. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16757. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16758. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16759. }
  16760. };
  16761. /**
  16762. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16763. *
  16764. * @param renderingGroupId The rendering group id corresponding to its index
  16765. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16766. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16767. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16768. */
  16769. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16770. if (depth === void 0) { depth = true; }
  16771. if (stencil === void 0) { stencil = true; }
  16772. this._autoClearDepthStencil[renderingGroupId] = {
  16773. autoClear: autoClearDepthStencil,
  16774. depth: depth,
  16775. stencil: stencil
  16776. };
  16777. };
  16778. return RenderingManager;
  16779. }());
  16780. /**
  16781. * The max id used for rendering groups (not included)
  16782. */
  16783. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16784. /**
  16785. * The min id used for rendering groups (included)
  16786. */
  16787. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16788. BABYLON.RenderingManager = RenderingManager;
  16789. })(BABYLON || (BABYLON = {}));
  16790. //# sourceMappingURL=babylon.renderingManager.js.map
  16791. var BABYLON;
  16792. (function (BABYLON) {
  16793. var RenderingGroup = (function () {
  16794. /**
  16795. * Creates a new rendering group.
  16796. * @param index The rendering group index
  16797. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16798. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16799. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16800. */
  16801. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16802. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16803. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16804. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16805. this.index = index;
  16806. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16807. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16808. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16809. this._particleSystems = new BABYLON.SmartArray(256);
  16810. this._spriteManagers = new BABYLON.SmartArray(256);
  16811. this._scene = scene;
  16812. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16813. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16814. this.transparentSortCompareFn = transparentSortCompareFn;
  16815. }
  16816. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16817. /**
  16818. * Set the opaque sort comparison function.
  16819. * If null the sub meshes will be render in the order they were created
  16820. */
  16821. set: function (value) {
  16822. this._opaqueSortCompareFn = value;
  16823. if (value) {
  16824. this._renderOpaque = this.renderOpaqueSorted;
  16825. }
  16826. else {
  16827. this._renderOpaque = RenderingGroup.renderUnsorted;
  16828. }
  16829. },
  16830. enumerable: true,
  16831. configurable: true
  16832. });
  16833. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16834. /**
  16835. * Set the alpha test sort comparison function.
  16836. * If null the sub meshes will be render in the order they were created
  16837. */
  16838. set: function (value) {
  16839. this._alphaTestSortCompareFn = value;
  16840. if (value) {
  16841. this._renderAlphaTest = this.renderAlphaTestSorted;
  16842. }
  16843. else {
  16844. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16845. }
  16846. },
  16847. enumerable: true,
  16848. configurable: true
  16849. });
  16850. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16851. /**
  16852. * Set the transparent sort comparison function.
  16853. * If null the sub meshes will be render in the order they were created
  16854. */
  16855. set: function (value) {
  16856. if (value) {
  16857. this._transparentSortCompareFn = value;
  16858. }
  16859. else {
  16860. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16861. }
  16862. this._renderTransparent = this.renderTransparentSorted;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. /**
  16868. * Render all the sub meshes contained in the group.
  16869. * @param customRenderFunction Used to override the default render behaviour of the group.
  16870. * @returns true if rendered some submeshes.
  16871. */
  16872. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16873. if (customRenderFunction) {
  16874. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16875. return;
  16876. }
  16877. var engine = this._scene.getEngine();
  16878. // Opaque
  16879. if (this._opaqueSubMeshes.length !== 0) {
  16880. this._renderOpaque(this._opaqueSubMeshes);
  16881. }
  16882. // Alpha test
  16883. if (this._alphaTestSubMeshes.length !== 0) {
  16884. engine.setAlphaTesting(true);
  16885. this._renderAlphaTest(this._alphaTestSubMeshes);
  16886. engine.setAlphaTesting(false);
  16887. }
  16888. // Sprites
  16889. if (renderSprites) {
  16890. this._renderSprites();
  16891. }
  16892. // Particles
  16893. if (renderParticles) {
  16894. this._renderParticles(activeMeshes);
  16895. }
  16896. if (this.onBeforeTransparentRendering) {
  16897. this.onBeforeTransparentRendering();
  16898. }
  16899. // Transparent
  16900. if (this._transparentSubMeshes.length !== 0) {
  16901. this._renderTransparent(this._transparentSubMeshes);
  16902. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16903. }
  16904. };
  16905. /**
  16906. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16907. * @param subMeshes The submeshes to render
  16908. */
  16909. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16910. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16911. };
  16912. /**
  16913. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16914. * @param subMeshes The submeshes to render
  16915. */
  16916. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16917. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16918. };
  16919. /**
  16920. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16921. * @param subMeshes The submeshes to render
  16922. */
  16923. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16924. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16925. };
  16926. /**
  16927. * Renders the submeshes in a specified order.
  16928. * @param subMeshes The submeshes to sort before render
  16929. * @param sortCompareFn The comparison function use to sort
  16930. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16931. * @param transparent Specifies to activate blending if true
  16932. */
  16933. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16934. var subIndex = 0;
  16935. var subMesh;
  16936. for (; subIndex < subMeshes.length; subIndex++) {
  16937. subMesh = subMeshes.data[subIndex];
  16938. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16939. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16940. }
  16941. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16942. sortedArray.sort(sortCompareFn);
  16943. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16944. subMesh = sortedArray[subIndex];
  16945. subMesh.render(transparent);
  16946. }
  16947. };
  16948. /**
  16949. * Renders the submeshes in the order they were dispatched (no sort applied).
  16950. * @param subMeshes The submeshes to render
  16951. */
  16952. RenderingGroup.renderUnsorted = function (subMeshes) {
  16953. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16954. var submesh = subMeshes.data[subIndex];
  16955. submesh.render(false);
  16956. }
  16957. };
  16958. /**
  16959. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16960. * are rendered back to front if in the same alpha index.
  16961. *
  16962. * @param a The first submesh
  16963. * @param b The second submesh
  16964. * @returns The result of the comparison
  16965. */
  16966. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16967. // Alpha index first
  16968. if (a._alphaIndex > b._alphaIndex) {
  16969. return 1;
  16970. }
  16971. if (a._alphaIndex < b._alphaIndex) {
  16972. return -1;
  16973. }
  16974. // Then distance to camera
  16975. return RenderingGroup.backToFrontSortCompare(a, b);
  16976. };
  16977. /**
  16978. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16979. * are rendered back to front.
  16980. *
  16981. * @param a The first submesh
  16982. * @param b The second submesh
  16983. * @returns The result of the comparison
  16984. */
  16985. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16986. // Then distance to camera
  16987. if (a._distanceToCamera < b._distanceToCamera) {
  16988. return 1;
  16989. }
  16990. if (a._distanceToCamera > b._distanceToCamera) {
  16991. return -1;
  16992. }
  16993. return 0;
  16994. };
  16995. /**
  16996. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16997. * are rendered front to back (prevent overdraw).
  16998. *
  16999. * @param a The first submesh
  17000. * @param b The second submesh
  17001. * @returns The result of the comparison
  17002. */
  17003. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17004. // Then distance to camera
  17005. if (a._distanceToCamera < b._distanceToCamera) {
  17006. return -1;
  17007. }
  17008. if (a._distanceToCamera > b._distanceToCamera) {
  17009. return 1;
  17010. }
  17011. return 0;
  17012. };
  17013. /**
  17014. * Resets the different lists of submeshes to prepare a new frame.
  17015. */
  17016. RenderingGroup.prototype.prepare = function () {
  17017. this._opaqueSubMeshes.reset();
  17018. this._transparentSubMeshes.reset();
  17019. this._alphaTestSubMeshes.reset();
  17020. this._particleSystems.reset();
  17021. this._spriteManagers.reset();
  17022. };
  17023. /**
  17024. * Inserts the submesh in its correct queue depending on its material.
  17025. * @param subMesh The submesh to dispatch
  17026. */
  17027. RenderingGroup.prototype.dispatch = function (subMesh) {
  17028. var material = subMesh.getMaterial();
  17029. var mesh = subMesh.getMesh();
  17030. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17031. this._transparentSubMeshes.push(subMesh);
  17032. }
  17033. else if (material.needAlphaTesting()) {
  17034. this._alphaTestSubMeshes.push(subMesh);
  17035. }
  17036. else {
  17037. this._opaqueSubMeshes.push(subMesh); // Opaque
  17038. }
  17039. };
  17040. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17041. this._spriteManagers.push(spriteManager);
  17042. };
  17043. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17044. this._particleSystems.push(particleSystem);
  17045. };
  17046. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17047. if (this._particleSystems.length === 0) {
  17048. return;
  17049. }
  17050. // Particles
  17051. var activeCamera = this._scene.activeCamera;
  17052. this._scene._particlesDuration.beginMonitoring();
  17053. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17054. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17055. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17056. continue;
  17057. }
  17058. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  17059. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17060. }
  17061. }
  17062. this._scene._particlesDuration.endMonitoring(false);
  17063. };
  17064. RenderingGroup.prototype._renderSprites = function () {
  17065. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17066. return;
  17067. }
  17068. // Sprites
  17069. var activeCamera = this._scene.activeCamera;
  17070. this._scene._spritesDuration.beginMonitoring();
  17071. for (var id = 0; id < this._spriteManagers.length; id++) {
  17072. var spriteManager = this._scene.spriteManagers[id];
  17073. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17074. spriteManager.render();
  17075. }
  17076. }
  17077. this._scene._spritesDuration.endMonitoring(false);
  17078. };
  17079. return RenderingGroup;
  17080. }());
  17081. BABYLON.RenderingGroup = RenderingGroup;
  17082. })(BABYLON || (BABYLON = {}));
  17083. //# sourceMappingURL=babylon.renderingGroup.js.map
  17084. var BABYLON;
  17085. (function (BABYLON) {
  17086. var PointerEventTypes = (function () {
  17087. function PointerEventTypes() {
  17088. }
  17089. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  17090. get: function () {
  17091. return PointerEventTypes._POINTERDOWN;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  17097. get: function () {
  17098. return PointerEventTypes._POINTERUP;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  17104. get: function () {
  17105. return PointerEventTypes._POINTERMOVE;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  17111. get: function () {
  17112. return PointerEventTypes._POINTERWHEEL;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  17118. get: function () {
  17119. return PointerEventTypes._POINTERPICK;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. return PointerEventTypes;
  17125. }());
  17126. PointerEventTypes._POINTERDOWN = 0x01;
  17127. PointerEventTypes._POINTERUP = 0x02;
  17128. PointerEventTypes._POINTERMOVE = 0x04;
  17129. PointerEventTypes._POINTERWHEEL = 0x08;
  17130. PointerEventTypes._POINTERPICK = 0x10;
  17131. BABYLON.PointerEventTypes = PointerEventTypes;
  17132. var PointerInfoBase = (function () {
  17133. function PointerInfoBase(type, event) {
  17134. this.type = type;
  17135. this.event = event;
  17136. }
  17137. return PointerInfoBase;
  17138. }());
  17139. BABYLON.PointerInfoBase = PointerInfoBase;
  17140. /**
  17141. * This class is used to store pointer related info for the onPrePointerObservable event.
  17142. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  17143. */
  17144. var PointerInfoPre = (function (_super) {
  17145. __extends(PointerInfoPre, _super);
  17146. function PointerInfoPre(type, event, localX, localY) {
  17147. var _this = _super.call(this, type, event) || this;
  17148. _this.skipOnPointerObservable = false;
  17149. _this.localPosition = new BABYLON.Vector2(localX, localY);
  17150. return _this;
  17151. }
  17152. return PointerInfoPre;
  17153. }(PointerInfoBase));
  17154. BABYLON.PointerInfoPre = PointerInfoPre;
  17155. /**
  17156. * This type contains all the data related to a pointer event in Babylon.js.
  17157. * 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.
  17158. */
  17159. var PointerInfo = (function (_super) {
  17160. __extends(PointerInfo, _super);
  17161. function PointerInfo(type, event, pickInfo) {
  17162. var _this = _super.call(this, type, event) || this;
  17163. _this.pickInfo = pickInfo;
  17164. return _this;
  17165. }
  17166. return PointerInfo;
  17167. }(PointerInfoBase));
  17168. BABYLON.PointerInfo = PointerInfo;
  17169. /**
  17170. * This class is used by the onRenderingGroupObservable
  17171. */
  17172. var RenderingGroupInfo = (function () {
  17173. function RenderingGroupInfo() {
  17174. }
  17175. return RenderingGroupInfo;
  17176. }());
  17177. /**
  17178. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17179. * This stage will be fired no matter what
  17180. */
  17181. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17182. /**
  17183. * Called before opaque object are rendered.
  17184. * This stage will be fired only if there's 3D Opaque content to render
  17185. */
  17186. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17187. /**
  17188. * Called after the opaque objects are rendered and before the transparent ones
  17189. * This stage will be fired only if there's 3D transparent content to render
  17190. */
  17191. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17192. /**
  17193. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17194. * This stage will be fired no matter what
  17195. */
  17196. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17197. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17198. /**
  17199. * Represents a scene to be rendered by the engine.
  17200. * @see http://doc.babylonjs.com/page.php?p=21911
  17201. */
  17202. var Scene = (function () {
  17203. /**
  17204. * @constructor
  17205. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17206. */
  17207. function Scene(engine) {
  17208. // Members
  17209. this.autoClear = true;
  17210. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17211. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17212. this.forceWireframe = false;
  17213. this.forcePointsCloud = false;
  17214. this.forceShowBoundingBoxes = false;
  17215. this.animationsEnabled = true;
  17216. this.constantlyUpdateMeshUnderPointer = false;
  17217. this.useRightHandedSystem = false;
  17218. this.hoverCursor = "pointer";
  17219. // Metadata
  17220. this.metadata = null;
  17221. // Events
  17222. /**
  17223. * An event triggered when the scene is disposed.
  17224. * @type {BABYLON.Observable}
  17225. */
  17226. this.onDisposeObservable = new BABYLON.Observable();
  17227. /**
  17228. * An event triggered before rendering the scene
  17229. * @type {BABYLON.Observable}
  17230. */
  17231. this.onBeforeRenderObservable = new BABYLON.Observable();
  17232. /**
  17233. * An event triggered after rendering the scene
  17234. * @type {BABYLON.Observable}
  17235. */
  17236. this.onAfterRenderObservable = new BABYLON.Observable();
  17237. /**
  17238. * An event triggered when the scene is ready
  17239. * @type {BABYLON.Observable}
  17240. */
  17241. this.onReadyObservable = new BABYLON.Observable();
  17242. /**
  17243. * An event triggered before rendering a camera
  17244. * @type {BABYLON.Observable}
  17245. */
  17246. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17247. /**
  17248. * An event triggered after rendering a camera
  17249. * @type {BABYLON.Observable}
  17250. */
  17251. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17252. /**
  17253. * An event triggered when a camera is created
  17254. * @type {BABYLON.Observable}
  17255. */
  17256. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17257. /**
  17258. * An event triggered when a camera is removed
  17259. * @type {BABYLON.Observable}
  17260. */
  17261. this.onCameraRemovedObservable = new BABYLON.Observable();
  17262. /**
  17263. * An event triggered when a light is created
  17264. * @type {BABYLON.Observable}
  17265. */
  17266. this.onNewLightAddedObservable = new BABYLON.Observable();
  17267. /**
  17268. * An event triggered when a light is removed
  17269. * @type {BABYLON.Observable}
  17270. */
  17271. this.onLightRemovedObservable = new BABYLON.Observable();
  17272. /**
  17273. * An event triggered when a geometry is created
  17274. * @type {BABYLON.Observable}
  17275. */
  17276. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17277. /**
  17278. * An event triggered when a geometry is removed
  17279. * @type {BABYLON.Observable}
  17280. */
  17281. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17282. /**
  17283. * An event triggered when a mesh is created
  17284. * @type {BABYLON.Observable}
  17285. */
  17286. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17287. /**
  17288. * An event triggered when a mesh is removed
  17289. * @type {BABYLON.Observable}
  17290. */
  17291. this.onMeshRemovedObservable = new BABYLON.Observable();
  17292. /**
  17293. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17294. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17295. * 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)
  17296. */
  17297. this.onRenderingGroupObservable = new BABYLON.Observable();
  17298. // Animations
  17299. this.animations = [];
  17300. /**
  17301. * 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).
  17302. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  17303. */
  17304. this.onPrePointerObservable = new BABYLON.Observable();
  17305. /**
  17306. * Observable event triggered each time an input event is received from the rendering canvas
  17307. */
  17308. this.onPointerObservable = new BABYLON.Observable();
  17309. 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
  17310. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17311. this._startingPointerTime = 0;
  17312. // Fog
  17313. /**
  17314. * is fog enabled on this scene.
  17315. * @type {boolean}
  17316. */
  17317. this.fogEnabled = true;
  17318. this.fogMode = Scene.FOGMODE_NONE;
  17319. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17320. this.fogDensity = 0.1;
  17321. this.fogStart = 0;
  17322. this.fogEnd = 1000.0;
  17323. // Lights
  17324. /**
  17325. * is shadow enabled on this scene.
  17326. * @type {boolean}
  17327. */
  17328. this.shadowsEnabled = true;
  17329. /**
  17330. * is light enabled on this scene.
  17331. * @type {boolean}
  17332. */
  17333. this.lightsEnabled = true;
  17334. /**
  17335. * All of the lights added to this scene.
  17336. * @see BABYLON.Light
  17337. * @type {BABYLON.Light[]}
  17338. */
  17339. this.lights = new Array();
  17340. // Cameras
  17341. /**
  17342. * All of the cameras added to this scene.
  17343. * @see BABYLON.Camera
  17344. * @type {BABYLON.Camera[]}
  17345. */
  17346. this.cameras = new Array();
  17347. this.activeCameras = new Array();
  17348. // Meshes
  17349. /**
  17350. * All of the (abstract) meshes added to this scene.
  17351. * @see BABYLON.AbstractMesh
  17352. * @type {BABYLON.AbstractMesh[]}
  17353. */
  17354. this.meshes = new Array();
  17355. // Geometries
  17356. this._geometries = new Array();
  17357. this.materials = new Array();
  17358. this.multiMaterials = new Array();
  17359. // Textures
  17360. this.texturesEnabled = true;
  17361. this.textures = new Array();
  17362. // Particles
  17363. this.particlesEnabled = true;
  17364. this.particleSystems = new Array();
  17365. // Sprites
  17366. this.spritesEnabled = true;
  17367. this.spriteManagers = new Array();
  17368. // Layers
  17369. this.layers = new Array();
  17370. this.highlightLayers = new Array();
  17371. // Skeletons
  17372. this.skeletonsEnabled = true;
  17373. this.skeletons = new Array();
  17374. // Lens flares
  17375. this.lensFlaresEnabled = true;
  17376. this.lensFlareSystems = new Array();
  17377. // Collisions
  17378. this.collisionsEnabled = true;
  17379. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17380. // Postprocesses
  17381. this.postProcessesEnabled = true;
  17382. // Customs render targets
  17383. this.renderTargetsEnabled = true;
  17384. this.dumpNextRenderTargets = false;
  17385. this.customRenderTargets = new Array();
  17386. // Imported meshes
  17387. this.importedMeshesFiles = new Array();
  17388. // Probes
  17389. this.probesEnabled = true;
  17390. this.reflectionProbes = new Array();
  17391. this._actionManagers = new Array();
  17392. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17393. // Procedural textures
  17394. this.proceduralTexturesEnabled = true;
  17395. this._proceduralTextures = new Array();
  17396. this.soundTracks = new Array();
  17397. this._audioEnabled = true;
  17398. this._headphone = false;
  17399. // Performance counters
  17400. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17401. this._totalLightsCounter = new BABYLON.PerfCounter();
  17402. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17403. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17404. this._totalVertices = new BABYLON.PerfCounter();
  17405. this._activeIndices = new BABYLON.PerfCounter();
  17406. this._activeParticles = new BABYLON.PerfCounter();
  17407. this._lastFrameDuration = new BABYLON.PerfCounter();
  17408. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17409. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17410. this._particlesDuration = new BABYLON.PerfCounter();
  17411. this._renderDuration = new BABYLON.PerfCounter();
  17412. this._spritesDuration = new BABYLON.PerfCounter();
  17413. this._activeBones = new BABYLON.PerfCounter();
  17414. this._animationTime = 0;
  17415. this.animationTimeScale = 1;
  17416. this._renderId = 0;
  17417. this._executeWhenReadyTimeoutId = -1;
  17418. this._intermediateRendering = false;
  17419. this._toBeDisposed = new BABYLON.SmartArray(256);
  17420. this._pendingData = []; //ANY
  17421. this._activeMeshes = new BABYLON.SmartArray(256);
  17422. this._processedMaterials = new BABYLON.SmartArray(256);
  17423. this._renderTargets = new BABYLON.SmartArray(256);
  17424. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17425. this._activeSkeletons = new BABYLON.SmartArray(32);
  17426. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17427. this._activeAnimatables = new Array();
  17428. this._transformMatrix = BABYLON.Matrix.Zero();
  17429. this._edgesRenderers = new BABYLON.SmartArray(16);
  17430. this._uniqueIdCounter = 0;
  17431. this._engine = engine;
  17432. engine.scenes.push(this);
  17433. this._externalData = new BABYLON.StringDictionary();
  17434. this._uid = null;
  17435. this._renderingManager = new BABYLON.RenderingManager(this);
  17436. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17437. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17438. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17439. if (BABYLON.OutlineRenderer) {
  17440. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17441. }
  17442. this.attachControl();
  17443. if (BABYLON.SoundTrack) {
  17444. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17445. }
  17446. //simplification queue
  17447. if (BABYLON.SimplificationQueue) {
  17448. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17449. }
  17450. //collision coordinator initialization. For now legacy per default.
  17451. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17452. }
  17453. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17454. get: function () {
  17455. return Scene._FOGMODE_NONE;
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17461. get: function () {
  17462. return Scene._FOGMODE_EXP;
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17468. get: function () {
  17469. return Scene._FOGMODE_EXP2;
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17475. get: function () {
  17476. return Scene._FOGMODE_LINEAR;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(Scene.prototype, "onDispose", {
  17482. set: function (callback) {
  17483. if (this._onDisposeObserver) {
  17484. this.onDisposeObservable.remove(this._onDisposeObserver);
  17485. }
  17486. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17487. },
  17488. enumerable: true,
  17489. configurable: true
  17490. });
  17491. Object.defineProperty(Scene.prototype, "beforeRender", {
  17492. set: function (callback) {
  17493. if (this._onBeforeRenderObserver) {
  17494. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17495. }
  17496. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17497. },
  17498. enumerable: true,
  17499. configurable: true
  17500. });
  17501. Object.defineProperty(Scene.prototype, "afterRender", {
  17502. set: function (callback) {
  17503. if (this._onAfterRenderObserver) {
  17504. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17505. }
  17506. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17507. },
  17508. enumerable: true,
  17509. configurable: true
  17510. });
  17511. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17512. set: function (callback) {
  17513. if (this._onBeforeCameraRenderObserver) {
  17514. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17515. }
  17516. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17517. },
  17518. enumerable: true,
  17519. configurable: true
  17520. });
  17521. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17522. set: function (callback) {
  17523. if (this._onAfterCameraRenderObserver) {
  17524. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17525. }
  17526. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17527. },
  17528. enumerable: true,
  17529. configurable: true
  17530. });
  17531. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17532. get: function () {
  17533. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17534. },
  17535. enumerable: true,
  17536. configurable: true
  17537. });
  17538. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17539. get: function () {
  17540. if (!this._defaultMaterial) {
  17541. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17542. }
  17543. return this._defaultMaterial;
  17544. },
  17545. enumerable: true,
  17546. configurable: true
  17547. });
  17548. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17549. get: function () {
  17550. return this._frustumPlanes;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(Scene.prototype, "debugLayer", {
  17556. // Properties
  17557. get: function () {
  17558. if (!this._debugLayer) {
  17559. this._debugLayer = new BABYLON.DebugLayer(this);
  17560. }
  17561. return this._debugLayer;
  17562. },
  17563. enumerable: true,
  17564. configurable: true
  17565. });
  17566. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17567. get: function () {
  17568. return this._workerCollisions;
  17569. },
  17570. set: function (enabled) {
  17571. enabled = (enabled && !!Worker);
  17572. this._workerCollisions = enabled;
  17573. if (this.collisionCoordinator) {
  17574. this.collisionCoordinator.destroy();
  17575. }
  17576. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17577. this.collisionCoordinator.init(this);
  17578. },
  17579. enumerable: true,
  17580. configurable: true
  17581. });
  17582. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  17583. get: function () {
  17584. return this._selectionOctree;
  17585. },
  17586. enumerable: true,
  17587. configurable: true
  17588. });
  17589. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17590. /**
  17591. * The mesh that is currently under the pointer.
  17592. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17593. */
  17594. get: function () {
  17595. return this._pointerOverMesh;
  17596. },
  17597. enumerable: true,
  17598. configurable: true
  17599. });
  17600. Object.defineProperty(Scene.prototype, "pointerX", {
  17601. /**
  17602. * Current on-screen X position of the pointer
  17603. * @return {number} X position of the pointer
  17604. */
  17605. get: function () {
  17606. return this._pointerX;
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. Object.defineProperty(Scene.prototype, "pointerY", {
  17612. /**
  17613. * Current on-screen Y position of the pointer
  17614. * @return {number} Y position of the pointer
  17615. */
  17616. get: function () {
  17617. return this._pointerY;
  17618. },
  17619. enumerable: true,
  17620. configurable: true
  17621. });
  17622. Scene.prototype.getCachedMaterial = function () {
  17623. return this._cachedMaterial;
  17624. };
  17625. Scene.prototype.getBoundingBoxRenderer = function () {
  17626. return this._boundingBoxRenderer;
  17627. };
  17628. Scene.prototype.getOutlineRenderer = function () {
  17629. return this._outlineRenderer;
  17630. };
  17631. Scene.prototype.getEngine = function () {
  17632. return this._engine;
  17633. };
  17634. Scene.prototype.getTotalVertices = function () {
  17635. return this._totalVertices.current;
  17636. };
  17637. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17638. get: function () {
  17639. return this._totalVertices;
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. Scene.prototype.getActiveIndices = function () {
  17645. return this._activeIndices.current;
  17646. };
  17647. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17648. get: function () {
  17649. return this._activeIndices;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Scene.prototype.getActiveParticles = function () {
  17655. return this._activeParticles.current;
  17656. };
  17657. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17658. get: function () {
  17659. return this._activeParticles;
  17660. },
  17661. enumerable: true,
  17662. configurable: true
  17663. });
  17664. Scene.prototype.getActiveBones = function () {
  17665. return this._activeBones.current;
  17666. };
  17667. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17668. get: function () {
  17669. return this._activeBones;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. // Stats
  17675. Scene.prototype.getLastFrameDuration = function () {
  17676. return this._lastFrameDuration.current;
  17677. };
  17678. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17679. get: function () {
  17680. return this._lastFrameDuration;
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17686. return this._evaluateActiveMeshesDuration.current;
  17687. };
  17688. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17689. get: function () {
  17690. return this._evaluateActiveMeshesDuration;
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. Scene.prototype.getActiveMeshes = function () {
  17696. return this._activeMeshes;
  17697. };
  17698. Scene.prototype.getRenderTargetsDuration = function () {
  17699. return this._renderTargetsDuration.current;
  17700. };
  17701. Scene.prototype.getRenderDuration = function () {
  17702. return this._renderDuration.current;
  17703. };
  17704. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17705. get: function () {
  17706. return this._renderDuration;
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. Scene.prototype.getParticlesDuration = function () {
  17712. return this._particlesDuration.current;
  17713. };
  17714. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17715. get: function () {
  17716. return this._particlesDuration;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Scene.prototype.getSpritesDuration = function () {
  17722. return this._spritesDuration.current;
  17723. };
  17724. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17725. get: function () {
  17726. return this._spritesDuration;
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Scene.prototype.getAnimationRatio = function () {
  17732. return this._animationRatio;
  17733. };
  17734. Scene.prototype.getRenderId = function () {
  17735. return this._renderId;
  17736. };
  17737. Scene.prototype.incrementRenderId = function () {
  17738. this._renderId++;
  17739. };
  17740. Scene.prototype._updatePointerPosition = function (evt) {
  17741. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17742. this._pointerX = evt.clientX - canvasRect.left;
  17743. this._pointerY = evt.clientY - canvasRect.top;
  17744. this._unTranslatedPointerX = this._pointerX;
  17745. this._unTranslatedPointerY = this._pointerY;
  17746. if (this.cameraToUseForPointers) {
  17747. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17748. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17749. }
  17750. };
  17751. // Pointers handling
  17752. /**
  17753. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17754. * @param attachUp defines if you want to attach events to pointerup
  17755. * @param attachDown defines if you want to attach events to pointerdown
  17756. * @param attachMove defines if you want to attach events to pointermove
  17757. */
  17758. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17759. var _this = this;
  17760. if (attachUp === void 0) { attachUp = true; }
  17761. if (attachDown === void 0) { attachDown = true; }
  17762. if (attachMove === void 0) { attachMove = true; }
  17763. var spritePredicate = function (sprite) {
  17764. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17765. };
  17766. this._onPointerMove = function (evt) {
  17767. _this._updatePointerPosition(evt);
  17768. // PreObservable support
  17769. if (_this.onPrePointerObservable.hasObservers()) {
  17770. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17771. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17772. _this.onPrePointerObservable.notifyObservers(pi, type);
  17773. if (pi.skipOnPointerObservable) {
  17774. return;
  17775. }
  17776. }
  17777. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17778. return;
  17779. }
  17780. var canvas = _this._engine.getRenderingCanvas();
  17781. if (!_this.pointerMovePredicate) {
  17782. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17783. }
  17784. // Meshes
  17785. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17786. if (pickResult.hit && pickResult.pickedMesh) {
  17787. _this.setPointerOverSprite(null);
  17788. _this.setPointerOverMesh(pickResult.pickedMesh);
  17789. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17790. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17791. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17792. }
  17793. else {
  17794. canvas.style.cursor = _this.hoverCursor;
  17795. }
  17796. }
  17797. else {
  17798. canvas.style.cursor = "";
  17799. }
  17800. }
  17801. else {
  17802. _this.setPointerOverMesh(null);
  17803. // Sprites
  17804. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17805. if (pickResult.hit && pickResult.pickedSprite) {
  17806. _this.setPointerOverSprite(pickResult.pickedSprite);
  17807. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17808. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17809. }
  17810. else {
  17811. canvas.style.cursor = _this.hoverCursor;
  17812. }
  17813. }
  17814. else {
  17815. _this.setPointerOverSprite(null);
  17816. // Restore pointer
  17817. canvas.style.cursor = "";
  17818. }
  17819. }
  17820. if (_this.onPointerMove) {
  17821. _this.onPointerMove(evt, pickResult);
  17822. }
  17823. if (_this.onPointerObservable.hasObservers()) {
  17824. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17825. var pi = new PointerInfo(type, evt, pickResult);
  17826. _this.onPointerObservable.notifyObservers(pi, type);
  17827. }
  17828. };
  17829. this._onPointerDown = function (evt) {
  17830. _this._updatePointerPosition(evt);
  17831. // PreObservable support
  17832. if (_this.onPrePointerObservable.hasObservers()) {
  17833. var type = PointerEventTypes.POINTERDOWN;
  17834. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17835. _this.onPrePointerObservable.notifyObservers(pi, type);
  17836. if (pi.skipOnPointerObservable) {
  17837. return;
  17838. }
  17839. }
  17840. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17841. return;
  17842. }
  17843. _this._startingPointerPosition.x = _this._pointerX;
  17844. _this._startingPointerPosition.y = _this._pointerY;
  17845. _this._startingPointerTime = new Date().getTime();
  17846. if (!_this.pointerDownPredicate) {
  17847. _this.pointerDownPredicate = function (mesh) {
  17848. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17849. };
  17850. }
  17851. // Meshes
  17852. _this._pickedDownMesh = null;
  17853. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17854. if (pickResult.hit && pickResult.pickedMesh) {
  17855. if (pickResult.pickedMesh.actionManager) {
  17856. _this._pickedDownMesh = pickResult.pickedMesh;
  17857. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17858. switch (evt.button) {
  17859. case 0:
  17860. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17861. break;
  17862. case 1:
  17863. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17864. break;
  17865. case 2:
  17866. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17867. break;
  17868. }
  17869. if (pickResult.pickedMesh.actionManager) {
  17870. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17871. }
  17872. }
  17873. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17874. var that = _this;
  17875. window.setTimeout(function () {
  17876. 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);
  17877. if (pickResult.hit && pickResult.pickedMesh) {
  17878. if (pickResult.pickedMesh.actionManager) {
  17879. 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)) {
  17880. that._startingPointerTime = 0;
  17881. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17882. }
  17883. }
  17884. }
  17885. }, BABYLON.ActionManager.LongPressDelay);
  17886. }
  17887. }
  17888. }
  17889. if (_this.onPointerDown) {
  17890. _this.onPointerDown(evt, pickResult);
  17891. }
  17892. if (_this.onPointerObservable.hasObservers()) {
  17893. var type = PointerEventTypes.POINTERDOWN;
  17894. var pi = new PointerInfo(type, evt, pickResult);
  17895. _this.onPointerObservable.notifyObservers(pi, type);
  17896. }
  17897. // Sprites
  17898. _this._pickedDownSprite = null;
  17899. if (_this.spriteManagers.length > 0) {
  17900. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17901. if (pickResult.hit && pickResult.pickedSprite) {
  17902. if (pickResult.pickedSprite.actionManager) {
  17903. _this._pickedDownSprite = pickResult.pickedSprite;
  17904. switch (evt.button) {
  17905. case 0:
  17906. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17907. break;
  17908. case 1:
  17909. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17910. break;
  17911. case 2:
  17912. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17913. break;
  17914. }
  17915. if (pickResult.pickedSprite.actionManager) {
  17916. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17917. }
  17918. }
  17919. }
  17920. }
  17921. };
  17922. this._onPointerUp = function (evt) {
  17923. _this._updatePointerPosition(evt);
  17924. // PreObservable support
  17925. if (_this.onPrePointerObservable.hasObservers()) {
  17926. var type = PointerEventTypes.POINTERUP;
  17927. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17928. _this.onPrePointerObservable.notifyObservers(pi, type);
  17929. if (pi.skipOnPointerObservable) {
  17930. return;
  17931. }
  17932. }
  17933. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17934. return;
  17935. }
  17936. if (!_this.pointerUpPredicate) {
  17937. _this.pointerUpPredicate = function (mesh) {
  17938. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17939. };
  17940. }
  17941. // Meshes
  17942. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17943. if (pickResult.hit && pickResult.pickedMesh) {
  17944. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17945. if (_this.onPointerPick) {
  17946. _this.onPointerPick(evt, pickResult);
  17947. }
  17948. if (_this.onPointerObservable.hasObservers()) {
  17949. var type = PointerEventTypes.POINTERPICK;
  17950. var pi = new PointerInfo(type, evt, pickResult);
  17951. _this.onPointerObservable.notifyObservers(pi, type);
  17952. }
  17953. }
  17954. if (pickResult.pickedMesh.actionManager) {
  17955. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17956. if (pickResult.pickedMesh.actionManager) {
  17957. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17958. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17959. }
  17960. }
  17961. }
  17962. }
  17963. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17964. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17965. }
  17966. if (_this.onPointerUp) {
  17967. _this.onPointerUp(evt, pickResult);
  17968. }
  17969. if (_this.onPointerObservable.hasObservers()) {
  17970. var type = PointerEventTypes.POINTERUP;
  17971. var pi = new PointerInfo(type, evt, pickResult);
  17972. _this.onPointerObservable.notifyObservers(pi, type);
  17973. }
  17974. _this._startingPointerTime = 0;
  17975. // Sprites
  17976. if (_this.spriteManagers.length > 0) {
  17977. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17978. if (pickResult.hit && pickResult.pickedSprite) {
  17979. if (pickResult.pickedSprite.actionManager) {
  17980. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17981. if (pickResult.pickedSprite.actionManager) {
  17982. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17983. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17984. }
  17985. }
  17986. }
  17987. }
  17988. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17989. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17990. }
  17991. }
  17992. };
  17993. this._onKeyDown = function (evt) {
  17994. if (_this.actionManager) {
  17995. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17996. }
  17997. };
  17998. this._onKeyUp = function (evt) {
  17999. if (_this.actionManager) {
  18000. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18001. }
  18002. };
  18003. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18004. var canvas = this._engine.getRenderingCanvas();
  18005. if (attachMove) {
  18006. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18007. // Wheel
  18008. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18009. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18010. }
  18011. if (attachDown) {
  18012. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18013. }
  18014. if (attachUp) {
  18015. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18016. }
  18017. canvas.tabIndex = 1;
  18018. canvas.addEventListener("keydown", this._onKeyDown, false);
  18019. canvas.addEventListener("keyup", this._onKeyUp, false);
  18020. };
  18021. Scene.prototype.detachControl = function () {
  18022. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18023. var canvas = this._engine.getRenderingCanvas();
  18024. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18025. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18026. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18027. // Wheel
  18028. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18029. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18030. canvas.removeEventListener("keydown", this._onKeyDown);
  18031. canvas.removeEventListener("keyup", this._onKeyUp);
  18032. };
  18033. // Ready
  18034. Scene.prototype.isReady = function () {
  18035. if (this._pendingData.length > 0) {
  18036. return false;
  18037. }
  18038. var index;
  18039. for (index = 0; index < this._geometries.length; index++) {
  18040. var geometry = this._geometries[index];
  18041. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18042. return false;
  18043. }
  18044. }
  18045. for (index = 0; index < this.meshes.length; index++) {
  18046. var mesh = this.meshes[index];
  18047. if (!mesh.isReady()) {
  18048. return false;
  18049. }
  18050. var mat = mesh.material;
  18051. if (mat) {
  18052. if (!mat.isReady(mesh)) {
  18053. return false;
  18054. }
  18055. }
  18056. }
  18057. return true;
  18058. };
  18059. Scene.prototype.resetCachedMaterial = function () {
  18060. this._cachedMaterial = null;
  18061. };
  18062. Scene.prototype.registerBeforeRender = function (func) {
  18063. this.onBeforeRenderObservable.add(func);
  18064. };
  18065. Scene.prototype.unregisterBeforeRender = function (func) {
  18066. this.onBeforeRenderObservable.removeCallback(func);
  18067. };
  18068. Scene.prototype.registerAfterRender = function (func) {
  18069. this.onAfterRenderObservable.add(func);
  18070. };
  18071. Scene.prototype.unregisterAfterRender = function (func) {
  18072. this.onAfterRenderObservable.removeCallback(func);
  18073. };
  18074. Scene.prototype._addPendingData = function (data) {
  18075. this._pendingData.push(data);
  18076. };
  18077. Scene.prototype._removePendingData = function (data) {
  18078. var index = this._pendingData.indexOf(data);
  18079. if (index !== -1) {
  18080. this._pendingData.splice(index, 1);
  18081. }
  18082. };
  18083. Scene.prototype.getWaitingItemsCount = function () {
  18084. return this._pendingData.length;
  18085. };
  18086. /**
  18087. * Registers a function to be executed when the scene is ready.
  18088. * @param {Function} func - the function to be executed.
  18089. */
  18090. Scene.prototype.executeWhenReady = function (func) {
  18091. var _this = this;
  18092. this.onReadyObservable.add(func);
  18093. if (this._executeWhenReadyTimeoutId !== -1) {
  18094. return;
  18095. }
  18096. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18097. _this._checkIsReady();
  18098. }, 150);
  18099. };
  18100. Scene.prototype._checkIsReady = function () {
  18101. var _this = this;
  18102. if (this.isReady()) {
  18103. this.onReadyObservable.notifyObservers(this);
  18104. this.onReadyObservable.clear();
  18105. this._executeWhenReadyTimeoutId = -1;
  18106. return;
  18107. }
  18108. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18109. _this._checkIsReady();
  18110. }, 150);
  18111. };
  18112. // Animations
  18113. /**
  18114. * Will start the animation sequence of a given target
  18115. * @param target - the target
  18116. * @param {number} from - from which frame should animation start
  18117. * @param {number} to - till which frame should animation run.
  18118. * @param {boolean} [loop] - should the animation loop
  18119. * @param {number} [speedRatio] - the speed in which to run the animation
  18120. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18121. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18122. * @return {BABYLON.Animatable} the animatable object created for this animation
  18123. * @see BABYLON.Animatable
  18124. * @see http://doc.babylonjs.com/page.php?p=22081
  18125. */
  18126. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18127. if (speedRatio === void 0) { speedRatio = 1.0; }
  18128. this.stopAnimation(target);
  18129. if (!animatable) {
  18130. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18131. }
  18132. // Local animations
  18133. if (target.animations) {
  18134. animatable.appendAnimations(target, target.animations);
  18135. }
  18136. // Children animations
  18137. if (target.getAnimatables) {
  18138. var animatables = target.getAnimatables();
  18139. for (var index = 0; index < animatables.length; index++) {
  18140. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18141. }
  18142. }
  18143. animatable.reset();
  18144. return animatable;
  18145. };
  18146. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18147. if (speedRatio === undefined) {
  18148. speedRatio = 1.0;
  18149. }
  18150. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18151. return animatable;
  18152. };
  18153. Scene.prototype.getAnimatableByTarget = function (target) {
  18154. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18155. if (this._activeAnimatables[index].target === target) {
  18156. return this._activeAnimatables[index];
  18157. }
  18158. }
  18159. return null;
  18160. };
  18161. Object.defineProperty(Scene.prototype, "Animatables", {
  18162. get: function () {
  18163. return this._activeAnimatables;
  18164. },
  18165. enumerable: true,
  18166. configurable: true
  18167. });
  18168. /**
  18169. * Will stop the animation of the given target
  18170. * @param target - the target
  18171. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18172. * @see beginAnimation
  18173. */
  18174. Scene.prototype.stopAnimation = function (target, animationName) {
  18175. var animatable = this.getAnimatableByTarget(target);
  18176. if (animatable) {
  18177. animatable.stop(animationName);
  18178. }
  18179. };
  18180. Scene.prototype._animate = function () {
  18181. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18182. return;
  18183. }
  18184. // Getting time
  18185. var now = BABYLON.Tools.Now;
  18186. if (!this._animationTimeLast) {
  18187. if (this._pendingData.length > 0) {
  18188. return;
  18189. }
  18190. this._animationTimeLast = now;
  18191. }
  18192. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18193. this._animationTime += deltaTime;
  18194. this._animationTimeLast = now;
  18195. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18196. this._activeAnimatables[index]._animate(this._animationTime);
  18197. }
  18198. };
  18199. // Matrix
  18200. Scene.prototype.getViewMatrix = function () {
  18201. return this._viewMatrix;
  18202. };
  18203. Scene.prototype.getProjectionMatrix = function () {
  18204. return this._projectionMatrix;
  18205. };
  18206. Scene.prototype.getTransformMatrix = function () {
  18207. return this._transformMatrix;
  18208. };
  18209. Scene.prototype.setTransformMatrix = function (view, projection) {
  18210. this._viewMatrix = view;
  18211. this._projectionMatrix = projection;
  18212. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18213. // Update frustum
  18214. if (!this._frustumPlanes) {
  18215. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18216. }
  18217. else {
  18218. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18219. }
  18220. };
  18221. // Methods
  18222. Scene.prototype.addMesh = function (newMesh) {
  18223. newMesh.uniqueId = this._uniqueIdCounter++;
  18224. var position = this.meshes.push(newMesh);
  18225. //notify the collision coordinator
  18226. this.collisionCoordinator.onMeshAdded(newMesh);
  18227. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18228. };
  18229. Scene.prototype.removeMesh = function (toRemove) {
  18230. var index = this.meshes.indexOf(toRemove);
  18231. if (index !== -1) {
  18232. // Remove from the scene if mesh found
  18233. this.meshes.splice(index, 1);
  18234. }
  18235. //notify the collision coordinator
  18236. this.collisionCoordinator.onMeshRemoved(toRemove);
  18237. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18238. return index;
  18239. };
  18240. Scene.prototype.removeSkeleton = function (toRemove) {
  18241. var index = this.skeletons.indexOf(toRemove);
  18242. if (index !== -1) {
  18243. // Remove from the scene if mesh found
  18244. this.skeletons.splice(index, 1);
  18245. }
  18246. return index;
  18247. };
  18248. Scene.prototype.removeLight = function (toRemove) {
  18249. var index = this.lights.indexOf(toRemove);
  18250. if (index !== -1) {
  18251. // Remove from the scene if mesh found
  18252. this.lights.splice(index, 1);
  18253. }
  18254. this.onLightRemovedObservable.notifyObservers(toRemove);
  18255. return index;
  18256. };
  18257. Scene.prototype.removeCamera = function (toRemove) {
  18258. var index = this.cameras.indexOf(toRemove);
  18259. if (index !== -1) {
  18260. // Remove from the scene if mesh found
  18261. this.cameras.splice(index, 1);
  18262. }
  18263. // Remove from activeCameras
  18264. var index2 = this.activeCameras.indexOf(toRemove);
  18265. if (index2 !== -1) {
  18266. // Remove from the scene if mesh found
  18267. this.activeCameras.splice(index2, 1);
  18268. }
  18269. // Reset the activeCamera
  18270. if (this.activeCamera === toRemove) {
  18271. if (this.cameras.length > 0) {
  18272. this.activeCamera = this.cameras[0];
  18273. }
  18274. else {
  18275. this.activeCamera = null;
  18276. }
  18277. }
  18278. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18279. return index;
  18280. };
  18281. Scene.prototype.addLight = function (newLight) {
  18282. newLight.uniqueId = this._uniqueIdCounter++;
  18283. var position = this.lights.push(newLight);
  18284. this.onNewLightAddedObservable.notifyObservers(newLight);
  18285. };
  18286. Scene.prototype.addCamera = function (newCamera) {
  18287. newCamera.uniqueId = this._uniqueIdCounter++;
  18288. var position = this.cameras.push(newCamera);
  18289. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18290. };
  18291. /**
  18292. * Switch active camera
  18293. * @param {Camera} newCamera - new active camera
  18294. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18295. */
  18296. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18297. if (attachControl === void 0) { attachControl = true; }
  18298. var canvas = this._engine.getRenderingCanvas();
  18299. this.activeCamera.detachControl(canvas);
  18300. this.activeCamera = newCamera;
  18301. if (attachControl) {
  18302. newCamera.attachControl(canvas);
  18303. }
  18304. };
  18305. /**
  18306. * sets the active camera of the scene using its ID
  18307. * @param {string} id - the camera's ID
  18308. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18309. * @see activeCamera
  18310. */
  18311. Scene.prototype.setActiveCameraByID = function (id) {
  18312. var camera = this.getCameraByID(id);
  18313. if (camera) {
  18314. this.activeCamera = camera;
  18315. return camera;
  18316. }
  18317. return null;
  18318. };
  18319. /**
  18320. * sets the active camera of the scene using its name
  18321. * @param {string} name - the camera's name
  18322. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18323. * @see activeCamera
  18324. */
  18325. Scene.prototype.setActiveCameraByName = function (name) {
  18326. var camera = this.getCameraByName(name);
  18327. if (camera) {
  18328. this.activeCamera = camera;
  18329. return camera;
  18330. }
  18331. return null;
  18332. };
  18333. /**
  18334. * get a material using its id
  18335. * @param {string} the material's ID
  18336. * @return {BABYLON.Material|null} the material or null if none found.
  18337. */
  18338. Scene.prototype.getMaterialByID = function (id) {
  18339. for (var index = 0; index < this.materials.length; index++) {
  18340. if (this.materials[index].id === id) {
  18341. return this.materials[index];
  18342. }
  18343. }
  18344. return null;
  18345. };
  18346. /**
  18347. * get a material using its name
  18348. * @param {string} the material's name
  18349. * @return {BABYLON.Material|null} the material or null if none found.
  18350. */
  18351. Scene.prototype.getMaterialByName = function (name) {
  18352. for (var index = 0; index < this.materials.length; index++) {
  18353. if (this.materials[index].name === name) {
  18354. return this.materials[index];
  18355. }
  18356. }
  18357. return null;
  18358. };
  18359. Scene.prototype.getLensFlareSystemByName = function (name) {
  18360. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18361. if (this.lensFlareSystems[index].name === name) {
  18362. return this.lensFlareSystems[index];
  18363. }
  18364. }
  18365. return null;
  18366. };
  18367. Scene.prototype.getLensFlareSystemByID = function (id) {
  18368. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18369. if (this.lensFlareSystems[index].id === id) {
  18370. return this.lensFlareSystems[index];
  18371. }
  18372. }
  18373. return null;
  18374. };
  18375. Scene.prototype.getCameraByID = function (id) {
  18376. for (var index = 0; index < this.cameras.length; index++) {
  18377. if (this.cameras[index].id === id) {
  18378. return this.cameras[index];
  18379. }
  18380. }
  18381. return null;
  18382. };
  18383. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18384. for (var index = 0; index < this.cameras.length; index++) {
  18385. if (this.cameras[index].uniqueId === uniqueId) {
  18386. return this.cameras[index];
  18387. }
  18388. }
  18389. return null;
  18390. };
  18391. /**
  18392. * get a camera using its name
  18393. * @param {string} the camera's name
  18394. * @return {BABYLON.Camera|null} the camera or null if none found.
  18395. */
  18396. Scene.prototype.getCameraByName = function (name) {
  18397. for (var index = 0; index < this.cameras.length; index++) {
  18398. if (this.cameras[index].name === name) {
  18399. return this.cameras[index];
  18400. }
  18401. }
  18402. return null;
  18403. };
  18404. /**
  18405. * get a bone using its id
  18406. * @param {string} the bone's id
  18407. * @return {BABYLON.Bone|null} the bone or null if not found
  18408. */
  18409. Scene.prototype.getBoneByID = function (id) {
  18410. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18411. var skeleton = this.skeletons[skeletonIndex];
  18412. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18413. if (skeleton.bones[boneIndex].id === id) {
  18414. return skeleton.bones[boneIndex];
  18415. }
  18416. }
  18417. }
  18418. return null;
  18419. };
  18420. /**
  18421. * get a bone using its id
  18422. * @param {string} the bone's name
  18423. * @return {BABYLON.Bone|null} the bone or null if not found
  18424. */
  18425. Scene.prototype.getBoneByName = function (name) {
  18426. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18427. var skeleton = this.skeletons[skeletonIndex];
  18428. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18429. if (skeleton.bones[boneIndex].name === name) {
  18430. return skeleton.bones[boneIndex];
  18431. }
  18432. }
  18433. }
  18434. return null;
  18435. };
  18436. /**
  18437. * get a light node using its name
  18438. * @param {string} the light's name
  18439. * @return {BABYLON.Light|null} the light or null if none found.
  18440. */
  18441. Scene.prototype.getLightByName = function (name) {
  18442. for (var index = 0; index < this.lights.length; index++) {
  18443. if (this.lights[index].name === name) {
  18444. return this.lights[index];
  18445. }
  18446. }
  18447. return null;
  18448. };
  18449. /**
  18450. * get a light node using its ID
  18451. * @param {string} the light's id
  18452. * @return {BABYLON.Light|null} the light or null if none found.
  18453. */
  18454. Scene.prototype.getLightByID = function (id) {
  18455. for (var index = 0; index < this.lights.length; index++) {
  18456. if (this.lights[index].id === id) {
  18457. return this.lights[index];
  18458. }
  18459. }
  18460. return null;
  18461. };
  18462. /**
  18463. * get a light node using its scene-generated unique ID
  18464. * @param {number} the light's unique id
  18465. * @return {BABYLON.Light|null} the light or null if none found.
  18466. */
  18467. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18468. for (var index = 0; index < this.lights.length; index++) {
  18469. if (this.lights[index].uniqueId === uniqueId) {
  18470. return this.lights[index];
  18471. }
  18472. }
  18473. return null;
  18474. };
  18475. /**
  18476. * get a particle system by id
  18477. * @param id {number} the particle system id
  18478. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  18479. */
  18480. Scene.prototype.getParticleSystemByID = function (id) {
  18481. for (var index = 0; index < this.particleSystems.length; index++) {
  18482. if (this.particleSystems[index].id === id) {
  18483. return this.particleSystems[index];
  18484. }
  18485. }
  18486. return null;
  18487. };
  18488. /**
  18489. * get a geometry using its ID
  18490. * @param {string} the geometry's id
  18491. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18492. */
  18493. Scene.prototype.getGeometryByID = function (id) {
  18494. for (var index = 0; index < this._geometries.length; index++) {
  18495. if (this._geometries[index].id === id) {
  18496. return this._geometries[index];
  18497. }
  18498. }
  18499. return null;
  18500. };
  18501. /**
  18502. * add a new geometry to this scene.
  18503. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18504. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18505. * @return {boolean} was the geometry added or not
  18506. */
  18507. Scene.prototype.pushGeometry = function (geometry, force) {
  18508. if (!force && this.getGeometryByID(geometry.id)) {
  18509. return false;
  18510. }
  18511. this._geometries.push(geometry);
  18512. //notify the collision coordinator
  18513. this.collisionCoordinator.onGeometryAdded(geometry);
  18514. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18515. return true;
  18516. };
  18517. /**
  18518. * Removes an existing geometry
  18519. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18520. * @return {boolean} was the geometry removed or not
  18521. */
  18522. Scene.prototype.removeGeometry = function (geometry) {
  18523. var index = this._geometries.indexOf(geometry);
  18524. if (index > -1) {
  18525. this._geometries.splice(index, 1);
  18526. //notify the collision coordinator
  18527. this.collisionCoordinator.onGeometryDeleted(geometry);
  18528. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18529. return true;
  18530. }
  18531. return false;
  18532. };
  18533. Scene.prototype.getGeometries = function () {
  18534. return this._geometries;
  18535. };
  18536. /**
  18537. * Get the first added mesh found of a given ID
  18538. * @param {string} id - the id to search for
  18539. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18540. */
  18541. Scene.prototype.getMeshByID = function (id) {
  18542. for (var index = 0; index < this.meshes.length; index++) {
  18543. if (this.meshes[index].id === id) {
  18544. return this.meshes[index];
  18545. }
  18546. }
  18547. return null;
  18548. };
  18549. Scene.prototype.getMeshesByID = function (id) {
  18550. return this.meshes.filter(function (m) {
  18551. return m.id === id;
  18552. });
  18553. };
  18554. /**
  18555. * Get a mesh with its auto-generated unique id
  18556. * @param {number} uniqueId - the unique id to search for
  18557. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18558. */
  18559. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18560. for (var index = 0; index < this.meshes.length; index++) {
  18561. if (this.meshes[index].uniqueId === uniqueId) {
  18562. return this.meshes[index];
  18563. }
  18564. }
  18565. return null;
  18566. };
  18567. /**
  18568. * Get a the last added mesh found of a given ID
  18569. * @param {string} id - the id to search for
  18570. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18571. */
  18572. Scene.prototype.getLastMeshByID = function (id) {
  18573. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18574. if (this.meshes[index].id === id) {
  18575. return this.meshes[index];
  18576. }
  18577. }
  18578. return null;
  18579. };
  18580. /**
  18581. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18582. * @param {string} id - the id to search for
  18583. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18584. */
  18585. Scene.prototype.getLastEntryByID = function (id) {
  18586. var index;
  18587. for (index = this.meshes.length - 1; index >= 0; index--) {
  18588. if (this.meshes[index].id === id) {
  18589. return this.meshes[index];
  18590. }
  18591. }
  18592. for (index = this.cameras.length - 1; index >= 0; index--) {
  18593. if (this.cameras[index].id === id) {
  18594. return this.cameras[index];
  18595. }
  18596. }
  18597. for (index = this.lights.length - 1; index >= 0; index--) {
  18598. if (this.lights[index].id === id) {
  18599. return this.lights[index];
  18600. }
  18601. }
  18602. return null;
  18603. };
  18604. Scene.prototype.getNodeByID = function (id) {
  18605. var mesh = this.getMeshByID(id);
  18606. if (mesh) {
  18607. return mesh;
  18608. }
  18609. var light = this.getLightByID(id);
  18610. if (light) {
  18611. return light;
  18612. }
  18613. var camera = this.getCameraByID(id);
  18614. if (camera) {
  18615. return camera;
  18616. }
  18617. var bone = this.getBoneByID(id);
  18618. return bone;
  18619. };
  18620. Scene.prototype.getNodeByName = function (name) {
  18621. var mesh = this.getMeshByName(name);
  18622. if (mesh) {
  18623. return mesh;
  18624. }
  18625. var light = this.getLightByName(name);
  18626. if (light) {
  18627. return light;
  18628. }
  18629. var camera = this.getCameraByName(name);
  18630. if (camera) {
  18631. return camera;
  18632. }
  18633. var bone = this.getBoneByName(name);
  18634. return bone;
  18635. };
  18636. Scene.prototype.getMeshByName = function (name) {
  18637. for (var index = 0; index < this.meshes.length; index++) {
  18638. if (this.meshes[index].name === name) {
  18639. return this.meshes[index];
  18640. }
  18641. }
  18642. return null;
  18643. };
  18644. Scene.prototype.getSoundByName = function (name) {
  18645. var index;
  18646. if (BABYLON.AudioEngine) {
  18647. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18648. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18649. return this.mainSoundTrack.soundCollection[index];
  18650. }
  18651. }
  18652. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18653. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18654. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18655. return this.soundTracks[sdIndex].soundCollection[index];
  18656. }
  18657. }
  18658. }
  18659. }
  18660. return null;
  18661. };
  18662. Scene.prototype.getLastSkeletonByID = function (id) {
  18663. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18664. if (this.skeletons[index].id === id) {
  18665. return this.skeletons[index];
  18666. }
  18667. }
  18668. return null;
  18669. };
  18670. Scene.prototype.getSkeletonById = function (id) {
  18671. for (var index = 0; index < this.skeletons.length; index++) {
  18672. if (this.skeletons[index].id === id) {
  18673. return this.skeletons[index];
  18674. }
  18675. }
  18676. return null;
  18677. };
  18678. Scene.prototype.getSkeletonByName = function (name) {
  18679. for (var index = 0; index < this.skeletons.length; index++) {
  18680. if (this.skeletons[index].name === name) {
  18681. return this.skeletons[index];
  18682. }
  18683. }
  18684. return null;
  18685. };
  18686. Scene.prototype.isActiveMesh = function (mesh) {
  18687. return (this._activeMeshes.indexOf(mesh) !== -1);
  18688. };
  18689. Object.defineProperty(Scene.prototype, "uid", {
  18690. /**
  18691. * Return a unique id as a string which can serve as an identifier for the scene
  18692. */
  18693. get: function () {
  18694. if (!this._uid) {
  18695. this._uid = BABYLON.Tools.RandomId();
  18696. }
  18697. return this._uid;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. /**
  18703. * Add an externaly attached data from its key.
  18704. * This method call will fail and return false, if such key already exists.
  18705. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18706. * @param key the unique key that identifies the data
  18707. * @param data the data object to associate to the key for this Engine instance
  18708. * @return true if no such key were already present and the data was added successfully, false otherwise
  18709. */
  18710. Scene.prototype.addExternalData = function (key, data) {
  18711. return this._externalData.add(key, data);
  18712. };
  18713. /**
  18714. * Get an externaly attached data from its key
  18715. * @param key the unique key that identifies the data
  18716. * @return the associated data, if present (can be null), or undefined if not present
  18717. */
  18718. Scene.prototype.getExternalData = function (key) {
  18719. return this._externalData.get(key);
  18720. };
  18721. /**
  18722. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18723. * @param key the unique key that identifies the data
  18724. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18725. * @return the associated data, can be null if the factory returned null.
  18726. */
  18727. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18728. return this._externalData.getOrAddWithFactory(key, factory);
  18729. };
  18730. /**
  18731. * Remove an externaly attached data from the Engine instance
  18732. * @param key the unique key that identifies the data
  18733. * @return true if the data was successfully removed, false if it doesn't exist
  18734. */
  18735. Scene.prototype.removeExternalData = function (key) {
  18736. return this._externalData.remove(key);
  18737. };
  18738. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18739. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18740. var material = subMesh.getMaterial();
  18741. if (mesh.showSubMeshesBoundingBox) {
  18742. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18743. }
  18744. if (material) {
  18745. // Render targets
  18746. if (material.getRenderTargetTextures) {
  18747. if (this._processedMaterials.indexOf(material) === -1) {
  18748. this._processedMaterials.push(material);
  18749. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18750. }
  18751. }
  18752. // Dispatch
  18753. this._activeIndices.addCount(subMesh.indexCount, false);
  18754. this._renderingManager.dispatch(subMesh);
  18755. }
  18756. }
  18757. };
  18758. Scene.prototype._isInIntermediateRendering = function () {
  18759. return this._intermediateRendering;
  18760. };
  18761. Scene.prototype._evaluateActiveMeshes = function () {
  18762. this.activeCamera._activeMeshes.reset();
  18763. this._activeMeshes.reset();
  18764. this._renderingManager.reset();
  18765. this._processedMaterials.reset();
  18766. this._activeParticleSystems.reset();
  18767. this._activeSkeletons.reset();
  18768. this._softwareSkinnedMeshes.reset();
  18769. this._boundingBoxRenderer.reset();
  18770. this._edgesRenderers.reset();
  18771. // Meshes
  18772. var meshes;
  18773. var len;
  18774. if (this._selectionOctree) {
  18775. var selection = this._selectionOctree.select(this._frustumPlanes);
  18776. meshes = selection.data;
  18777. len = selection.length;
  18778. }
  18779. else {
  18780. len = this.meshes.length;
  18781. meshes = this.meshes;
  18782. }
  18783. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18784. var mesh = meshes[meshIndex];
  18785. if (mesh.isBlocked) {
  18786. continue;
  18787. }
  18788. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18789. if (!mesh.isReady() || !mesh.isEnabled()) {
  18790. continue;
  18791. }
  18792. mesh.computeWorldMatrix();
  18793. // Intersections
  18794. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18795. this._meshesForIntersections.pushNoDuplicate(mesh);
  18796. }
  18797. // Switch to current LOD
  18798. var meshLOD = mesh.getLOD(this.activeCamera);
  18799. if (!meshLOD) {
  18800. continue;
  18801. }
  18802. mesh._preActivate();
  18803. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18804. this._activeMeshes.push(mesh);
  18805. this.activeCamera._activeMeshes.push(mesh);
  18806. mesh._activate(this._renderId);
  18807. this._activeMesh(mesh, meshLOD);
  18808. }
  18809. }
  18810. // Particle systems
  18811. this._particlesDuration.beginMonitoring();
  18812. var beforeParticlesDate = BABYLON.Tools.Now;
  18813. if (this.particlesEnabled) {
  18814. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18815. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18816. var particleSystem = this.particleSystems[particleIndex];
  18817. if (!particleSystem.isStarted()) {
  18818. continue;
  18819. }
  18820. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18821. this._activeParticleSystems.push(particleSystem);
  18822. particleSystem.animate();
  18823. this._renderingManager.dispatchParticles(particleSystem);
  18824. }
  18825. }
  18826. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18827. }
  18828. this._particlesDuration.endMonitoring(false);
  18829. };
  18830. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18831. if (mesh.skeleton && this.skeletonsEnabled) {
  18832. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18833. mesh.skeleton.prepare();
  18834. }
  18835. if (!mesh.computeBonesUsingShaders) {
  18836. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18837. }
  18838. }
  18839. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18840. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18841. }
  18842. if (sourceMesh._edgesRenderer) {
  18843. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18844. }
  18845. if (mesh && mesh.subMeshes) {
  18846. // Submeshes Octrees
  18847. var len;
  18848. var subMeshes;
  18849. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18850. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18851. len = intersections.length;
  18852. subMeshes = intersections.data;
  18853. }
  18854. else {
  18855. subMeshes = mesh.subMeshes;
  18856. len = subMeshes.length;
  18857. }
  18858. for (var subIndex = 0; subIndex < len; subIndex++) {
  18859. var subMesh = subMeshes[subIndex];
  18860. this._evaluateSubMesh(subMesh, mesh);
  18861. }
  18862. }
  18863. };
  18864. Scene.prototype.updateTransformMatrix = function (force) {
  18865. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18866. };
  18867. Scene.prototype._renderForCamera = function (camera) {
  18868. var engine = this._engine;
  18869. var startTime = BABYLON.Tools.Now;
  18870. this.activeCamera = camera;
  18871. if (!this.activeCamera)
  18872. throw new Error("Active camera not set");
  18873. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18874. // Viewport
  18875. engine.setViewport(this.activeCamera.viewport);
  18876. // Camera
  18877. this.resetCachedMaterial();
  18878. this._renderId++;
  18879. this.updateTransformMatrix();
  18880. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18881. // Meshes
  18882. this._evaluateActiveMeshesDuration.beginMonitoring();
  18883. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18884. this._evaluateActiveMeshes();
  18885. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18886. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18887. // Software skinning
  18888. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18889. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18890. mesh.applySkeleton(mesh.skeleton);
  18891. }
  18892. // Render targets
  18893. this._renderTargetsDuration.beginMonitoring();
  18894. var needsRestoreFrameBuffer = false;
  18895. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18896. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18897. this._intermediateRendering = true;
  18898. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18899. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18900. var renderTarget = this._renderTargets.data[renderIndex];
  18901. if (renderTarget._shouldRender()) {
  18902. this._renderId++;
  18903. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18904. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18905. }
  18906. }
  18907. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18908. this._intermediateRendering = false;
  18909. this._renderId++;
  18910. needsRestoreFrameBuffer = true; // Restore back buffer
  18911. }
  18912. // Render HighlightLayer Texture
  18913. var stencilState = this._engine.getStencilBuffer();
  18914. var renderhighlights = false;
  18915. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18916. this._intermediateRendering = true;
  18917. for (var i = 0; i < this.highlightLayers.length; i++) {
  18918. var highlightLayer = this.highlightLayers[i];
  18919. if (highlightLayer.shouldRender() &&
  18920. (!highlightLayer.camera ||
  18921. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18922. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18923. renderhighlights = true;
  18924. var renderTarget = highlightLayer._mainTexture;
  18925. if (renderTarget._shouldRender()) {
  18926. this._renderId++;
  18927. renderTarget.render(false, false);
  18928. needsRestoreFrameBuffer = true;
  18929. }
  18930. }
  18931. }
  18932. this._intermediateRendering = false;
  18933. this._renderId++;
  18934. }
  18935. if (needsRestoreFrameBuffer) {
  18936. engine.restoreDefaultFramebuffer();
  18937. }
  18938. this._renderTargetsDuration.endMonitoring(false);
  18939. // Prepare Frame
  18940. this.postProcessManager._prepareFrame();
  18941. this._renderDuration.beginMonitoring();
  18942. // Backgrounds
  18943. var layerIndex;
  18944. var layer;
  18945. if (this.layers.length) {
  18946. engine.setDepthBuffer(false);
  18947. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18948. layer = this.layers[layerIndex];
  18949. if (layer.isBackground) {
  18950. layer.render();
  18951. }
  18952. }
  18953. engine.setDepthBuffer(true);
  18954. }
  18955. // Render
  18956. BABYLON.Tools.StartPerformanceCounter("Main render");
  18957. // Activate HighlightLayer stencil
  18958. if (renderhighlights) {
  18959. this._engine.setStencilBuffer(true);
  18960. }
  18961. this._renderingManager.render(null, null, true, true);
  18962. // Restore HighlightLayer stencil
  18963. if (renderhighlights) {
  18964. this._engine.setStencilBuffer(stencilState);
  18965. }
  18966. BABYLON.Tools.EndPerformanceCounter("Main render");
  18967. // Bounding boxes
  18968. this._boundingBoxRenderer.render();
  18969. // Edges
  18970. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18971. this._edgesRenderers.data[edgesRendererIndex].render();
  18972. }
  18973. // Lens flares
  18974. if (this.lensFlaresEnabled) {
  18975. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18976. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18977. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18978. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18979. lensFlareSystem.render();
  18980. }
  18981. }
  18982. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18983. }
  18984. // Foregrounds
  18985. if (this.layers.length) {
  18986. engine.setDepthBuffer(false);
  18987. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18988. layer = this.layers[layerIndex];
  18989. if (!layer.isBackground) {
  18990. layer.render();
  18991. }
  18992. }
  18993. engine.setDepthBuffer(true);
  18994. }
  18995. // Highlight Layer
  18996. if (renderhighlights) {
  18997. engine.setDepthBuffer(false);
  18998. for (var i = 0; i < this.highlightLayers.length; i++) {
  18999. if (this.highlightLayers[i].shouldRender()) {
  19000. this.highlightLayers[i].render();
  19001. }
  19002. }
  19003. engine.setDepthBuffer(true);
  19004. }
  19005. this._renderDuration.endMonitoring(false);
  19006. // Finalize frame
  19007. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19008. // Update camera
  19009. this.activeCamera._updateFromScene();
  19010. // Reset some special arrays
  19011. this._renderTargets.reset();
  19012. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19013. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19014. };
  19015. Scene.prototype._processSubCameras = function (camera) {
  19016. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19017. this._renderForCamera(camera);
  19018. return;
  19019. }
  19020. // rig cameras
  19021. for (var index = 0; index < camera._rigCameras.length; index++) {
  19022. this._renderForCamera(camera._rigCameras[index]);
  19023. }
  19024. this.activeCamera = camera;
  19025. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19026. // Update camera
  19027. this.activeCamera._updateFromScene();
  19028. };
  19029. Scene.prototype._checkIntersections = function () {
  19030. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19031. var sourceMesh = this._meshesForIntersections.data[index];
  19032. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19033. var action = sourceMesh.actionManager.actions[actionIndex];
  19034. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19035. var parameters = action.getTriggerParameter();
  19036. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19037. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19038. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19039. if (areIntersecting && currentIntersectionInProgress === -1) {
  19040. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19041. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19042. sourceMesh._intersectionsInProgress.push(otherMesh);
  19043. }
  19044. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19045. sourceMesh._intersectionsInProgress.push(otherMesh);
  19046. }
  19047. }
  19048. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19049. //They intersected, and now they don't.
  19050. //is this trigger an exit trigger? execute an event.
  19051. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19052. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19053. }
  19054. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19055. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19056. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19057. }
  19058. }
  19059. }
  19060. }
  19061. }
  19062. };
  19063. Scene.prototype.render = function () {
  19064. this._lastFrameDuration.beginMonitoring();
  19065. this._particlesDuration.fetchNewFrame();
  19066. this._spritesDuration.fetchNewFrame();
  19067. this._activeParticles.fetchNewFrame();
  19068. this._renderDuration.fetchNewFrame();
  19069. this._renderTargetsDuration.fetchNewFrame();
  19070. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19071. this._totalVertices.fetchNewFrame();
  19072. this._activeIndices.fetchNewFrame();
  19073. this._activeBones.fetchNewFrame();
  19074. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19075. this._meshesForIntersections.reset();
  19076. this.resetCachedMaterial();
  19077. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19078. // Actions
  19079. if (this.actionManager) {
  19080. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19081. }
  19082. //Simplification Queue
  19083. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19084. this.simplificationQueue.executeNext();
  19085. }
  19086. // Animations
  19087. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19088. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19089. this._animate();
  19090. // Physics
  19091. if (this._physicsEngine) {
  19092. BABYLON.Tools.StartPerformanceCounter("Physics");
  19093. this._physicsEngine._step(deltaTime / 1000.0);
  19094. BABYLON.Tools.EndPerformanceCounter("Physics");
  19095. }
  19096. // Before render
  19097. this.onBeforeRenderObservable.notifyObservers(this);
  19098. // Customs render targets
  19099. this._renderTargetsDuration.beginMonitoring();
  19100. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19101. var engine = this.getEngine();
  19102. var currentActiveCamera = this.activeCamera;
  19103. if (this.renderTargetsEnabled) {
  19104. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19105. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19106. var renderTarget = this.customRenderTargets[customIndex];
  19107. if (renderTarget._shouldRender()) {
  19108. this._renderId++;
  19109. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19110. if (!this.activeCamera)
  19111. throw new Error("Active camera not set");
  19112. // Viewport
  19113. engine.setViewport(this.activeCamera.viewport);
  19114. // Camera
  19115. this.updateTransformMatrix();
  19116. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19117. }
  19118. }
  19119. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19120. this._renderId++;
  19121. }
  19122. if (this.customRenderTargets.length > 0) {
  19123. engine.restoreDefaultFramebuffer();
  19124. }
  19125. this._renderTargetsDuration.endMonitoring();
  19126. this.activeCamera = currentActiveCamera;
  19127. // Procedural textures
  19128. if (this.proceduralTexturesEnabled) {
  19129. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19130. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19131. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19132. if (proceduralTexture._shouldRender()) {
  19133. proceduralTexture.render();
  19134. }
  19135. }
  19136. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19137. }
  19138. // Clear
  19139. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  19140. // Shadows
  19141. if (this.shadowsEnabled) {
  19142. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19143. var light = this.lights[lightIndex];
  19144. var shadowGenerator = light.getShadowGenerator();
  19145. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  19146. this._renderTargets.push(shadowGenerator.getShadowMap());
  19147. }
  19148. }
  19149. }
  19150. // Depth renderer
  19151. if (this._depthRenderer) {
  19152. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19153. }
  19154. // RenderPipeline
  19155. this.postProcessRenderPipelineManager.update();
  19156. // Multi-cameras?
  19157. if (this.activeCameras.length > 0) {
  19158. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19159. if (cameraIndex > 0) {
  19160. this._engine.clear(null, false, true, true);
  19161. }
  19162. this._processSubCameras(this.activeCameras[cameraIndex]);
  19163. }
  19164. }
  19165. else {
  19166. if (!this.activeCamera) {
  19167. throw new Error("No camera defined");
  19168. }
  19169. this._processSubCameras(this.activeCamera);
  19170. }
  19171. // Intersection checks
  19172. this._checkIntersections();
  19173. // Update the audio listener attached to the camera
  19174. if (BABYLON.AudioEngine) {
  19175. this._updateAudioParameters();
  19176. }
  19177. // After render
  19178. if (this.afterRender) {
  19179. this.afterRender();
  19180. }
  19181. this.onAfterRenderObservable.notifyObservers(this);
  19182. // Cleaning
  19183. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19184. this._toBeDisposed.data[index].dispose();
  19185. this._toBeDisposed[index] = null;
  19186. }
  19187. this._toBeDisposed.reset();
  19188. if (this.dumpNextRenderTargets) {
  19189. this.dumpNextRenderTargets = false;
  19190. }
  19191. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19192. this._lastFrameDuration.endMonitoring();
  19193. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19194. this._totalLightsCounter.addCount(this.lights.length, true);
  19195. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19196. this._totalTexturesCounter.addCount(this.textures.length, true);
  19197. this._activeBones.addCount(0, true);
  19198. this._activeIndices.addCount(0, true);
  19199. this._activeParticles.addCount(0, true);
  19200. };
  19201. Scene.prototype._updateAudioParameters = function () {
  19202. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19203. return;
  19204. }
  19205. var listeningCamera;
  19206. var audioEngine = BABYLON.Engine.audioEngine;
  19207. if (this.activeCameras.length > 0) {
  19208. listeningCamera = this.activeCameras[0];
  19209. }
  19210. else {
  19211. listeningCamera = this.activeCamera;
  19212. }
  19213. if (listeningCamera && audioEngine.canUseWebAudio) {
  19214. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19215. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19216. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19217. cameraDirection.normalize();
  19218. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19219. var i;
  19220. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19221. var sound = this.mainSoundTrack.soundCollection[i];
  19222. if (sound.useCustomAttenuation) {
  19223. sound.updateDistanceFromListener();
  19224. }
  19225. }
  19226. for (i = 0; i < this.soundTracks.length; i++) {
  19227. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19228. sound = this.soundTracks[i].soundCollection[j];
  19229. if (sound.useCustomAttenuation) {
  19230. sound.updateDistanceFromListener();
  19231. }
  19232. }
  19233. }
  19234. }
  19235. };
  19236. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19237. // Audio
  19238. get: function () {
  19239. return this._audioEnabled;
  19240. },
  19241. set: function (value) {
  19242. this._audioEnabled = value;
  19243. if (BABYLON.AudioEngine) {
  19244. if (this._audioEnabled) {
  19245. this._enableAudio();
  19246. }
  19247. else {
  19248. this._disableAudio();
  19249. }
  19250. }
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Scene.prototype._disableAudio = function () {
  19256. var i;
  19257. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19258. this.mainSoundTrack.soundCollection[i].pause();
  19259. }
  19260. for (i = 0; i < this.soundTracks.length; i++) {
  19261. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19262. this.soundTracks[i].soundCollection[j].pause();
  19263. }
  19264. }
  19265. };
  19266. Scene.prototype._enableAudio = function () {
  19267. var i;
  19268. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19269. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19270. this.mainSoundTrack.soundCollection[i].play();
  19271. }
  19272. }
  19273. for (i = 0; i < this.soundTracks.length; i++) {
  19274. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19275. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19276. this.soundTracks[i].soundCollection[j].play();
  19277. }
  19278. }
  19279. }
  19280. };
  19281. Object.defineProperty(Scene.prototype, "headphone", {
  19282. get: function () {
  19283. return this._headphone;
  19284. },
  19285. set: function (value) {
  19286. this._headphone = value;
  19287. if (BABYLON.AudioEngine) {
  19288. if (this._headphone) {
  19289. this._switchAudioModeForHeadphones();
  19290. }
  19291. else {
  19292. this._switchAudioModeForNormalSpeakers();
  19293. }
  19294. }
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Scene.prototype._switchAudioModeForHeadphones = function () {
  19300. this.mainSoundTrack.switchPanningModelToHRTF();
  19301. for (var i = 0; i < this.soundTracks.length; i++) {
  19302. this.soundTracks[i].switchPanningModelToHRTF();
  19303. }
  19304. };
  19305. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19306. this.mainSoundTrack.switchPanningModelToEqualPower();
  19307. for (var i = 0; i < this.soundTracks.length; i++) {
  19308. this.soundTracks[i].switchPanningModelToEqualPower();
  19309. }
  19310. };
  19311. Scene.prototype.enableDepthRenderer = function () {
  19312. if (this._depthRenderer) {
  19313. return this._depthRenderer;
  19314. }
  19315. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19316. return this._depthRenderer;
  19317. };
  19318. Scene.prototype.disableDepthRenderer = function () {
  19319. if (!this._depthRenderer) {
  19320. return;
  19321. }
  19322. this._depthRenderer.dispose();
  19323. this._depthRenderer = null;
  19324. };
  19325. Scene.prototype.freezeMaterials = function () {
  19326. for (var i = 0; i < this.materials.length; i++) {
  19327. this.materials[i].freeze();
  19328. }
  19329. };
  19330. Scene.prototype.unfreezeMaterials = function () {
  19331. for (var i = 0; i < this.materials.length; i++) {
  19332. this.materials[i].unfreeze();
  19333. }
  19334. };
  19335. Scene.prototype.dispose = function () {
  19336. this.beforeRender = null;
  19337. this.afterRender = null;
  19338. this.skeletons = [];
  19339. this._boundingBoxRenderer.dispose();
  19340. if (this._depthRenderer) {
  19341. this._depthRenderer.dispose();
  19342. }
  19343. // Debug layer
  19344. if (this._debugLayer) {
  19345. this._debugLayer.hide();
  19346. }
  19347. // Events
  19348. this.onDisposeObservable.notifyObservers(this);
  19349. this.onDisposeObservable.clear();
  19350. this.onBeforeRenderObservable.clear();
  19351. this.onAfterRenderObservable.clear();
  19352. this.detachControl();
  19353. // Release sounds & sounds tracks
  19354. if (BABYLON.AudioEngine) {
  19355. this.disposeSounds();
  19356. }
  19357. // Detach cameras
  19358. var canvas = this._engine.getRenderingCanvas();
  19359. var index;
  19360. for (index = 0; index < this.cameras.length; index++) {
  19361. this.cameras[index].detachControl(canvas);
  19362. }
  19363. // Release lights
  19364. while (this.lights.length) {
  19365. this.lights[0].dispose();
  19366. }
  19367. // Release meshes
  19368. while (this.meshes.length) {
  19369. this.meshes[0].dispose(true);
  19370. }
  19371. // Release cameras
  19372. while (this.cameras.length) {
  19373. this.cameras[0].dispose();
  19374. }
  19375. // Release materials
  19376. while (this.materials.length) {
  19377. this.materials[0].dispose();
  19378. }
  19379. // Release particles
  19380. while (this.particleSystems.length) {
  19381. this.particleSystems[0].dispose();
  19382. }
  19383. // Release sprites
  19384. while (this.spriteManagers.length) {
  19385. this.spriteManagers[0].dispose();
  19386. }
  19387. // Release layers
  19388. while (this.layers.length) {
  19389. this.layers[0].dispose();
  19390. }
  19391. while (this.highlightLayers.length) {
  19392. this.highlightLayers[0].dispose();
  19393. }
  19394. // Release textures
  19395. while (this.textures.length) {
  19396. this.textures[0].dispose();
  19397. }
  19398. // Post-processes
  19399. this.postProcessManager.dispose();
  19400. // Physics
  19401. if (this._physicsEngine) {
  19402. this.disablePhysicsEngine();
  19403. }
  19404. // Remove from engine
  19405. index = this._engine.scenes.indexOf(this);
  19406. if (index > -1) {
  19407. this._engine.scenes.splice(index, 1);
  19408. }
  19409. this._engine.wipeCaches();
  19410. };
  19411. // Release sounds & sounds tracks
  19412. Scene.prototype.disposeSounds = function () {
  19413. this.mainSoundTrack.dispose();
  19414. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19415. this.soundTracks[scIndex].dispose();
  19416. }
  19417. };
  19418. // Octrees
  19419. Scene.prototype.getWorldExtends = function () {
  19420. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19421. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19422. for (var index = 0; index < this.meshes.length; index++) {
  19423. var mesh = this.meshes[index];
  19424. mesh.computeWorldMatrix(true);
  19425. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19426. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19427. BABYLON.Tools.CheckExtends(minBox, min, max);
  19428. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19429. }
  19430. return {
  19431. min: min,
  19432. max: max
  19433. };
  19434. };
  19435. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19436. if (maxCapacity === void 0) { maxCapacity = 64; }
  19437. if (maxDepth === void 0) { maxDepth = 2; }
  19438. if (!this._selectionOctree) {
  19439. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19440. }
  19441. var worldExtends = this.getWorldExtends();
  19442. // Update octree
  19443. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19444. return this._selectionOctree;
  19445. };
  19446. // Picking
  19447. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19448. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19449. var engine = this._engine;
  19450. if (!camera) {
  19451. if (!this.activeCamera)
  19452. throw new Error("Active camera not set");
  19453. camera = this.activeCamera;
  19454. }
  19455. var cameraViewport = camera.viewport;
  19456. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19457. // Moving coordinates to local viewport world
  19458. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19459. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19460. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19461. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19462. };
  19463. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19464. var engine = this._engine;
  19465. if (!camera) {
  19466. if (!this.activeCamera)
  19467. throw new Error("Active camera not set");
  19468. camera = this.activeCamera;
  19469. }
  19470. var cameraViewport = camera.viewport;
  19471. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19472. var identity = BABYLON.Matrix.Identity();
  19473. // Moving coordinates to local viewport world
  19474. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19475. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19476. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19477. };
  19478. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19479. var pickingInfo = null;
  19480. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19481. var mesh = this.meshes[meshIndex];
  19482. if (predicate) {
  19483. if (!predicate(mesh)) {
  19484. continue;
  19485. }
  19486. }
  19487. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19488. continue;
  19489. }
  19490. var world = mesh.getWorldMatrix();
  19491. var ray = rayFunction(world);
  19492. var result = mesh.intersects(ray, fastCheck);
  19493. if (!result || !result.hit)
  19494. continue;
  19495. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19496. continue;
  19497. pickingInfo = result;
  19498. if (fastCheck) {
  19499. break;
  19500. }
  19501. }
  19502. return pickingInfo || new BABYLON.PickingInfo();
  19503. };
  19504. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19505. var pickingInfos = new Array();
  19506. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19507. var mesh = this.meshes[meshIndex];
  19508. if (predicate) {
  19509. if (!predicate(mesh)) {
  19510. continue;
  19511. }
  19512. }
  19513. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19514. continue;
  19515. }
  19516. var world = mesh.getWorldMatrix();
  19517. var ray = rayFunction(world);
  19518. var result = mesh.intersects(ray, false);
  19519. if (!result || !result.hit)
  19520. continue;
  19521. pickingInfos.push(result);
  19522. }
  19523. return pickingInfos;
  19524. };
  19525. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19526. var pickingInfo = null;
  19527. camera = camera || this.activeCamera;
  19528. if (this.spriteManagers.length > 0) {
  19529. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19530. var spriteManager = this.spriteManagers[spriteIndex];
  19531. if (!spriteManager.isPickable) {
  19532. continue;
  19533. }
  19534. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19535. if (!result || !result.hit)
  19536. continue;
  19537. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19538. continue;
  19539. pickingInfo = result;
  19540. if (fastCheck) {
  19541. break;
  19542. }
  19543. }
  19544. }
  19545. return pickingInfo || new BABYLON.PickingInfo();
  19546. };
  19547. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19548. /// <param name="x">X position on screen</param>
  19549. /// <param name="y">Y position on screen</param>
  19550. /// <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>
  19551. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19552. /// <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>
  19553. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19554. var _this = this;
  19555. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19556. };
  19557. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19558. /// <param name="x">X position on screen</param>
  19559. /// <param name="y">Y position on screen</param>
  19560. /// <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>
  19561. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19562. /// <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>
  19563. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19564. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19565. };
  19566. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19567. var _this = this;
  19568. return this._internalPick(function (world) {
  19569. if (!_this._pickWithRayInverseMatrix) {
  19570. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19571. }
  19572. world.invertToRef(_this._pickWithRayInverseMatrix);
  19573. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19574. }, predicate, fastCheck);
  19575. };
  19576. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19577. /// <param name="x">X position on screen</param>
  19578. /// <param name="y">Y position on screen</param>
  19579. /// <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>
  19580. /// <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>
  19581. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19582. var _this = this;
  19583. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19584. };
  19585. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19586. /// <param name="ray">Ray to use</param>
  19587. /// <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>
  19588. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19589. var _this = this;
  19590. return this._internalMultiPick(function (world) {
  19591. if (!_this._pickWithRayInverseMatrix) {
  19592. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19593. }
  19594. world.invertToRef(_this._pickWithRayInverseMatrix);
  19595. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19596. }, predicate);
  19597. };
  19598. Scene.prototype.setPointerOverMesh = function (mesh) {
  19599. if (this._pointerOverMesh === mesh) {
  19600. return;
  19601. }
  19602. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19603. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19604. }
  19605. this._pointerOverMesh = mesh;
  19606. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19607. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19608. }
  19609. };
  19610. Scene.prototype.getPointerOverMesh = function () {
  19611. return this._pointerOverMesh;
  19612. };
  19613. Scene.prototype.setPointerOverSprite = function (sprite) {
  19614. if (this._pointerOverSprite === sprite) {
  19615. return;
  19616. }
  19617. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19618. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19619. }
  19620. this._pointerOverSprite = sprite;
  19621. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19622. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19623. }
  19624. };
  19625. Scene.prototype.getPointerOverSprite = function () {
  19626. return this._pointerOverSprite;
  19627. };
  19628. // Physics
  19629. Scene.prototype.getPhysicsEngine = function () {
  19630. return this._physicsEngine;
  19631. };
  19632. /**
  19633. * Enables physics to the current scene
  19634. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19635. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19636. * @return {boolean} was the physics engine initialized
  19637. */
  19638. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19639. if (this._physicsEngine) {
  19640. return true;
  19641. }
  19642. try {
  19643. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19644. return true;
  19645. }
  19646. catch (e) {
  19647. BABYLON.Tools.Error(e.message);
  19648. return false;
  19649. }
  19650. };
  19651. Scene.prototype.disablePhysicsEngine = function () {
  19652. if (!this._physicsEngine) {
  19653. return;
  19654. }
  19655. this._physicsEngine.dispose();
  19656. this._physicsEngine = undefined;
  19657. };
  19658. Scene.prototype.isPhysicsEnabled = function () {
  19659. return this._physicsEngine !== undefined;
  19660. };
  19661. /**
  19662. *
  19663. * Sets the gravity of the physics engine (and NOT of the scene)
  19664. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19665. */
  19666. Scene.prototype.setGravity = function (gravity) {
  19667. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19668. if (!this._physicsEngine) {
  19669. return;
  19670. }
  19671. this._physicsEngine.setGravity(gravity);
  19672. };
  19673. /**
  19674. * Legacy support, using the new API
  19675. * @Deprecated
  19676. */
  19677. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19678. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19679. if (parts.parts) {
  19680. options = parts;
  19681. parts = parts.parts;
  19682. }
  19683. var mainMesh = parts[0].mesh;
  19684. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19685. for (var index = 1; index < parts.length; index++) {
  19686. var mesh = parts[index].mesh;
  19687. if (mesh.parent !== mainMesh) {
  19688. mesh.position = mesh.position.subtract(mainMesh.position);
  19689. mesh.parent = mainMesh;
  19690. }
  19691. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19692. }
  19693. mainMesh.physicsImpostor.forceUpdate();
  19694. };
  19695. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19696. var mesh = compound.parts[0].mesh;
  19697. mesh.physicsImpostor.dispose();
  19698. mesh.physicsImpostor = null;
  19699. };
  19700. // Misc.
  19701. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19702. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19703. // Light
  19704. if (this.lights.length === 0) {
  19705. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19706. }
  19707. // Camera
  19708. if (!this.activeCamera) {
  19709. // Compute position
  19710. var worldExtends = this.getWorldExtends();
  19711. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19712. var camera;
  19713. if (createArcRotateCamera) {
  19714. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19715. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19716. camera.setTarget(worldCenter);
  19717. }
  19718. else {
  19719. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19720. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19721. camera.setTarget(worldCenter);
  19722. }
  19723. this.activeCamera = camera;
  19724. }
  19725. };
  19726. // Tags
  19727. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19728. if (tagsQuery === undefined) {
  19729. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19730. return list;
  19731. }
  19732. var listByTags = [];
  19733. forEach = forEach || (function (item) { return; });
  19734. for (var i in list) {
  19735. var item = list[i];
  19736. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19737. listByTags.push(item);
  19738. forEach(item);
  19739. }
  19740. }
  19741. return listByTags;
  19742. };
  19743. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19744. return this._getByTags(this.meshes, tagsQuery, forEach);
  19745. };
  19746. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19747. return this._getByTags(this.cameras, tagsQuery, forEach);
  19748. };
  19749. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19750. return this._getByTags(this.lights, tagsQuery, forEach);
  19751. };
  19752. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19753. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19754. };
  19755. /**
  19756. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19757. * This allowed control for front to back rendering or reversly depending of the special needs.
  19758. *
  19759. * @param renderingGroupId The rendering group id corresponding to its index
  19760. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19761. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19762. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19763. */
  19764. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19765. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19766. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19767. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19768. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19769. };
  19770. /**
  19771. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19772. *
  19773. * @param renderingGroupId The rendering group id corresponding to its index
  19774. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19775. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19776. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19777. */
  19778. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19779. if (depth === void 0) { depth = true; }
  19780. if (stencil === void 0) { stencil = true; }
  19781. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19782. };
  19783. return Scene;
  19784. }());
  19785. // Statics
  19786. Scene._FOGMODE_NONE = 0;
  19787. Scene._FOGMODE_EXP = 1;
  19788. Scene._FOGMODE_EXP2 = 2;
  19789. Scene._FOGMODE_LINEAR = 3;
  19790. Scene.MinDeltaTime = 1.0;
  19791. Scene.MaxDeltaTime = 1000.0;
  19792. BABYLON.Scene = Scene;
  19793. })(BABYLON || (BABYLON = {}));
  19794. //# sourceMappingURL=babylon.scene.js.map
  19795. var BABYLON;
  19796. (function (BABYLON) {
  19797. var Buffer = (function () {
  19798. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19799. if (engine instanceof BABYLON.Mesh) {
  19800. this._engine = engine.getScene().getEngine();
  19801. }
  19802. else {
  19803. this._engine = engine;
  19804. }
  19805. this._updatable = updatable;
  19806. this._data = data;
  19807. this._strideSize = stride;
  19808. if (!postponeInternalCreation) {
  19809. this.create();
  19810. }
  19811. this._instanced = instanced;
  19812. }
  19813. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19814. // a lot of these parameters are ignored as they are overriden by the buffer
  19815. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19816. };
  19817. // Properties
  19818. Buffer.prototype.isUpdatable = function () {
  19819. return this._updatable;
  19820. };
  19821. Buffer.prototype.getData = function () {
  19822. return this._data;
  19823. };
  19824. Buffer.prototype.getBuffer = function () {
  19825. return this._buffer;
  19826. };
  19827. Buffer.prototype.getStrideSize = function () {
  19828. return this._strideSize;
  19829. };
  19830. Buffer.prototype.getIsInstanced = function () {
  19831. return this._instanced;
  19832. };
  19833. // Methods
  19834. Buffer.prototype.create = function (data) {
  19835. if (!data && this._buffer) {
  19836. return; // nothing to do
  19837. }
  19838. data = data || this._data;
  19839. if (!this._buffer) {
  19840. if (this._updatable) {
  19841. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19842. this._data = data;
  19843. }
  19844. else {
  19845. this._buffer = this._engine.createVertexBuffer(data);
  19846. }
  19847. }
  19848. else if (this._updatable) {
  19849. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19850. this._data = data;
  19851. }
  19852. };
  19853. Buffer.prototype.update = function (data) {
  19854. this.create(data);
  19855. };
  19856. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19857. if (!this._buffer) {
  19858. return;
  19859. }
  19860. if (this._updatable) {
  19861. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19862. this._data = null;
  19863. }
  19864. };
  19865. Buffer.prototype.dispose = function () {
  19866. if (!this._buffer) {
  19867. return;
  19868. }
  19869. if (this._engine._releaseBuffer(this._buffer)) {
  19870. this._buffer = null;
  19871. }
  19872. };
  19873. return Buffer;
  19874. }());
  19875. BABYLON.Buffer = Buffer;
  19876. })(BABYLON || (BABYLON = {}));
  19877. //# sourceMappingURL=babylon.buffer.js.map
  19878. var BABYLON;
  19879. (function (BABYLON) {
  19880. var VertexBuffer = (function () {
  19881. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19882. if (!stride) {
  19883. // Deduce stride from kind
  19884. switch (kind) {
  19885. case VertexBuffer.PositionKind:
  19886. stride = 3;
  19887. break;
  19888. case VertexBuffer.NormalKind:
  19889. stride = 3;
  19890. break;
  19891. case VertexBuffer.UVKind:
  19892. case VertexBuffer.UV2Kind:
  19893. case VertexBuffer.UV3Kind:
  19894. case VertexBuffer.UV4Kind:
  19895. case VertexBuffer.UV5Kind:
  19896. case VertexBuffer.UV6Kind:
  19897. stride = 2;
  19898. break;
  19899. case VertexBuffer.ColorKind:
  19900. stride = 4;
  19901. break;
  19902. case VertexBuffer.MatricesIndicesKind:
  19903. case VertexBuffer.MatricesIndicesExtraKind:
  19904. stride = 4;
  19905. break;
  19906. case VertexBuffer.MatricesWeightsKind:
  19907. case VertexBuffer.MatricesWeightsExtraKind:
  19908. stride = 4;
  19909. break;
  19910. }
  19911. }
  19912. if (data instanceof BABYLON.Buffer) {
  19913. if (!stride) {
  19914. stride = data.getStrideSize();
  19915. }
  19916. this._buffer = data;
  19917. this._ownsBuffer = false;
  19918. }
  19919. else {
  19920. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19921. this._ownsBuffer = true;
  19922. }
  19923. this._stride = stride;
  19924. this._offset = offset ? offset : 0;
  19925. this._size = size ? size : stride;
  19926. this._kind = kind;
  19927. }
  19928. VertexBuffer.prototype.getKind = function () {
  19929. return this._kind;
  19930. };
  19931. // Properties
  19932. VertexBuffer.prototype.isUpdatable = function () {
  19933. return this._buffer.isUpdatable();
  19934. };
  19935. VertexBuffer.prototype.getData = function () {
  19936. return this._buffer.getData();
  19937. };
  19938. VertexBuffer.prototype.getBuffer = function () {
  19939. return this._buffer.getBuffer();
  19940. };
  19941. VertexBuffer.prototype.getStrideSize = function () {
  19942. return this._stride;
  19943. };
  19944. VertexBuffer.prototype.getOffset = function () {
  19945. return this._offset;
  19946. };
  19947. VertexBuffer.prototype.getSize = function () {
  19948. return this._size;
  19949. };
  19950. VertexBuffer.prototype.getIsInstanced = function () {
  19951. return this._buffer.getIsInstanced();
  19952. };
  19953. // Methods
  19954. VertexBuffer.prototype.create = function (data) {
  19955. return this._buffer.create(data);
  19956. };
  19957. VertexBuffer.prototype.update = function (data) {
  19958. return this._buffer.update(data);
  19959. };
  19960. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19961. return this._buffer.updateDirectly(data, offset);
  19962. };
  19963. VertexBuffer.prototype.dispose = function () {
  19964. if (this._ownsBuffer) {
  19965. this._buffer.dispose();
  19966. }
  19967. };
  19968. Object.defineProperty(VertexBuffer, "PositionKind", {
  19969. get: function () {
  19970. return VertexBuffer._PositionKind;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(VertexBuffer, "NormalKind", {
  19976. get: function () {
  19977. return VertexBuffer._NormalKind;
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(VertexBuffer, "UVKind", {
  19983. get: function () {
  19984. return VertexBuffer._UVKind;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19990. get: function () {
  19991. return VertexBuffer._UV2Kind;
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19997. get: function () {
  19998. return VertexBuffer._UV3Kind;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20004. get: function () {
  20005. return VertexBuffer._UV4Kind;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20011. get: function () {
  20012. return VertexBuffer._UV5Kind;
  20013. },
  20014. enumerable: true,
  20015. configurable: true
  20016. });
  20017. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20018. get: function () {
  20019. return VertexBuffer._UV6Kind;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(VertexBuffer, "ColorKind", {
  20025. get: function () {
  20026. return VertexBuffer._ColorKind;
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20032. get: function () {
  20033. return VertexBuffer._MatricesIndicesKind;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20039. get: function () {
  20040. return VertexBuffer._MatricesWeightsKind;
  20041. },
  20042. enumerable: true,
  20043. configurable: true
  20044. });
  20045. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20046. get: function () {
  20047. return VertexBuffer._MatricesIndicesExtraKind;
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20053. get: function () {
  20054. return VertexBuffer._MatricesWeightsExtraKind;
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. return VertexBuffer;
  20060. }());
  20061. // Enums
  20062. VertexBuffer._PositionKind = "position";
  20063. VertexBuffer._NormalKind = "normal";
  20064. VertexBuffer._UVKind = "uv";
  20065. VertexBuffer._UV2Kind = "uv2";
  20066. VertexBuffer._UV3Kind = "uv3";
  20067. VertexBuffer._UV4Kind = "uv4";
  20068. VertexBuffer._UV5Kind = "uv5";
  20069. VertexBuffer._UV6Kind = "uv6";
  20070. VertexBuffer._ColorKind = "color";
  20071. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20072. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20073. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20074. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20075. BABYLON.VertexBuffer = VertexBuffer;
  20076. })(BABYLON || (BABYLON = {}));
  20077. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20078. var BABYLON;
  20079. (function (BABYLON) {
  20080. /**
  20081. * Creates an instance based on a source mesh.
  20082. */
  20083. var InstancedMesh = (function (_super) {
  20084. __extends(InstancedMesh, _super);
  20085. function InstancedMesh(name, source) {
  20086. var _this = _super.call(this, name, source.getScene()) || this;
  20087. source.instances.push(_this);
  20088. _this._sourceMesh = source;
  20089. _this.position.copyFrom(source.position);
  20090. _this.rotation.copyFrom(source.rotation);
  20091. _this.scaling.copyFrom(source.scaling);
  20092. if (source.rotationQuaternion) {
  20093. _this.rotationQuaternion = source.rotationQuaternion.clone();
  20094. }
  20095. _this.infiniteDistance = source.infiniteDistance;
  20096. _this.setPivotMatrix(source.getPivotMatrix());
  20097. _this.refreshBoundingInfo();
  20098. _this._syncSubMeshes();
  20099. return _this;
  20100. }
  20101. InstancedMesh.prototype.getClassName = function () {
  20102. return "InstancedMesh";
  20103. };
  20104. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  20105. // Methods
  20106. get: function () {
  20107. return this._sourceMesh.receiveShadows;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(InstancedMesh.prototype, "material", {
  20113. get: function () {
  20114. return this._sourceMesh.material;
  20115. },
  20116. enumerable: true,
  20117. configurable: true
  20118. });
  20119. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  20120. get: function () {
  20121. return this._sourceMesh.visibility;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  20127. get: function () {
  20128. return this._sourceMesh.skeleton;
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  20134. get: function () {
  20135. return this._sourceMesh.renderingGroupId;
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. InstancedMesh.prototype.getTotalVertices = function () {
  20141. return this._sourceMesh.getTotalVertices();
  20142. };
  20143. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  20144. get: function () {
  20145. return this._sourceMesh;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20151. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  20152. };
  20153. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  20154. return this._sourceMesh.isVerticesDataPresent(kind);
  20155. };
  20156. InstancedMesh.prototype.getIndices = function () {
  20157. return this._sourceMesh.getIndices();
  20158. };
  20159. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  20160. get: function () {
  20161. return this._sourceMesh._positions;
  20162. },
  20163. enumerable: true,
  20164. configurable: true
  20165. });
  20166. InstancedMesh.prototype.refreshBoundingInfo = function () {
  20167. var meshBB = this._sourceMesh.getBoundingInfo();
  20168. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  20169. this._updateBoundingInfo();
  20170. };
  20171. InstancedMesh.prototype._preActivate = function () {
  20172. if (this._currentLOD) {
  20173. this._currentLOD._preActivate();
  20174. }
  20175. };
  20176. InstancedMesh.prototype._activate = function (renderId) {
  20177. if (this._currentLOD) {
  20178. this._currentLOD._registerInstanceForRenderId(this, renderId);
  20179. }
  20180. };
  20181. InstancedMesh.prototype.getLOD = function (camera) {
  20182. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  20183. if (this._currentLOD === this.sourceMesh) {
  20184. return this;
  20185. }
  20186. return this._currentLOD;
  20187. };
  20188. InstancedMesh.prototype._syncSubMeshes = function () {
  20189. this.releaseSubMeshes();
  20190. if (this._sourceMesh.subMeshes) {
  20191. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  20192. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  20193. }
  20194. }
  20195. };
  20196. InstancedMesh.prototype._generatePointsArray = function () {
  20197. return this._sourceMesh._generatePointsArray();
  20198. };
  20199. // Clone
  20200. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20201. var result = this._sourceMesh.createInstance(name);
  20202. // Deep copy
  20203. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  20204. // Bounding info
  20205. this.refreshBoundingInfo();
  20206. // Parent
  20207. if (newParent) {
  20208. result.parent = newParent;
  20209. }
  20210. if (!doNotCloneChildren) {
  20211. // Children
  20212. for (var index = 0; index < this.getScene().meshes.length; index++) {
  20213. var mesh = this.getScene().meshes[index];
  20214. if (mesh.parent === this) {
  20215. mesh.clone(mesh.name, result);
  20216. }
  20217. }
  20218. }
  20219. result.computeWorldMatrix(true);
  20220. return result;
  20221. };
  20222. // Dispose
  20223. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  20224. // Remove from mesh
  20225. var index = this._sourceMesh.instances.indexOf(this);
  20226. this._sourceMesh.instances.splice(index, 1);
  20227. _super.prototype.dispose.call(this, doNotRecurse);
  20228. };
  20229. return InstancedMesh;
  20230. }(BABYLON.AbstractMesh));
  20231. BABYLON.InstancedMesh = InstancedMesh;
  20232. })(BABYLON || (BABYLON = {}));
  20233. //# sourceMappingURL=babylon.instancedMesh.js.map
  20234. var BABYLON;
  20235. (function (BABYLON) {
  20236. var _InstancesBatch = (function () {
  20237. function _InstancesBatch() {
  20238. this.mustReturn = false;
  20239. this.visibleInstances = new Array();
  20240. this.renderSelf = new Array();
  20241. }
  20242. return _InstancesBatch;
  20243. }());
  20244. BABYLON._InstancesBatch = _InstancesBatch;
  20245. var Mesh = (function (_super) {
  20246. __extends(Mesh, _super);
  20247. /**
  20248. * @constructor
  20249. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20250. * @param {Scene} scene The scene to add this mesh to.
  20251. * @param {Node} parent The parent of this mesh, if it has one
  20252. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20253. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20254. * When false, achieved by calling a clone(), also passing False.
  20255. * This will make creation of children, recursive.
  20256. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20257. */
  20258. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20259. if (parent === void 0) { parent = null; }
  20260. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20261. var _this = _super.call(this, name, scene) || this;
  20262. // Events
  20263. /**
  20264. * An event triggered before rendering the mesh
  20265. * @type {BABYLON.Observable}
  20266. */
  20267. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20268. /**
  20269. * An event triggered after rendering the mesh
  20270. * @type {BABYLON.Observable}
  20271. */
  20272. _this.onAfterRenderObservable = new BABYLON.Observable();
  20273. /**
  20274. * An event triggered before drawing the mesh
  20275. * @type {BABYLON.Observable}
  20276. */
  20277. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20278. // Members
  20279. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20280. _this.instances = new Array();
  20281. _this._LODLevels = new Array();
  20282. _this._visibleInstances = {};
  20283. _this._renderIdForInstances = new Array();
  20284. _this._batchCache = new _InstancesBatch();
  20285. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20286. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20287. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20288. // Will be used to save a source mesh reference, If any
  20289. _this._source = null;
  20290. if (source) {
  20291. // Source mesh
  20292. _this._source = source;
  20293. // Geometry
  20294. if (source._geometry) {
  20295. source._geometry.applyToMesh(_this);
  20296. }
  20297. // Deep copy
  20298. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  20299. // Parent
  20300. _this.parent = source.parent;
  20301. // Pivot
  20302. _this.setPivotMatrix(source.getPivotMatrix());
  20303. _this.id = name + "." + source.id;
  20304. // Material
  20305. _this.material = source.material;
  20306. var index;
  20307. if (!doNotCloneChildren) {
  20308. // Children
  20309. for (index = 0; index < scene.meshes.length; index++) {
  20310. var mesh = scene.meshes[index];
  20311. if (mesh.parent === source) {
  20312. // doNotCloneChildren is always going to be False
  20313. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20314. }
  20315. }
  20316. }
  20317. // Physics clone
  20318. var physicsEngine = _this.getScene().getPhysicsEngine();
  20319. if (clonePhysicsImpostor && physicsEngine) {
  20320. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20321. if (impostor) {
  20322. _this.physicsImpostor = impostor.clone(_this);
  20323. }
  20324. }
  20325. // Particles
  20326. for (index = 0; index < scene.particleSystems.length; index++) {
  20327. var system = scene.particleSystems[index];
  20328. if (system.emitter === source) {
  20329. system.clone(system.name, _this);
  20330. }
  20331. }
  20332. _this.computeWorldMatrix(true);
  20333. }
  20334. // Parent
  20335. if (parent !== null) {
  20336. _this.parent = parent;
  20337. }
  20338. return _this;
  20339. }
  20340. Object.defineProperty(Mesh, "FRONTSIDE", {
  20341. /**
  20342. * Mesh side orientation : usually the external or front surface
  20343. */
  20344. get: function () {
  20345. return Mesh._FRONTSIDE;
  20346. },
  20347. enumerable: true,
  20348. configurable: true
  20349. });
  20350. Object.defineProperty(Mesh, "BACKSIDE", {
  20351. /**
  20352. * Mesh side orientation : usually the internal or back surface
  20353. */
  20354. get: function () {
  20355. return Mesh._BACKSIDE;
  20356. },
  20357. enumerable: true,
  20358. configurable: true
  20359. });
  20360. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20361. /**
  20362. * Mesh side orientation : both internal and external or front and back surfaces
  20363. */
  20364. get: function () {
  20365. return Mesh._DOUBLESIDE;
  20366. },
  20367. enumerable: true,
  20368. configurable: true
  20369. });
  20370. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20371. /**
  20372. * Mesh side orientation : by default, `FRONTSIDE`
  20373. */
  20374. get: function () {
  20375. return Mesh._DEFAULTSIDE;
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. Object.defineProperty(Mesh, "NO_CAP", {
  20381. /**
  20382. * Mesh cap setting : no cap
  20383. */
  20384. get: function () {
  20385. return Mesh._NO_CAP;
  20386. },
  20387. enumerable: true,
  20388. configurable: true
  20389. });
  20390. Object.defineProperty(Mesh, "CAP_START", {
  20391. /**
  20392. * Mesh cap setting : one cap at the beginning of the mesh
  20393. */
  20394. get: function () {
  20395. return Mesh._CAP_START;
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. Object.defineProperty(Mesh, "CAP_END", {
  20401. /**
  20402. * Mesh cap setting : one cap at the end of the mesh
  20403. */
  20404. get: function () {
  20405. return Mesh._CAP_END;
  20406. },
  20407. enumerable: true,
  20408. configurable: true
  20409. });
  20410. Object.defineProperty(Mesh, "CAP_ALL", {
  20411. /**
  20412. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20413. */
  20414. get: function () {
  20415. return Mesh._CAP_ALL;
  20416. },
  20417. enumerable: true,
  20418. configurable: true
  20419. });
  20420. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20421. set: function (callback) {
  20422. if (this._onBeforeDrawObserver) {
  20423. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20424. }
  20425. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20426. },
  20427. enumerable: true,
  20428. configurable: true
  20429. });
  20430. Object.defineProperty(Mesh.prototype, "source", {
  20431. get: function () {
  20432. return this._source;
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. // Methods
  20438. Mesh.prototype.getClassName = function () {
  20439. return "Mesh";
  20440. };
  20441. /**
  20442. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20443. */
  20444. Mesh.prototype.toString = function (fullDetails) {
  20445. var ret = _super.prototype.toString.call(this, fullDetails);
  20446. ret += ", n vertices: " + this.getTotalVertices();
  20447. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20448. if (this.animations) {
  20449. for (var i = 0; i < this.animations.length; i++) {
  20450. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20451. }
  20452. }
  20453. if (fullDetails) {
  20454. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20455. }
  20456. return ret;
  20457. };
  20458. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20459. get: function () {
  20460. return this._LODLevels.length > 0;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Mesh.prototype._sortLODLevels = function () {
  20466. this._LODLevels.sort(function (a, b) {
  20467. if (a.distance < b.distance) {
  20468. return 1;
  20469. }
  20470. if (a.distance > b.distance) {
  20471. return -1;
  20472. }
  20473. return 0;
  20474. });
  20475. };
  20476. /**
  20477. * Add a mesh as LOD level triggered at the given distance.
  20478. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20479. * @param {number} distance The distance from the center of the object to show this level
  20480. * @param {Mesh} mesh The mesh to be added as LOD level
  20481. * @return {Mesh} This mesh (for chaining)
  20482. */
  20483. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20484. if (mesh && mesh._masterMesh) {
  20485. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20486. return this;
  20487. }
  20488. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20489. this._LODLevels.push(level);
  20490. if (mesh) {
  20491. mesh._masterMesh = this;
  20492. }
  20493. this._sortLODLevels();
  20494. return this;
  20495. };
  20496. /**
  20497. * Returns the LOD level mesh at the passed distance or null if not found.
  20498. * It is related to the method `addLODLevel(distance, mesh)`.
  20499. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20500. */
  20501. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20502. for (var index = 0; index < this._LODLevels.length; index++) {
  20503. var level = this._LODLevels[index];
  20504. if (level.distance === distance) {
  20505. return level.mesh;
  20506. }
  20507. }
  20508. return null;
  20509. };
  20510. /**
  20511. * Remove a mesh from the LOD array
  20512. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20513. * @param {Mesh} mesh The mesh to be removed.
  20514. * @return {Mesh} This mesh (for chaining)
  20515. */
  20516. Mesh.prototype.removeLODLevel = function (mesh) {
  20517. for (var index = 0; index < this._LODLevels.length; index++) {
  20518. if (this._LODLevels[index].mesh === mesh) {
  20519. this._LODLevels.splice(index, 1);
  20520. if (mesh) {
  20521. mesh._masterMesh = null;
  20522. }
  20523. }
  20524. }
  20525. this._sortLODLevels();
  20526. return this;
  20527. };
  20528. /**
  20529. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20530. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20531. */
  20532. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20533. if (!this._LODLevels || this._LODLevels.length === 0) {
  20534. return this;
  20535. }
  20536. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20537. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20538. if (this.onLODLevelSelection) {
  20539. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20540. }
  20541. return this;
  20542. }
  20543. for (var index = 0; index < this._LODLevels.length; index++) {
  20544. var level = this._LODLevels[index];
  20545. if (level.distance < distanceToCamera) {
  20546. if (level.mesh) {
  20547. level.mesh._preActivate();
  20548. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20549. }
  20550. if (this.onLODLevelSelection) {
  20551. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20552. }
  20553. return level.mesh;
  20554. }
  20555. }
  20556. if (this.onLODLevelSelection) {
  20557. this.onLODLevelSelection(distanceToCamera, this, this);
  20558. }
  20559. return this;
  20560. };
  20561. Object.defineProperty(Mesh.prototype, "geometry", {
  20562. /**
  20563. * Returns the mesh internal Geometry object.
  20564. */
  20565. get: function () {
  20566. return this._geometry;
  20567. },
  20568. enumerable: true,
  20569. configurable: true
  20570. });
  20571. /**
  20572. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20573. */
  20574. Mesh.prototype.getTotalVertices = function () {
  20575. if (!this._geometry) {
  20576. return 0;
  20577. }
  20578. return this._geometry.getTotalVertices();
  20579. };
  20580. /**
  20581. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20582. * 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.
  20583. * Returns null if the mesh has no geometry or no vertex buffer.
  20584. * Possible `kind` values :
  20585. * - BABYLON.VertexBuffer.PositionKind
  20586. * - BABYLON.VertexBuffer.UVKind
  20587. * - BABYLON.VertexBuffer.UV2Kind
  20588. * - BABYLON.VertexBuffer.UV3Kind
  20589. * - BABYLON.VertexBuffer.UV4Kind
  20590. * - BABYLON.VertexBuffer.UV5Kind
  20591. * - BABYLON.VertexBuffer.UV6Kind
  20592. * - BABYLON.VertexBuffer.ColorKind
  20593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20597. */
  20598. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20599. if (!this._geometry) {
  20600. return null;
  20601. }
  20602. return this._geometry.getVerticesData(kind, copyWhenShared);
  20603. };
  20604. /**
  20605. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20606. * Returns `undefined` if the mesh has no geometry.
  20607. * Possible `kind` values :
  20608. * - BABYLON.VertexBuffer.PositionKind
  20609. * - BABYLON.VertexBuffer.UVKind
  20610. * - BABYLON.VertexBuffer.UV2Kind
  20611. * - BABYLON.VertexBuffer.UV3Kind
  20612. * - BABYLON.VertexBuffer.UV4Kind
  20613. * - BABYLON.VertexBuffer.UV5Kind
  20614. * - BABYLON.VertexBuffer.UV6Kind
  20615. * - BABYLON.VertexBuffer.ColorKind
  20616. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20617. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20618. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20619. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20620. */
  20621. Mesh.prototype.getVertexBuffer = function (kind) {
  20622. if (!this._geometry) {
  20623. return undefined;
  20624. }
  20625. return this._geometry.getVertexBuffer(kind);
  20626. };
  20627. /**
  20628. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20629. * Possible `kind` values :
  20630. * - BABYLON.VertexBuffer.PositionKind
  20631. * - BABYLON.VertexBuffer.UVKind
  20632. * - BABYLON.VertexBuffer.UV2Kind
  20633. * - BABYLON.VertexBuffer.UV3Kind
  20634. * - BABYLON.VertexBuffer.UV4Kind
  20635. * - BABYLON.VertexBuffer.UV5Kind
  20636. * - BABYLON.VertexBuffer.UV6Kind
  20637. * - BABYLON.VertexBuffer.ColorKind
  20638. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20639. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20640. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20641. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20642. */
  20643. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20644. if (!this._geometry) {
  20645. if (this._delayInfo) {
  20646. return this._delayInfo.indexOf(kind) !== -1;
  20647. }
  20648. return false;
  20649. }
  20650. return this._geometry.isVerticesDataPresent(kind);
  20651. };
  20652. /**
  20653. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20654. * Possible `kind` values :
  20655. * - BABYLON.VertexBuffer.PositionKind
  20656. * - BABYLON.VertexBuffer.UVKind
  20657. * - BABYLON.VertexBuffer.UV2Kind
  20658. * - BABYLON.VertexBuffer.UV3Kind
  20659. * - BABYLON.VertexBuffer.UV4Kind
  20660. * - BABYLON.VertexBuffer.UV5Kind
  20661. * - BABYLON.VertexBuffer.UV6Kind
  20662. * - BABYLON.VertexBuffer.ColorKind
  20663. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20664. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20665. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20666. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20667. */
  20668. Mesh.prototype.getVerticesDataKinds = function () {
  20669. if (!this._geometry) {
  20670. var result = [];
  20671. if (this._delayInfo) {
  20672. this._delayInfo.forEach(function (kind, index, array) {
  20673. result.push(kind);
  20674. });
  20675. }
  20676. return result;
  20677. }
  20678. return this._geometry.getVerticesDataKinds();
  20679. };
  20680. /**
  20681. * Returns a positive integer : the total number of indices in this mesh geometry.
  20682. * Returns zero if the mesh has no geometry.
  20683. */
  20684. Mesh.prototype.getTotalIndices = function () {
  20685. if (!this._geometry) {
  20686. return 0;
  20687. }
  20688. return this._geometry.getTotalIndices();
  20689. };
  20690. /**
  20691. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20692. * 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.
  20693. * Returns an empty array if the mesh has no geometry.
  20694. */
  20695. Mesh.prototype.getIndices = function (copyWhenShared) {
  20696. if (!this._geometry) {
  20697. return [];
  20698. }
  20699. return this._geometry.getIndices(copyWhenShared);
  20700. };
  20701. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20702. get: function () {
  20703. return this._masterMesh !== null && this._masterMesh !== undefined;
  20704. },
  20705. enumerable: true,
  20706. configurable: true
  20707. });
  20708. /**
  20709. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20710. */
  20711. Mesh.prototype.isReady = function () {
  20712. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20713. return false;
  20714. }
  20715. return _super.prototype.isReady.call(this);
  20716. };
  20717. /**
  20718. * Boolean : true if the mesh has been disposed.
  20719. */
  20720. Mesh.prototype.isDisposed = function () {
  20721. return this._isDisposed;
  20722. };
  20723. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20724. get: function () {
  20725. return this._sideOrientation;
  20726. },
  20727. /**
  20728. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20729. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20730. */
  20731. set: function (sideO) {
  20732. this._sideOrientation = sideO;
  20733. },
  20734. enumerable: true,
  20735. configurable: true
  20736. });
  20737. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20738. /**
  20739. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20740. * This property is pertinent only for updatable parametric shapes.
  20741. */
  20742. get: function () {
  20743. return this._areNormalsFrozen;
  20744. },
  20745. enumerable: true,
  20746. configurable: true
  20747. });
  20748. /**
  20749. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20750. * It has no effect at all on other shapes.
  20751. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20752. */
  20753. Mesh.prototype.freezeNormals = function () {
  20754. this._areNormalsFrozen = true;
  20755. };
  20756. /**
  20757. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20758. * It has no effect at all on other shapes.
  20759. * It reactivates the mesh normals computation if it was previously frozen.
  20760. */
  20761. Mesh.prototype.unfreezeNormals = function () {
  20762. this._areNormalsFrozen = false;
  20763. };
  20764. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20765. /**
  20766. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20767. */
  20768. set: function (count) {
  20769. this._overridenInstanceCount = count;
  20770. },
  20771. enumerable: true,
  20772. configurable: true
  20773. });
  20774. // Methods
  20775. Mesh.prototype._preActivate = function () {
  20776. var sceneRenderId = this.getScene().getRenderId();
  20777. if (this._preActivateId === sceneRenderId) {
  20778. return;
  20779. }
  20780. this._preActivateId = sceneRenderId;
  20781. this._visibleInstances = null;
  20782. };
  20783. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20784. if (this._visibleInstances) {
  20785. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20786. }
  20787. };
  20788. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20789. if (!this._visibleInstances) {
  20790. this._visibleInstances = {};
  20791. this._visibleInstances.defaultRenderId = renderId;
  20792. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20793. }
  20794. if (!this._visibleInstances[renderId]) {
  20795. this._visibleInstances[renderId] = new Array();
  20796. }
  20797. this._visibleInstances[renderId].push(instance);
  20798. };
  20799. /**
  20800. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20801. * This means the mesh underlying bounding box and sphere are recomputed.
  20802. */
  20803. Mesh.prototype.refreshBoundingInfo = function () {
  20804. if (this._boundingInfo.isLocked) {
  20805. return;
  20806. }
  20807. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20808. if (data) {
  20809. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20810. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20811. }
  20812. if (this.subMeshes) {
  20813. for (var index = 0; index < this.subMeshes.length; index++) {
  20814. this.subMeshes[index].refreshBoundingInfo();
  20815. }
  20816. }
  20817. this._updateBoundingInfo();
  20818. };
  20819. Mesh.prototype._createGlobalSubMesh = function () {
  20820. var totalVertices = this.getTotalVertices();
  20821. if (!totalVertices || !this.getIndices()) {
  20822. return null;
  20823. }
  20824. this.releaseSubMeshes();
  20825. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20826. };
  20827. Mesh.prototype.subdivide = function (count) {
  20828. if (count < 1) {
  20829. return;
  20830. }
  20831. var totalIndices = this.getTotalIndices();
  20832. var subdivisionSize = (totalIndices / count) | 0;
  20833. var offset = 0;
  20834. // Ensure that subdivisionSize is a multiple of 3
  20835. while (subdivisionSize % 3 !== 0) {
  20836. subdivisionSize++;
  20837. }
  20838. this.releaseSubMeshes();
  20839. for (var index = 0; index < count; index++) {
  20840. if (offset >= totalIndices) {
  20841. break;
  20842. }
  20843. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20844. offset += subdivisionSize;
  20845. }
  20846. this.synchronizeInstances();
  20847. };
  20848. /**
  20849. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20850. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20851. * The `data` are either a numeric array either a Float32Array.
  20852. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20853. * 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).
  20854. * Note that a new underlying VertexBuffer object is created each call.
  20855. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20856. *
  20857. * Possible `kind` values :
  20858. * - BABYLON.VertexBuffer.PositionKind
  20859. * - BABYLON.VertexBuffer.UVKind
  20860. * - BABYLON.VertexBuffer.UV2Kind
  20861. * - BABYLON.VertexBuffer.UV3Kind
  20862. * - BABYLON.VertexBuffer.UV4Kind
  20863. * - BABYLON.VertexBuffer.UV5Kind
  20864. * - BABYLON.VertexBuffer.UV6Kind
  20865. * - BABYLON.VertexBuffer.ColorKind
  20866. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20867. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20868. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20869. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20870. */
  20871. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20872. if (!this._geometry) {
  20873. var vertexData = new BABYLON.VertexData();
  20874. vertexData.set(data, kind);
  20875. var scene = this.getScene();
  20876. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20877. }
  20878. else {
  20879. this._geometry.setVerticesData(kind, data, updatable, stride);
  20880. }
  20881. };
  20882. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20883. if (!this._geometry) {
  20884. var scene = this.getScene();
  20885. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20886. }
  20887. this._geometry.setVerticesBuffer(buffer);
  20888. };
  20889. /**
  20890. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20891. * If the mesh has no geometry, it is simply returned as it is.
  20892. * The `data` are either a numeric array either a Float32Array.
  20893. * No new underlying VertexBuffer object is created.
  20894. * 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.
  20895. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20896. *
  20897. * Possible `kind` values :
  20898. * - BABYLON.VertexBuffer.PositionKind
  20899. * - BABYLON.VertexBuffer.UVKind
  20900. * - BABYLON.VertexBuffer.UV2Kind
  20901. * - BABYLON.VertexBuffer.UV3Kind
  20902. * - BABYLON.VertexBuffer.UV4Kind
  20903. * - BABYLON.VertexBuffer.UV5Kind
  20904. * - BABYLON.VertexBuffer.UV6Kind
  20905. * - BABYLON.VertexBuffer.ColorKind
  20906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20910. */
  20911. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20912. if (!this._geometry) {
  20913. return;
  20914. }
  20915. if (!makeItUnique) {
  20916. this._geometry.updateVerticesData(kind, data, updateExtends);
  20917. }
  20918. else {
  20919. this.makeGeometryUnique();
  20920. this.updateVerticesData(kind, data, updateExtends, false);
  20921. }
  20922. };
  20923. /**
  20924. * Deprecated since BabylonJS v2.3
  20925. */
  20926. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20927. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20928. if (!this._geometry) {
  20929. return;
  20930. }
  20931. if (!makeItUnique) {
  20932. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20933. }
  20934. else {
  20935. this.makeGeometryUnique();
  20936. this.updateVerticesDataDirectly(kind, data, offset, false);
  20937. }
  20938. };
  20939. /**
  20940. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20941. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20942. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20943. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20944. */
  20945. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20946. if (computeNormals === void 0) { computeNormals = true; }
  20947. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20948. positionFunction(positions);
  20949. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20950. if (computeNormals) {
  20951. var indices = this.getIndices();
  20952. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20953. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20954. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20955. }
  20956. };
  20957. Mesh.prototype.makeGeometryUnique = function () {
  20958. if (!this._geometry) {
  20959. return;
  20960. }
  20961. var oldGeometry = this._geometry;
  20962. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20963. oldGeometry.releaseForMesh(this, true);
  20964. geometry.applyToMesh(this);
  20965. };
  20966. /**
  20967. * Sets the mesh indices.
  20968. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20969. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20970. * This method creates a new index buffer each call.
  20971. */
  20972. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20973. if (!this._geometry) {
  20974. var vertexData = new BABYLON.VertexData();
  20975. vertexData.indices = indices;
  20976. var scene = this.getScene();
  20977. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20978. }
  20979. else {
  20980. this._geometry.setIndices(indices, totalVertices);
  20981. }
  20982. };
  20983. /**
  20984. * Invert the geometry to move from a right handed system to a left handed one.
  20985. */
  20986. Mesh.prototype.toLeftHanded = function () {
  20987. if (!this._geometry) {
  20988. return;
  20989. }
  20990. this._geometry.toLeftHanded();
  20991. };
  20992. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20993. var engine = this.getScene().getEngine();
  20994. // Wireframe
  20995. var indexToBind;
  20996. if (this._unIndexed) {
  20997. indexToBind = null;
  20998. }
  20999. else {
  21000. switch (fillMode) {
  21001. case BABYLON.Material.PointFillMode:
  21002. indexToBind = null;
  21003. break;
  21004. case BABYLON.Material.WireFrameFillMode:
  21005. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21006. break;
  21007. default:
  21008. case BABYLON.Material.TriangleFillMode:
  21009. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21010. break;
  21011. }
  21012. }
  21013. // VBOs
  21014. this._geometry._bind(effect, indexToBind);
  21015. };
  21016. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21017. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21018. return;
  21019. }
  21020. this.onBeforeDrawObservable.notifyObservers(this);
  21021. var engine = this.getScene().getEngine();
  21022. // Draw order
  21023. switch (fillMode) {
  21024. case BABYLON.Material.PointFillMode:
  21025. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21026. break;
  21027. case BABYLON.Material.WireFrameFillMode:
  21028. if (this._unIndexed) {
  21029. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21030. }
  21031. else {
  21032. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  21033. }
  21034. break;
  21035. default:
  21036. if (this._unIndexed) {
  21037. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21038. }
  21039. else {
  21040. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21041. }
  21042. }
  21043. };
  21044. /**
  21045. * Registers for this mesh a javascript function called just before the rendering process.
  21046. * This function is passed the current mesh and doesn't return anything.
  21047. */
  21048. Mesh.prototype.registerBeforeRender = function (func) {
  21049. this.onBeforeRenderObservable.add(func);
  21050. };
  21051. /**
  21052. * Disposes a previously registered javascript function called before the rendering.
  21053. * This function is passed the current mesh and doesn't return anything.
  21054. */
  21055. Mesh.prototype.unregisterBeforeRender = function (func) {
  21056. this.onBeforeRenderObservable.removeCallback(func);
  21057. };
  21058. /**
  21059. * Registers for this mesh a javascript function called just after the rendering is complete.
  21060. * This function is passed the current mesh and doesn't return anything.
  21061. */
  21062. Mesh.prototype.registerAfterRender = function (func) {
  21063. this.onAfterRenderObservable.add(func);
  21064. };
  21065. /**
  21066. * Disposes a previously registered javascript function called after the rendering.
  21067. * This function is passed the current mesh and doesn't return anything.
  21068. */
  21069. Mesh.prototype.unregisterAfterRender = function (func) {
  21070. this.onAfterRenderObservable.removeCallback(func);
  21071. };
  21072. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21073. var scene = this.getScene();
  21074. this._batchCache.mustReturn = false;
  21075. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21076. this._batchCache.visibleInstances[subMeshId] = null;
  21077. if (this._visibleInstances) {
  21078. var currentRenderId = scene.getRenderId();
  21079. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21080. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21081. var selfRenderId = this._renderId;
  21082. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21083. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21084. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21085. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21086. }
  21087. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21088. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21089. this._batchCache.mustReturn = true;
  21090. return this._batchCache;
  21091. }
  21092. if (currentRenderId !== selfRenderId) {
  21093. this._batchCache.renderSelf[subMeshId] = false;
  21094. }
  21095. }
  21096. this._renderIdForInstances[subMeshId] = currentRenderId;
  21097. }
  21098. return this._batchCache;
  21099. };
  21100. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21101. var visibleInstances = batch.visibleInstances[subMesh._id];
  21102. var matricesCount = visibleInstances.length + 1;
  21103. var bufferSize = matricesCount * 16 * 4;
  21104. var currentInstancesBufferSize = this._instancesBufferSize;
  21105. var instancesBuffer = this._instancesBuffer;
  21106. while (this._instancesBufferSize < bufferSize) {
  21107. this._instancesBufferSize *= 2;
  21108. }
  21109. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21110. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21111. }
  21112. var offset = 0;
  21113. var instancesCount = 0;
  21114. var world = this.getWorldMatrix();
  21115. if (batch.renderSelf[subMesh._id]) {
  21116. world.copyToArray(this._instancesData, offset);
  21117. offset += 16;
  21118. instancesCount++;
  21119. }
  21120. if (visibleInstances) {
  21121. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21122. var instance = visibleInstances[instanceIndex];
  21123. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21124. offset += 16;
  21125. instancesCount++;
  21126. }
  21127. }
  21128. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21129. if (instancesBuffer) {
  21130. instancesBuffer.dispose();
  21131. }
  21132. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21133. this._instancesBuffer = instancesBuffer;
  21134. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21135. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21136. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21137. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21138. }
  21139. else {
  21140. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21141. }
  21142. this.geometry._bind(effect);
  21143. this._draw(subMesh, fillMode, instancesCount);
  21144. engine.unbindInstanceAttributes();
  21145. };
  21146. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21147. var scene = this.getScene();
  21148. var engine = scene.getEngine();
  21149. if (hardwareInstancedRendering) {
  21150. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21151. }
  21152. else {
  21153. if (batch.renderSelf[subMesh._id]) {
  21154. // Draw
  21155. if (onBeforeDraw) {
  21156. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21157. }
  21158. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21159. }
  21160. if (batch.visibleInstances[subMesh._id]) {
  21161. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21162. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21163. // World
  21164. var world = instance.getWorldMatrix();
  21165. if (onBeforeDraw) {
  21166. onBeforeDraw(true, world, effectiveMaterial);
  21167. }
  21168. // Draw
  21169. this._draw(subMesh, fillMode);
  21170. }
  21171. }
  21172. }
  21173. };
  21174. /**
  21175. * Triggers the draw call for the mesh.
  21176. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21177. */
  21178. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21179. var scene = this.getScene();
  21180. // Managing instances
  21181. var batch = this._getInstancesRenderList(subMesh._id);
  21182. if (batch.mustReturn) {
  21183. return;
  21184. }
  21185. // Checking geometry state
  21186. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21187. return;
  21188. }
  21189. var callbackIndex;
  21190. this.onBeforeRenderObservable.notifyObservers(this);
  21191. var engine = scene.getEngine();
  21192. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21193. // Material
  21194. var effectiveMaterial = subMesh.getMaterial();
  21195. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21196. return;
  21197. }
  21198. // Outline - step 1
  21199. var savedDepthWrite = engine.getDepthWrite();
  21200. if (this.renderOutline) {
  21201. engine.setDepthWrite(false);
  21202. scene.getOutlineRenderer().render(subMesh, batch);
  21203. engine.setDepthWrite(savedDepthWrite);
  21204. }
  21205. effectiveMaterial._preBind();
  21206. var effect = effectiveMaterial.getEffect();
  21207. // Bind
  21208. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21209. this._bind(subMesh, effect, fillMode);
  21210. var world = this.getWorldMatrix();
  21211. effectiveMaterial.bind(world, this);
  21212. // Alpha mode
  21213. if (enableAlphaMode) {
  21214. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21215. }
  21216. // Draw
  21217. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21218. // Unbind
  21219. effectiveMaterial.unbind();
  21220. // Outline - step 2
  21221. if (this.renderOutline && savedDepthWrite) {
  21222. engine.setDepthWrite(true);
  21223. engine.setColorWrite(false);
  21224. scene.getOutlineRenderer().render(subMesh, batch);
  21225. engine.setColorWrite(true);
  21226. }
  21227. // Overlay
  21228. if (this.renderOverlay) {
  21229. var currentMode = engine.getAlphaMode();
  21230. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21231. scene.getOutlineRenderer().render(subMesh, batch, true);
  21232. engine.setAlphaMode(currentMode);
  21233. }
  21234. this.onAfterRenderObservable.notifyObservers(this);
  21235. };
  21236. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21237. if (isInstance) {
  21238. effectiveMaterial.bindOnlyWorldMatrix(world);
  21239. }
  21240. };
  21241. /**
  21242. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21243. */
  21244. Mesh.prototype.getEmittedParticleSystems = function () {
  21245. var results = new Array();
  21246. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21247. var particleSystem = this.getScene().particleSystems[index];
  21248. if (particleSystem.emitter === this) {
  21249. results.push(particleSystem);
  21250. }
  21251. }
  21252. return results;
  21253. };
  21254. /**
  21255. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21256. */
  21257. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21258. var results = new Array();
  21259. var descendants = this.getDescendants();
  21260. descendants.push(this);
  21261. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21262. var particleSystem = this.getScene().particleSystems[index];
  21263. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  21264. results.push(particleSystem);
  21265. }
  21266. }
  21267. return results;
  21268. };
  21269. Mesh.prototype._checkDelayState = function () {
  21270. var scene = this.getScene();
  21271. if (this._geometry) {
  21272. this._geometry.load(scene);
  21273. }
  21274. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21275. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21276. this._queueLoad(this, scene);
  21277. }
  21278. };
  21279. Mesh.prototype._queueLoad = function (mesh, scene) {
  21280. var _this = this;
  21281. scene._addPendingData(mesh);
  21282. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21283. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21284. if (data instanceof ArrayBuffer) {
  21285. _this._delayLoadingFunction(data, _this);
  21286. }
  21287. else {
  21288. _this._delayLoadingFunction(JSON.parse(data), _this);
  21289. }
  21290. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21291. scene._removePendingData(_this);
  21292. }, function () { }, scene.database, getBinaryData);
  21293. };
  21294. /**
  21295. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21296. */
  21297. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21298. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21299. return false;
  21300. }
  21301. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21302. return false;
  21303. }
  21304. this._checkDelayState();
  21305. return true;
  21306. };
  21307. /**
  21308. * Sets the mesh material by the material or multiMaterial `id` property.
  21309. * The material `id` is a string identifying the material or the multiMaterial.
  21310. * This method returns nothing.
  21311. */
  21312. Mesh.prototype.setMaterialByID = function (id) {
  21313. var materials = this.getScene().materials;
  21314. var index;
  21315. for (index = 0; index < materials.length; index++) {
  21316. if (materials[index].id === id) {
  21317. this.material = materials[index];
  21318. return;
  21319. }
  21320. }
  21321. // Multi
  21322. var multiMaterials = this.getScene().multiMaterials;
  21323. for (index = 0; index < multiMaterials.length; index++) {
  21324. if (multiMaterials[index].id === id) {
  21325. this.material = multiMaterials[index];
  21326. return;
  21327. }
  21328. }
  21329. };
  21330. /**
  21331. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21332. */
  21333. Mesh.prototype.getAnimatables = function () {
  21334. var results = [];
  21335. if (this.material) {
  21336. results.push(this.material);
  21337. }
  21338. if (this.skeleton) {
  21339. results.push(this.skeleton);
  21340. }
  21341. return results;
  21342. };
  21343. /**
  21344. * Modifies the mesh geometry according to the passed transformation matrix.
  21345. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21346. * The mesh normals are modified accordingly the same transformation.
  21347. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21348. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21349. */
  21350. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21351. // Position
  21352. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21353. return;
  21354. }
  21355. var submeshes = this.subMeshes.splice(0);
  21356. this._resetPointsArrayCache();
  21357. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21358. var temp = [];
  21359. var index;
  21360. for (index = 0; index < data.length; index += 3) {
  21361. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21362. }
  21363. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21364. // Normals
  21365. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21366. return;
  21367. }
  21368. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21369. temp = [];
  21370. for (index = 0; index < data.length; index += 3) {
  21371. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21372. }
  21373. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21374. // flip faces?
  21375. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21376. this.flipFaces();
  21377. }
  21378. // Restore submeshes
  21379. this.releaseSubMeshes();
  21380. this.subMeshes = submeshes;
  21381. };
  21382. /**
  21383. * Modifies the mesh geometry according to its own current World Matrix.
  21384. * The mesh World Matrix is then reset.
  21385. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21386. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21387. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21388. */
  21389. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21390. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21391. this.scaling.copyFromFloats(1, 1, 1);
  21392. this.position.copyFromFloats(0, 0, 0);
  21393. this.rotation.copyFromFloats(0, 0, 0);
  21394. //only if quaternion is already set
  21395. if (this.rotationQuaternion) {
  21396. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21397. }
  21398. this._worldMatrix = BABYLON.Matrix.Identity();
  21399. };
  21400. // Cache
  21401. Mesh.prototype._resetPointsArrayCache = function () {
  21402. this._positions = null;
  21403. };
  21404. Mesh.prototype._generatePointsArray = function () {
  21405. if (this._positions)
  21406. return true;
  21407. this._positions = [];
  21408. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21409. if (!data) {
  21410. return false;
  21411. }
  21412. for (var index = 0; index < data.length; index += 3) {
  21413. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  21414. }
  21415. return true;
  21416. };
  21417. /**
  21418. * Returns a new Mesh object generated from the current mesh properties.
  21419. * This method must not get confused with createInstance().
  21420. * The parameter `name` is a string, the name given to the new mesh.
  21421. * The optional parameter `newParent` can be any Node object (default `null`).
  21422. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21423. * 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.
  21424. */
  21425. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21426. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21427. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21428. };
  21429. /**
  21430. * Disposes the mesh.
  21431. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21432. */
  21433. Mesh.prototype.dispose = function (doNotRecurse) {
  21434. var _this = this;
  21435. if (this._geometry) {
  21436. this._geometry.releaseForMesh(this, true);
  21437. }
  21438. // Sources
  21439. var meshes = this.getScene().meshes;
  21440. meshes.forEach(function (mesh) {
  21441. if (mesh._source && mesh._source === _this) {
  21442. mesh._source = null;
  21443. }
  21444. });
  21445. this._source = null;
  21446. // Instances
  21447. if (this._instancesBuffer) {
  21448. this._instancesBuffer.dispose();
  21449. this._instancesBuffer = null;
  21450. }
  21451. while (this.instances.length) {
  21452. this.instances[0].dispose();
  21453. }
  21454. // Highlight layers.
  21455. var highlightLayers = this.getScene().highlightLayers;
  21456. for (var i = 0; i < highlightLayers.length; i++) {
  21457. var highlightLayer = highlightLayers[i];
  21458. if (highlightLayer) {
  21459. highlightLayer.removeMesh(this);
  21460. highlightLayer.removeExcludedMesh(this);
  21461. }
  21462. }
  21463. _super.prototype.dispose.call(this, doNotRecurse);
  21464. };
  21465. /**
  21466. * Modifies the mesh geometry according to a displacement map.
  21467. * 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.
  21468. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21469. * This method returns nothing.
  21470. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21471. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21472. * 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.
  21473. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21474. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21475. */
  21476. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21477. var _this = this;
  21478. var scene = this.getScene();
  21479. var onload = function (img) {
  21480. // Getting height map data
  21481. var canvas = document.createElement("canvas");
  21482. var context = canvas.getContext("2d");
  21483. var heightMapWidth = img.width;
  21484. var heightMapHeight = img.height;
  21485. canvas.width = heightMapWidth;
  21486. canvas.height = heightMapHeight;
  21487. context.drawImage(img, 0, 0);
  21488. // Create VertexData from map data
  21489. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21490. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21491. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21492. //execute success callback, if set
  21493. if (onSuccess) {
  21494. onSuccess(_this);
  21495. }
  21496. };
  21497. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21498. };
  21499. /**
  21500. * Modifies the mesh geometry according to a displacementMap buffer.
  21501. * 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.
  21502. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21503. * This method returns nothing.
  21504. * 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.
  21505. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21506. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21507. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21508. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21509. */
  21510. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21511. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21512. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21513. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21514. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21515. return;
  21516. }
  21517. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21518. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21519. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21520. var position = BABYLON.Vector3.Zero();
  21521. var normal = BABYLON.Vector3.Zero();
  21522. var uv = BABYLON.Vector2.Zero();
  21523. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21524. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21525. for (var index = 0; index < positions.length; index += 3) {
  21526. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21527. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21528. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21529. // Compute height
  21530. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21531. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21532. var pos = (u + v * heightMapWidth) * 4;
  21533. var r = buffer[pos] / 255.0;
  21534. var g = buffer[pos + 1] / 255.0;
  21535. var b = buffer[pos + 2] / 255.0;
  21536. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21537. normal.normalize();
  21538. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21539. position = position.add(normal);
  21540. position.toArray(positions, index);
  21541. }
  21542. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21543. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21544. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21545. };
  21546. /**
  21547. * Modify the mesh to get a flat shading rendering.
  21548. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21549. * This method returns nothing.
  21550. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21551. */
  21552. Mesh.prototype.convertToFlatShadedMesh = function () {
  21553. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21554. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21555. var kinds = this.getVerticesDataKinds();
  21556. var vbs = [];
  21557. var data = [];
  21558. var newdata = [];
  21559. var updatableNormals = false;
  21560. var kindIndex;
  21561. var kind;
  21562. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21563. kind = kinds[kindIndex];
  21564. var vertexBuffer = this.getVertexBuffer(kind);
  21565. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21566. updatableNormals = vertexBuffer.isUpdatable();
  21567. kinds.splice(kindIndex, 1);
  21568. kindIndex--;
  21569. continue;
  21570. }
  21571. vbs[kind] = vertexBuffer;
  21572. data[kind] = vbs[kind].getData();
  21573. newdata[kind] = [];
  21574. }
  21575. // Save previous submeshes
  21576. var previousSubmeshes = this.subMeshes.slice(0);
  21577. var indices = this.getIndices();
  21578. var totalIndices = this.getTotalIndices();
  21579. // Generating unique vertices per face
  21580. var index;
  21581. for (index = 0; index < totalIndices; index++) {
  21582. var vertexIndex = indices[index];
  21583. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21584. kind = kinds[kindIndex];
  21585. var stride = vbs[kind].getStrideSize();
  21586. for (var offset = 0; offset < stride; offset++) {
  21587. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21588. }
  21589. }
  21590. }
  21591. // Updating faces & normal
  21592. var normals = [];
  21593. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21594. for (index = 0; index < totalIndices; index += 3) {
  21595. indices[index] = index;
  21596. indices[index + 1] = index + 1;
  21597. indices[index + 2] = index + 2;
  21598. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21599. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21600. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21601. var p1p2 = p1.subtract(p2);
  21602. var p3p2 = p3.subtract(p2);
  21603. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21604. // Store same normals for every vertex
  21605. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21606. normals.push(normal.x);
  21607. normals.push(normal.y);
  21608. normals.push(normal.z);
  21609. }
  21610. }
  21611. this.setIndices(indices);
  21612. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21613. // Updating vertex buffers
  21614. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21615. kind = kinds[kindIndex];
  21616. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21617. }
  21618. // Updating submeshes
  21619. this.releaseSubMeshes();
  21620. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21621. var previousOne = previousSubmeshes[submeshIndex];
  21622. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21623. }
  21624. this.synchronizeInstances();
  21625. };
  21626. /**
  21627. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21628. * In other words, more vertices, no more indices and a single bigger VBO.
  21629. * This method returns nothing.
  21630. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21631. *
  21632. */
  21633. Mesh.prototype.convertToUnIndexedMesh = function () {
  21634. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21635. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21636. var kinds = this.getVerticesDataKinds();
  21637. var vbs = [];
  21638. var data = [];
  21639. var newdata = [];
  21640. var updatableNormals = false;
  21641. var kindIndex;
  21642. var kind;
  21643. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21644. kind = kinds[kindIndex];
  21645. var vertexBuffer = this.getVertexBuffer(kind);
  21646. vbs[kind] = vertexBuffer;
  21647. data[kind] = vbs[kind].getData();
  21648. newdata[kind] = [];
  21649. }
  21650. // Save previous submeshes
  21651. var previousSubmeshes = this.subMeshes.slice(0);
  21652. var indices = this.getIndices();
  21653. var totalIndices = this.getTotalIndices();
  21654. // Generating unique vertices per face
  21655. var index;
  21656. for (index = 0; index < totalIndices; index++) {
  21657. var vertexIndex = indices[index];
  21658. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21659. kind = kinds[kindIndex];
  21660. var stride = vbs[kind].getStrideSize();
  21661. for (var offset = 0; offset < stride; offset++) {
  21662. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21663. }
  21664. }
  21665. }
  21666. // Updating indices
  21667. for (index = 0; index < totalIndices; index += 3) {
  21668. indices[index] = index;
  21669. indices[index + 1] = index + 1;
  21670. indices[index + 2] = index + 2;
  21671. }
  21672. this.setIndices(indices);
  21673. // Updating vertex buffers
  21674. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21675. kind = kinds[kindIndex];
  21676. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21677. }
  21678. // Updating submeshes
  21679. this.releaseSubMeshes();
  21680. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21681. var previousOne = previousSubmeshes[submeshIndex];
  21682. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21683. }
  21684. this._unIndexed = true;
  21685. this.synchronizeInstances();
  21686. };
  21687. /**
  21688. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21689. * This method returns nothing.
  21690. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21691. */
  21692. Mesh.prototype.flipFaces = function (flipNormals) {
  21693. if (flipNormals === void 0) { flipNormals = false; }
  21694. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21695. var i;
  21696. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21697. for (i = 0; i < vertex_data.normals.length; i++) {
  21698. vertex_data.normals[i] *= -1;
  21699. }
  21700. }
  21701. var temp;
  21702. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21703. // reassign indices
  21704. temp = vertex_data.indices[i + 1];
  21705. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21706. vertex_data.indices[i + 2] = temp;
  21707. }
  21708. vertex_data.applyToMesh(this);
  21709. };
  21710. // Instances
  21711. /**
  21712. * Creates a new InstancedMesh object from the mesh model.
  21713. * An instance shares the same properties and the same material than its model.
  21714. * Only these properties of each instance can then be set individually :
  21715. * - position
  21716. * - rotation
  21717. * - rotationQuaternion
  21718. * - setPivotMatrix
  21719. * - scaling
  21720. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21721. * Warning : this method is not supported for Line mesh and LineSystem
  21722. */
  21723. Mesh.prototype.createInstance = function (name) {
  21724. return new BABYLON.InstancedMesh(name, this);
  21725. };
  21726. /**
  21727. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21728. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21729. * This method returns nothing.
  21730. */
  21731. Mesh.prototype.synchronizeInstances = function () {
  21732. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21733. var instance = this.instances[instanceIndex];
  21734. instance._syncSubMeshes();
  21735. }
  21736. };
  21737. /**
  21738. * Simplify the mesh according to the given array of settings.
  21739. * Function will return immediately and will simplify async. It returns nothing.
  21740. * @param settings a collection of simplification settings.
  21741. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21742. * @param type the type of simplification to run.
  21743. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21744. */
  21745. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21746. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21747. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21748. this.getScene().simplificationQueue.addTask({
  21749. settings: settings,
  21750. parallelProcessing: parallelProcessing,
  21751. mesh: this,
  21752. simplificationType: simplificationType,
  21753. successCallback: successCallback
  21754. });
  21755. };
  21756. /**
  21757. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21758. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21759. * This should be used together with the simplification to avoid disappearing triangles.
  21760. * @param successCallback an optional success callback to be called after the optimization finished.
  21761. */
  21762. Mesh.prototype.optimizeIndices = function (successCallback) {
  21763. var _this = this;
  21764. var indices = this.getIndices();
  21765. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21766. var vectorPositions = [];
  21767. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21768. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21769. }
  21770. var dupes = [];
  21771. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21772. var realPos = vectorPositions.length - 1 - iteration;
  21773. var testedPosition = vectorPositions[realPos];
  21774. for (var j = 0; j < realPos; ++j) {
  21775. var againstPosition = vectorPositions[j];
  21776. if (testedPosition.equals(againstPosition)) {
  21777. dupes[realPos] = j;
  21778. break;
  21779. }
  21780. }
  21781. }, function () {
  21782. for (var i = 0; i < indices.length; ++i) {
  21783. indices[i] = dupes[indices[i]] || indices[i];
  21784. }
  21785. //indices are now reordered
  21786. var originalSubMeshes = _this.subMeshes.slice(0);
  21787. _this.setIndices(indices);
  21788. _this.subMeshes = originalSubMeshes;
  21789. if (successCallback) {
  21790. successCallback(_this);
  21791. }
  21792. });
  21793. };
  21794. // Statics
  21795. /**
  21796. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21797. * The parameter `parsedMesh` is the mesh to be copied.
  21798. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21799. */
  21800. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21801. var mesh = new Mesh(parsedMesh.name, scene);
  21802. mesh.id = parsedMesh.id;
  21803. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21804. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21805. if (parsedMesh.metadata !== undefined) {
  21806. mesh.metadata = parsedMesh.metadata;
  21807. }
  21808. if (parsedMesh.rotationQuaternion) {
  21809. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21810. }
  21811. else if (parsedMesh.rotation) {
  21812. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21813. }
  21814. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21815. if (parsedMesh.localMatrix) {
  21816. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21817. }
  21818. else if (parsedMesh.pivotMatrix) {
  21819. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21820. }
  21821. mesh.setEnabled(parsedMesh.isEnabled);
  21822. mesh.isVisible = parsedMesh.isVisible;
  21823. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21824. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21825. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21826. if (parsedMesh.applyFog !== undefined) {
  21827. mesh.applyFog = parsedMesh.applyFog;
  21828. }
  21829. if (parsedMesh.pickable !== undefined) {
  21830. mesh.isPickable = parsedMesh.pickable;
  21831. }
  21832. if (parsedMesh.alphaIndex !== undefined) {
  21833. mesh.alphaIndex = parsedMesh.alphaIndex;
  21834. }
  21835. mesh.receiveShadows = parsedMesh.receiveShadows;
  21836. mesh.billboardMode = parsedMesh.billboardMode;
  21837. if (parsedMesh.visibility !== undefined) {
  21838. mesh.visibility = parsedMesh.visibility;
  21839. }
  21840. mesh.checkCollisions = parsedMesh.checkCollisions;
  21841. if (parsedMesh.isBlocker !== undefined) {
  21842. mesh.isBlocker = parsedMesh.isBlocker;
  21843. }
  21844. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21845. // freezeWorldMatrix
  21846. if (parsedMesh.freezeWorldMatrix) {
  21847. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21848. }
  21849. // Parent
  21850. if (parsedMesh.parentId) {
  21851. mesh._waitingParentId = parsedMesh.parentId;
  21852. }
  21853. // Actions
  21854. if (parsedMesh.actions !== undefined) {
  21855. mesh._waitingActions = parsedMesh.actions;
  21856. }
  21857. // Overlay
  21858. if (parsedMesh.overlayAlpha !== undefined) {
  21859. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21860. }
  21861. if (parsedMesh.overlayColor !== undefined) {
  21862. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21863. }
  21864. if (parsedMesh.renderOverlay !== undefined) {
  21865. mesh.renderOverlay = parsedMesh.renderOverlay;
  21866. }
  21867. // Geometry
  21868. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21869. if (parsedMesh.delayLoadingFile) {
  21870. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21871. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21872. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21873. if (parsedMesh._binaryInfo) {
  21874. mesh._binaryInfo = parsedMesh._binaryInfo;
  21875. }
  21876. mesh._delayInfo = [];
  21877. if (parsedMesh.hasUVs) {
  21878. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21879. }
  21880. if (parsedMesh.hasUVs2) {
  21881. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21882. }
  21883. if (parsedMesh.hasUVs3) {
  21884. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21885. }
  21886. if (parsedMesh.hasUVs4) {
  21887. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21888. }
  21889. if (parsedMesh.hasUVs5) {
  21890. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21891. }
  21892. if (parsedMesh.hasUVs6) {
  21893. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21894. }
  21895. if (parsedMesh.hasColors) {
  21896. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21897. }
  21898. if (parsedMesh.hasMatricesIndices) {
  21899. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21900. }
  21901. if (parsedMesh.hasMatricesWeights) {
  21902. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21903. }
  21904. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21905. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21906. mesh._checkDelayState();
  21907. }
  21908. }
  21909. else {
  21910. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21911. }
  21912. // Material
  21913. if (parsedMesh.materialId) {
  21914. mesh.setMaterialByID(parsedMesh.materialId);
  21915. }
  21916. else {
  21917. mesh.material = null;
  21918. }
  21919. // Skeleton
  21920. if (parsedMesh.skeletonId > -1) {
  21921. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21922. if (parsedMesh.numBoneInfluencers) {
  21923. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21924. }
  21925. }
  21926. // Animations
  21927. if (parsedMesh.animations) {
  21928. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21929. var parsedAnimation = parsedMesh.animations[animationIndex];
  21930. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21931. }
  21932. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21933. }
  21934. if (parsedMesh.autoAnimate) {
  21935. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21936. }
  21937. // Layer Mask
  21938. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21939. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21940. }
  21941. else {
  21942. mesh.layerMask = 0x0FFFFFFF;
  21943. }
  21944. //(Deprecated) physics
  21945. if (parsedMesh.physicsImpostor) {
  21946. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21947. mass: parsedMesh.physicsMass,
  21948. friction: parsedMesh.physicsFriction,
  21949. restitution: parsedMesh.physicsRestitution
  21950. }, scene);
  21951. }
  21952. // Instances
  21953. if (parsedMesh.instances) {
  21954. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21955. var parsedInstance = parsedMesh.instances[index];
  21956. var instance = mesh.createInstance(parsedInstance.name);
  21957. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21958. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21959. if (parsedInstance.parentId) {
  21960. instance._waitingParentId = parsedInstance.parentId;
  21961. }
  21962. if (parsedInstance.rotationQuaternion) {
  21963. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21964. }
  21965. else if (parsedInstance.rotation) {
  21966. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21967. }
  21968. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21969. instance.checkCollisions = mesh.checkCollisions;
  21970. if (parsedMesh.animations) {
  21971. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21972. parsedAnimation = parsedMesh.animations[animationIndex];
  21973. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21974. }
  21975. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21976. }
  21977. }
  21978. }
  21979. return mesh;
  21980. };
  21981. /**
  21982. * Creates a ribbon mesh.
  21983. * Please consider using the same method from the MeshBuilder class instead.
  21984. * 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.
  21985. *
  21986. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21987. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21988. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21989. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21990. * 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.
  21991. * 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.
  21992. * 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
  21993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21996. */
  21997. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21998. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21999. pathArray: pathArray,
  22000. closeArray: closeArray,
  22001. closePath: closePath,
  22002. offset: offset,
  22003. updatable: updatable,
  22004. sideOrientation: sideOrientation,
  22005. instance: instance
  22006. }, scene);
  22007. };
  22008. /**
  22009. * Creates a plane polygonal mesh. By default, this is a disc.
  22010. * Please consider using the same method from the MeshBuilder class instead.
  22011. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22012. * 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.
  22013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22016. */
  22017. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22018. var options = {
  22019. radius: radius,
  22020. tessellation: tessellation,
  22021. sideOrientation: sideOrientation,
  22022. updatable: updatable
  22023. };
  22024. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22025. };
  22026. /**
  22027. * Creates a box mesh.
  22028. * Please consider using the same method from the MeshBuilder class instead.
  22029. * The parameter `size` sets the size (float) of each box side (default 1).
  22030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22033. */
  22034. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22035. var options = {
  22036. size: size,
  22037. sideOrientation: sideOrientation,
  22038. updatable: updatable
  22039. };
  22040. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22041. };
  22042. /**
  22043. * Creates a sphere mesh.
  22044. * Please consider using the same method from the MeshBuilder class instead.
  22045. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22046. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22050. */
  22051. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22052. var options = {
  22053. segments: segments,
  22054. diameterX: diameter,
  22055. diameterY: diameter,
  22056. diameterZ: diameter,
  22057. sideOrientation: sideOrientation,
  22058. updatable: updatable
  22059. };
  22060. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22061. };
  22062. /**
  22063. * Creates a cylinder or a cone mesh.
  22064. * Please consider using the same method from the MeshBuilder class instead.
  22065. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22066. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22067. * 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.
  22068. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22069. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22073. */
  22074. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22075. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22076. if (scene !== undefined) {
  22077. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22078. updatable = scene;
  22079. }
  22080. scene = subdivisions;
  22081. subdivisions = 1;
  22082. }
  22083. var options = {
  22084. height: height,
  22085. diameterTop: diameterTop,
  22086. diameterBottom: diameterBottom,
  22087. tessellation: tessellation,
  22088. subdivisions: subdivisions,
  22089. sideOrientation: sideOrientation,
  22090. updatable: updatable
  22091. };
  22092. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22093. };
  22094. // Torus (Code from SharpDX.org)
  22095. /**
  22096. * Creates a torus mesh.
  22097. * Please consider using the same method from the MeshBuilder class instead.
  22098. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22099. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22100. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22104. */
  22105. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22106. var options = {
  22107. diameter: diameter,
  22108. thickness: thickness,
  22109. tessellation: tessellation,
  22110. sideOrientation: sideOrientation,
  22111. updatable: updatable
  22112. };
  22113. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22114. };
  22115. /**
  22116. * Creates a torus knot mesh.
  22117. * Please consider using the same method from the MeshBuilder class instead.
  22118. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22119. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22120. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22121. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22123. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22125. */
  22126. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22127. var options = {
  22128. radius: radius,
  22129. tube: tube,
  22130. radialSegments: radialSegments,
  22131. tubularSegments: tubularSegments,
  22132. p: p,
  22133. q: q,
  22134. sideOrientation: sideOrientation,
  22135. updatable: updatable
  22136. };
  22137. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22138. };
  22139. /**
  22140. * Creates a line mesh.
  22141. * Please consider using the same method from the MeshBuilder class instead.
  22142. * 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.
  22143. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22144. * The parameter `points` is an array successive Vector3.
  22145. * 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
  22146. * When updating an instance, remember that only point positions can change, not the number of points.
  22147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22148. */
  22149. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22150. var options = {
  22151. points: points,
  22152. updatable: updatable,
  22153. instance: instance
  22154. };
  22155. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22156. };
  22157. /**
  22158. * Creates a dashed line mesh.
  22159. * Please consider using the same method from the MeshBuilder class instead.
  22160. * 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.
  22161. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22162. * The parameter `points` is an array successive Vector3.
  22163. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22164. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22165. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22166. * 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
  22167. * When updating an instance, remember that only point positions can change, not the number of points.
  22168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22169. */
  22170. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22171. var options = {
  22172. points: points,
  22173. dashSize: dashSize,
  22174. gapSize: gapSize,
  22175. dashNb: dashNb,
  22176. updatable: updatable,
  22177. instance: instance
  22178. };
  22179. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22180. };
  22181. /**
  22182. * Creates an extruded shape mesh.
  22183. * 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.
  22184. * Please consider using the same method from the MeshBuilder class instead.
  22185. *
  22186. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22187. * 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
  22188. * extruded along the Z axis.
  22189. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22190. * 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.
  22191. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22192. * 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
  22193. * 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
  22194. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22198. */
  22199. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22200. var options = {
  22201. shape: shape,
  22202. path: path,
  22203. scale: scale,
  22204. rotation: rotation,
  22205. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22206. sideOrientation: sideOrientation,
  22207. instance: instance,
  22208. updatable: updatable
  22209. };
  22210. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22211. };
  22212. /**
  22213. * Creates an custom extruded shape mesh.
  22214. * 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.
  22215. * Please consider using the same method from the MeshBuilder class instead.
  22216. *
  22217. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22218. * 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
  22219. * extruded along the Z axis.
  22220. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22221. * 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
  22222. * and the distance of this point from the begining of the path :
  22223. * ```javascript
  22224. * var rotationFunction = function(i, distance) {
  22225. * // do things
  22226. * return rotationValue; }
  22227. * ```
  22228. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22229. * 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
  22230. * and the distance of this point from the begining of the path :
  22231. * ```javascript
  22232. * var scaleFunction = function(i, distance) {
  22233. * // do things
  22234. * return scaleValue;}
  22235. * ```
  22236. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22237. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22238. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22239. * 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
  22240. * 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
  22241. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22243. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22245. */
  22246. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22247. var options = {
  22248. shape: shape,
  22249. path: path,
  22250. scaleFunction: scaleFunction,
  22251. rotationFunction: rotationFunction,
  22252. ribbonCloseArray: ribbonCloseArray,
  22253. ribbonClosePath: ribbonClosePath,
  22254. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22255. sideOrientation: sideOrientation,
  22256. instance: instance,
  22257. updatable: updatable
  22258. };
  22259. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22260. };
  22261. /**
  22262. * Creates lathe mesh.
  22263. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22264. * Please consider using the same method from the MeshBuilder class instead.
  22265. * 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
  22266. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22267. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22268. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22270. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22272. */
  22273. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22274. var options = {
  22275. shape: shape,
  22276. radius: radius,
  22277. tessellation: tessellation,
  22278. sideOrientation: sideOrientation,
  22279. updatable: updatable
  22280. };
  22281. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22282. };
  22283. /**
  22284. * Creates a plane mesh.
  22285. * Please consider using the same method from the MeshBuilder class instead.
  22286. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22290. */
  22291. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22292. var options = {
  22293. size: size,
  22294. width: size,
  22295. height: size,
  22296. sideOrientation: sideOrientation,
  22297. updatable: updatable
  22298. };
  22299. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22300. };
  22301. /**
  22302. * Creates a ground mesh.
  22303. * Please consider using the same method from the MeshBuilder class instead.
  22304. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22305. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22307. */
  22308. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22309. var options = {
  22310. width: width,
  22311. height: height,
  22312. subdivisions: subdivisions,
  22313. updatable: updatable
  22314. };
  22315. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22316. };
  22317. /**
  22318. * Creates a tiled ground mesh.
  22319. * Please consider using the same method from the MeshBuilder class instead.
  22320. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22321. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22322. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22323. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22324. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22325. * numbers of subdivisions on the ground width and height of each tile.
  22326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22327. */
  22328. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22329. var options = {
  22330. xmin: xmin,
  22331. zmin: zmin,
  22332. xmax: xmax,
  22333. zmax: zmax,
  22334. subdivisions: subdivisions,
  22335. precision: precision,
  22336. updatable: updatable
  22337. };
  22338. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22339. };
  22340. /**
  22341. * Creates a ground mesh from a height map.
  22342. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22343. * Please consider using the same method from the MeshBuilder class instead.
  22344. * The parameter `url` sets the URL of the height map image resource.
  22345. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22346. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22347. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22348. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22349. * 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).
  22350. * This function is passed the newly built mesh :
  22351. * ```javascript
  22352. * function(mesh) { // do things
  22353. * return; }
  22354. * ```
  22355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22356. */
  22357. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22358. var options = {
  22359. width: width,
  22360. height: height,
  22361. subdivisions: subdivisions,
  22362. minHeight: minHeight,
  22363. maxHeight: maxHeight,
  22364. updatable: updatable,
  22365. onReady: onReady
  22366. };
  22367. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22368. };
  22369. /**
  22370. * Creates a tube mesh.
  22371. * 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.
  22372. * Please consider using the same method from the MeshBuilder class instead.
  22373. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22374. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22375. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22376. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22377. * 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.
  22378. * It must return a radius value (positive float) :
  22379. * ```javascript
  22380. * var radiusFunction = function(i, distance) {
  22381. * // do things
  22382. * return radius; }
  22383. * ```
  22384. * 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
  22385. * 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
  22386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22389. */
  22390. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22391. var options = {
  22392. path: path,
  22393. radius: radius,
  22394. tessellation: tessellation,
  22395. radiusFunction: radiusFunction,
  22396. arc: 1,
  22397. cap: cap,
  22398. updatable: updatable,
  22399. sideOrientation: sideOrientation,
  22400. instance: instance
  22401. };
  22402. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22403. };
  22404. /**
  22405. * Creates a polyhedron mesh.
  22406. * Please consider using the same method from the MeshBuilder class instead.
  22407. * 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
  22408. * to choose the wanted type.
  22409. * The parameter `size` (positive float, default 1) sets the polygon size.
  22410. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22411. * 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`.
  22412. * 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
  22413. * 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)`).
  22414. * 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
  22415. * 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.
  22416. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22417. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22419. */
  22420. Mesh.CreatePolyhedron = function (name, options, scene) {
  22421. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22422. };
  22423. /**
  22424. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22425. * Please consider using the same method from the MeshBuilder class instead.
  22426. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22427. * 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`).
  22428. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22429. * 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.
  22430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22431. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22433. */
  22434. Mesh.CreateIcoSphere = function (name, options, scene) {
  22435. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22436. };
  22437. /**
  22438. * Creates a decal mesh.
  22439. * Please consider using the same method from the MeshBuilder class instead.
  22440. * 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.
  22441. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22442. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22443. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22444. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22445. */
  22446. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22447. var options = {
  22448. position: position,
  22449. normal: normal,
  22450. size: size,
  22451. angle: angle
  22452. };
  22453. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22454. };
  22455. // Skeletons
  22456. /**
  22457. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22458. */
  22459. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22460. var source;
  22461. if (!this._sourcePositions) {
  22462. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22463. this._sourcePositions = new Float32Array(source);
  22464. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22465. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22466. }
  22467. }
  22468. return this._sourcePositions;
  22469. };
  22470. /**
  22471. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22472. */
  22473. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22474. var source;
  22475. if (!this._sourceNormals) {
  22476. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22477. this._sourceNormals = new Float32Array(source);
  22478. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22479. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22480. }
  22481. }
  22482. return this._sourceNormals;
  22483. };
  22484. /**
  22485. * Update the vertex buffers by applying transformation from the bones
  22486. * @param {skeleton} skeleton to apply
  22487. */
  22488. Mesh.prototype.applySkeleton = function (skeleton) {
  22489. if (!this.geometry) {
  22490. return;
  22491. }
  22492. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22493. return;
  22494. }
  22495. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22496. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22497. return this;
  22498. }
  22499. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22500. return this;
  22501. }
  22502. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22503. return this;
  22504. }
  22505. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22506. return this;
  22507. }
  22508. if (!this._sourcePositions) {
  22509. var submeshes = this.subMeshes.slice();
  22510. this.setPositionsForCPUSkinning();
  22511. this.subMeshes = submeshes;
  22512. }
  22513. if (!this._sourceNormals) {
  22514. this.setNormalsForCPUSkinning();
  22515. }
  22516. // positionsData checks for not being Float32Array will only pass at most once
  22517. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22518. if (!(positionsData instanceof Float32Array)) {
  22519. positionsData = new Float32Array(positionsData);
  22520. }
  22521. // normalsData checks for not being Float32Array will only pass at most once
  22522. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22523. if (!(normalsData instanceof Float32Array)) {
  22524. normalsData = new Float32Array(normalsData);
  22525. }
  22526. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22527. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22528. var needExtras = this.numBoneInfluencers > 4;
  22529. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22530. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22531. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22532. var tempVector3 = BABYLON.Vector3.Zero();
  22533. var finalMatrix = new BABYLON.Matrix();
  22534. var tempMatrix = new BABYLON.Matrix();
  22535. var matWeightIdx = 0;
  22536. var inf;
  22537. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22538. var weight;
  22539. for (inf = 0; inf < 4; inf++) {
  22540. weight = matricesWeightsData[matWeightIdx + inf];
  22541. if (weight > 0) {
  22542. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22543. finalMatrix.addToSelf(tempMatrix);
  22544. }
  22545. else
  22546. break;
  22547. }
  22548. if (needExtras) {
  22549. for (inf = 0; inf < 4; inf++) {
  22550. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22551. if (weight > 0) {
  22552. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22553. finalMatrix.addToSelf(tempMatrix);
  22554. }
  22555. else
  22556. break;
  22557. }
  22558. }
  22559. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22560. tempVector3.toArray(positionsData, index);
  22561. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22562. tempVector3.toArray(normalsData, index);
  22563. finalMatrix.reset();
  22564. }
  22565. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22566. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22567. return this;
  22568. };
  22569. // Tools
  22570. /**
  22571. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22572. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22573. */
  22574. Mesh.MinMax = function (meshes) {
  22575. var minVector = null;
  22576. var maxVector = null;
  22577. meshes.forEach(function (mesh, index, array) {
  22578. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22579. if (!minVector) {
  22580. minVector = boundingBox.minimumWorld;
  22581. maxVector = boundingBox.maximumWorld;
  22582. }
  22583. else {
  22584. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22585. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22586. }
  22587. });
  22588. return {
  22589. min: minVector,
  22590. max: maxVector
  22591. };
  22592. };
  22593. /**
  22594. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22595. */
  22596. Mesh.Center = function (meshesOrMinMaxVector) {
  22597. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22598. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22599. };
  22600. /**
  22601. * Merge the array of meshes into a single mesh for performance reasons.
  22602. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22603. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22604. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22605. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22606. */
  22607. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  22608. if (disposeSource === void 0) { disposeSource = true; }
  22609. var index;
  22610. if (!allow32BitsIndices) {
  22611. var totalVertices = 0;
  22612. // Counting vertices
  22613. for (index = 0; index < meshes.length; index++) {
  22614. if (meshes[index]) {
  22615. totalVertices += meshes[index].getTotalVertices();
  22616. if (totalVertices > 65536) {
  22617. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22618. return null;
  22619. }
  22620. }
  22621. }
  22622. }
  22623. // Merge
  22624. var vertexData;
  22625. var otherVertexData;
  22626. var source;
  22627. for (index = 0; index < meshes.length; index++) {
  22628. if (meshes[index]) {
  22629. meshes[index].computeWorldMatrix(true);
  22630. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22631. otherVertexData.transform(meshes[index].getWorldMatrix());
  22632. if (vertexData) {
  22633. vertexData.merge(otherVertexData);
  22634. }
  22635. else {
  22636. vertexData = otherVertexData;
  22637. source = meshes[index];
  22638. }
  22639. }
  22640. }
  22641. if (!meshSubclass) {
  22642. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22643. }
  22644. vertexData.applyToMesh(meshSubclass);
  22645. // Setting properties
  22646. meshSubclass.material = source.material;
  22647. meshSubclass.checkCollisions = source.checkCollisions;
  22648. // Cleaning
  22649. if (disposeSource) {
  22650. for (index = 0; index < meshes.length; index++) {
  22651. if (meshes[index]) {
  22652. meshes[index].dispose();
  22653. }
  22654. }
  22655. }
  22656. return meshSubclass;
  22657. };
  22658. return Mesh;
  22659. }(BABYLON.AbstractMesh));
  22660. // Consts
  22661. Mesh._FRONTSIDE = 0;
  22662. Mesh._BACKSIDE = 1;
  22663. Mesh._DOUBLESIDE = 2;
  22664. Mesh._DEFAULTSIDE = 0;
  22665. Mesh._NO_CAP = 0;
  22666. Mesh._CAP_START = 1;
  22667. Mesh._CAP_END = 2;
  22668. Mesh._CAP_ALL = 3;
  22669. BABYLON.Mesh = Mesh;
  22670. })(BABYLON || (BABYLON = {}));
  22671. //# sourceMappingURL=babylon.mesh.js.map
  22672. var BABYLON;
  22673. (function (BABYLON) {
  22674. var SubMesh = (function () {
  22675. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22676. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22677. this.materialIndex = materialIndex;
  22678. this.verticesStart = verticesStart;
  22679. this.verticesCount = verticesCount;
  22680. this.indexStart = indexStart;
  22681. this.indexCount = indexCount;
  22682. this._renderId = 0;
  22683. this._mesh = mesh;
  22684. this._renderingMesh = renderingMesh || mesh;
  22685. mesh.subMeshes.push(this);
  22686. this._trianglePlanes = [];
  22687. this._id = mesh.subMeshes.length - 1;
  22688. if (createBoundingBox) {
  22689. this.refreshBoundingInfo();
  22690. mesh.computeWorldMatrix(true);
  22691. }
  22692. }
  22693. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22694. get: function () {
  22695. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22696. },
  22697. enumerable: true,
  22698. configurable: true
  22699. });
  22700. SubMesh.prototype.getBoundingInfo = function () {
  22701. if (this.IsGlobal) {
  22702. return this._mesh.getBoundingInfo();
  22703. }
  22704. return this._boundingInfo;
  22705. };
  22706. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22707. this._boundingInfo = boundingInfo;
  22708. };
  22709. SubMesh.prototype.getMesh = function () {
  22710. return this._mesh;
  22711. };
  22712. SubMesh.prototype.getRenderingMesh = function () {
  22713. return this._renderingMesh;
  22714. };
  22715. SubMesh.prototype.getMaterial = function () {
  22716. var rootMaterial = this._renderingMesh.material;
  22717. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22718. var multiMaterial = rootMaterial;
  22719. return multiMaterial.getSubMaterial(this.materialIndex);
  22720. }
  22721. if (!rootMaterial) {
  22722. return this._mesh.getScene().defaultMaterial;
  22723. }
  22724. return rootMaterial;
  22725. };
  22726. // Methods
  22727. SubMesh.prototype.refreshBoundingInfo = function () {
  22728. this._lastColliderWorldVertices = null;
  22729. if (this.IsGlobal) {
  22730. return;
  22731. }
  22732. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22733. if (!data) {
  22734. this._boundingInfo = this._mesh._boundingInfo;
  22735. return;
  22736. }
  22737. var indices = this._renderingMesh.getIndices();
  22738. var extend;
  22739. //is this the only submesh?
  22740. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22741. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22742. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22743. }
  22744. else {
  22745. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22746. }
  22747. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22748. };
  22749. SubMesh.prototype._checkCollision = function (collider) {
  22750. return this.getBoundingInfo()._checkCollision(collider);
  22751. };
  22752. SubMesh.prototype.updateBoundingInfo = function (world) {
  22753. if (!this.getBoundingInfo()) {
  22754. this.refreshBoundingInfo();
  22755. }
  22756. this.getBoundingInfo().update(world);
  22757. };
  22758. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22759. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22760. };
  22761. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22762. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22763. };
  22764. SubMesh.prototype.render = function (enableAlphaMode) {
  22765. this._renderingMesh.render(this, enableAlphaMode);
  22766. };
  22767. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22768. if (!this._linesIndexBuffer) {
  22769. var linesIndices = [];
  22770. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22771. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22772. }
  22773. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22774. this.linesIndexCount = linesIndices.length;
  22775. }
  22776. return this._linesIndexBuffer;
  22777. };
  22778. SubMesh.prototype.canIntersects = function (ray) {
  22779. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22780. };
  22781. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22782. var intersectInfo = null;
  22783. // LineMesh first as it's also a Mesh...
  22784. if (this._mesh instanceof BABYLON.LinesMesh) {
  22785. var lineMesh = this._mesh;
  22786. // Line test
  22787. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22788. var p0 = positions[indices[index]];
  22789. var p1 = positions[indices[index + 1]];
  22790. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22791. if (length < 0) {
  22792. continue;
  22793. }
  22794. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22795. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22796. if (fastCheck) {
  22797. break;
  22798. }
  22799. }
  22800. }
  22801. }
  22802. else {
  22803. // Triangles test
  22804. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22805. var p0 = positions[indices[index]];
  22806. var p1 = positions[indices[index + 1]];
  22807. var p2 = positions[indices[index + 2]];
  22808. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22809. if (currentIntersectInfo) {
  22810. if (currentIntersectInfo.distance < 0) {
  22811. continue;
  22812. }
  22813. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22814. intersectInfo = currentIntersectInfo;
  22815. intersectInfo.faceId = index / 3;
  22816. if (fastCheck) {
  22817. break;
  22818. }
  22819. }
  22820. }
  22821. }
  22822. }
  22823. return intersectInfo;
  22824. };
  22825. // Clone
  22826. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22827. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22828. if (!this.IsGlobal) {
  22829. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22830. }
  22831. return result;
  22832. };
  22833. // Dispose
  22834. SubMesh.prototype.dispose = function () {
  22835. if (this._linesIndexBuffer) {
  22836. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22837. this._linesIndexBuffer = null;
  22838. }
  22839. // Remove from mesh
  22840. var index = this._mesh.subMeshes.indexOf(this);
  22841. this._mesh.subMeshes.splice(index, 1);
  22842. };
  22843. // Statics
  22844. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22845. var minVertexIndex = Number.MAX_VALUE;
  22846. var maxVertexIndex = -Number.MAX_VALUE;
  22847. renderingMesh = renderingMesh || mesh;
  22848. var indices = renderingMesh.getIndices();
  22849. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22850. var vertexIndex = indices[index];
  22851. if (vertexIndex < minVertexIndex)
  22852. minVertexIndex = vertexIndex;
  22853. if (vertexIndex > maxVertexIndex)
  22854. maxVertexIndex = vertexIndex;
  22855. }
  22856. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22857. };
  22858. return SubMesh;
  22859. }());
  22860. BABYLON.SubMesh = SubMesh;
  22861. })(BABYLON || (BABYLON = {}));
  22862. //# sourceMappingURL=babylon.subMesh.js.map
  22863. var BABYLON;
  22864. (function (BABYLON) {
  22865. var MeshBuilder = (function () {
  22866. function MeshBuilder() {
  22867. }
  22868. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22869. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22870. return BABYLON.Mesh.DOUBLESIDE;
  22871. }
  22872. if (orientation === undefined || orientation === null) {
  22873. return BABYLON.Mesh.FRONTSIDE;
  22874. }
  22875. return orientation;
  22876. };
  22877. /**
  22878. * Creates a box mesh.
  22879. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22880. * The parameter `size` sets the size (float) of each box side (default 1).
  22881. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22882. * 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).
  22883. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22887. */
  22888. MeshBuilder.CreateBox = function (name, options, scene) {
  22889. var box = new BABYLON.Mesh(name, scene);
  22890. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22891. box.sideOrientation = options.sideOrientation;
  22892. var vertexData = BABYLON.VertexData.CreateBox(options);
  22893. vertexData.applyToMesh(box, options.updatable);
  22894. return box;
  22895. };
  22896. /**
  22897. * Creates a sphere mesh.
  22898. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22899. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22900. * 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`).
  22901. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22902. * 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
  22903. * 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).
  22904. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22905. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22906. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22907. */
  22908. MeshBuilder.CreateSphere = function (name, options, scene) {
  22909. var sphere = new BABYLON.Mesh(name, scene);
  22910. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22911. sphere.sideOrientation = options.sideOrientation;
  22912. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22913. vertexData.applyToMesh(sphere, options.updatable);
  22914. return sphere;
  22915. };
  22916. /**
  22917. * Creates a plane polygonal mesh. By default, this is a disc.
  22918. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22919. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22920. * 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.
  22921. * 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
  22922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22923. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22925. */
  22926. MeshBuilder.CreateDisc = function (name, options, scene) {
  22927. var disc = new BABYLON.Mesh(name, scene);
  22928. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22929. disc.sideOrientation = options.sideOrientation;
  22930. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22931. vertexData.applyToMesh(disc, options.updatable);
  22932. return disc;
  22933. };
  22934. /**
  22935. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22936. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22937. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22938. * 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`).
  22939. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22940. * 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.
  22941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22944. */
  22945. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22946. var sphere = new BABYLON.Mesh(name, scene);
  22947. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22948. sphere.sideOrientation = options.sideOrientation;
  22949. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22950. vertexData.applyToMesh(sphere, options.updatable);
  22951. return sphere;
  22952. };
  22953. ;
  22954. /**
  22955. * Creates a ribbon mesh.
  22956. * 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.
  22957. *
  22958. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22959. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22960. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22961. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22962. * 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.
  22963. * 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.
  22964. * 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
  22965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22967. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22969. */
  22970. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22971. var pathArray = options.pathArray;
  22972. var closeArray = options.closeArray;
  22973. var closePath = options.closePath;
  22974. var offset = options.offset;
  22975. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  22976. var instance = options.instance;
  22977. var updatable = options.updatable;
  22978. if (instance) {
  22979. // positionFunction : ribbon case
  22980. // only pathArray and sideOrientation parameters are taken into account for positions update
  22981. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22982. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22983. var positionFunction = function (positions) {
  22984. var minlg = pathArray[0].length;
  22985. var i = 0;
  22986. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22987. for (var si = 1; si <= ns; si++) {
  22988. for (var p = 0; p < pathArray.length; p++) {
  22989. var path = pathArray[p];
  22990. var l = path.length;
  22991. minlg = (minlg < l) ? minlg : l;
  22992. var j = 0;
  22993. while (j < minlg) {
  22994. positions[i] = path[j].x;
  22995. positions[i + 1] = path[j].y;
  22996. positions[i + 2] = path[j].z;
  22997. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22998. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22999. }
  23000. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  23001. BABYLON.Tmp.Vector3[1].x = path[j].x;
  23002. }
  23003. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  23004. BABYLON.Tmp.Vector3[0].y = path[j].y;
  23005. }
  23006. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  23007. BABYLON.Tmp.Vector3[1].y = path[j].y;
  23008. }
  23009. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  23010. BABYLON.Tmp.Vector3[0].z = path[j].z;
  23011. }
  23012. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  23013. BABYLON.Tmp.Vector3[1].z = path[j].z;
  23014. }
  23015. j++;
  23016. i += 3;
  23017. }
  23018. if (instance._closePath) {
  23019. positions[i] = path[0].x;
  23020. positions[i + 1] = path[0].y;
  23021. positions[i + 2] = path[0].z;
  23022. i += 3;
  23023. }
  23024. }
  23025. }
  23026. };
  23027. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23028. positionFunction(positions);
  23029. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  23030. instance._boundingInfo.update(instance._worldMatrix);
  23031. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23032. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  23033. var indices = instance.getIndices();
  23034. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23035. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  23036. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  23037. if (instance._closePath) {
  23038. var indexFirst = 0;
  23039. var indexLast = 0;
  23040. for (var p = 0; p < pathArray.length; p++) {
  23041. indexFirst = instance._idx[p] * 3;
  23042. if (p + 1 < pathArray.length) {
  23043. indexLast = (instance._idx[p + 1] - 1) * 3;
  23044. }
  23045. else {
  23046. indexLast = normals.length - 3;
  23047. }
  23048. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23049. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23050. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23051. normals[indexLast] = normals[indexFirst];
  23052. normals[indexLast + 1] = normals[indexFirst + 1];
  23053. normals[indexLast + 2] = normals[indexFirst + 2];
  23054. }
  23055. }
  23056. if (!(instance.areNormalsFrozen)) {
  23057. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23058. }
  23059. }
  23060. return instance;
  23061. }
  23062. else {
  23063. var ribbon = new BABYLON.Mesh(name, scene);
  23064. ribbon.sideOrientation = sideOrientation;
  23065. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  23066. if (closePath) {
  23067. ribbon._idx = vertexData._idx;
  23068. }
  23069. ribbon._closePath = closePath;
  23070. ribbon._closeArray = closeArray;
  23071. vertexData.applyToMesh(ribbon, updatable);
  23072. return ribbon;
  23073. }
  23074. };
  23075. /**
  23076. * Creates a cylinder or a cone mesh.
  23077. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  23078. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23079. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23080. * 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.
  23081. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23082. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23083. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  23084. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  23085. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  23086. * 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).
  23087. * 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
  23088. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  23089. * 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
  23090. * 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.
  23091. * If `enclose` is false, a ring surface is one element.
  23092. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  23093. * 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
  23094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23097. */
  23098. MeshBuilder.CreateCylinder = function (name, options, scene) {
  23099. var cylinder = new BABYLON.Mesh(name, scene);
  23100. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23101. cylinder.sideOrientation = options.sideOrientation;
  23102. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  23103. vertexData.applyToMesh(cylinder, options.updatable);
  23104. return cylinder;
  23105. };
  23106. /**
  23107. * Creates a torus mesh.
  23108. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  23109. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23110. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23111. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23113. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23115. */
  23116. MeshBuilder.CreateTorus = function (name, options, scene) {
  23117. var torus = new BABYLON.Mesh(name, scene);
  23118. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23119. torus.sideOrientation = options.sideOrientation;
  23120. var vertexData = BABYLON.VertexData.CreateTorus(options);
  23121. vertexData.applyToMesh(torus, options.updatable);
  23122. return torus;
  23123. };
  23124. /**
  23125. * Creates a torus knot mesh.
  23126. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  23127. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23128. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23129. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23130. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23131. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23132. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23134. */
  23135. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  23136. var torusKnot = new BABYLON.Mesh(name, scene);
  23137. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23138. torusKnot.sideOrientation = options.sideOrientation;
  23139. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  23140. vertexData.applyToMesh(torusKnot, options.updatable);
  23141. return torusKnot;
  23142. };
  23143. /**
  23144. * Creates a line system mesh.
  23145. * A line system is a pool of many lines gathered in a single mesh.
  23146. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  23147. * 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.
  23148. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  23149. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  23150. * 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
  23151. * 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
  23152. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  23153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23154. */
  23155. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  23156. var instance = options.instance;
  23157. var lines = options.lines;
  23158. if (instance) {
  23159. var positionFunction = function (positions) {
  23160. var i = 0;
  23161. for (var l = 0; l < lines.length; l++) {
  23162. var points = lines[l];
  23163. for (var p = 0; p < points.length; p++) {
  23164. positions[i] = points[p].x;
  23165. positions[i + 1] = points[p].y;
  23166. positions[i + 2] = points[p].z;
  23167. i += 3;
  23168. }
  23169. }
  23170. };
  23171. instance.updateMeshPositions(positionFunction, false);
  23172. return instance;
  23173. }
  23174. // line system creation
  23175. var lineSystem = new BABYLON.LinesMesh(name, scene);
  23176. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  23177. vertexData.applyToMesh(lineSystem, options.updatable);
  23178. return lineSystem;
  23179. };
  23180. /**
  23181. * Creates a line mesh.
  23182. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  23183. * 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.
  23184. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23185. * The parameter `points` is an array successive Vector3.
  23186. * 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
  23187. * When updating an instance, remember that only point positions can change, not the number of points.
  23188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23189. */
  23190. MeshBuilder.CreateLines = function (name, options, scene) {
  23191. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  23192. return lines;
  23193. };
  23194. /**
  23195. * Creates a dashed line mesh.
  23196. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  23197. * 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.
  23198. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23199. * The parameter `points` is an array successive Vector3.
  23200. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23201. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23202. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23203. * 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
  23204. * When updating an instance, remember that only point positions can change, not the number of points.
  23205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23206. */
  23207. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  23208. var points = options.points;
  23209. var instance = options.instance;
  23210. var gapSize = options.gapSize;
  23211. var dashNb = options.dashNb;
  23212. var dashSize = options.dashSize;
  23213. if (instance) {
  23214. var positionFunction = function (positions) {
  23215. var curvect = BABYLON.Vector3.Zero();
  23216. var nbSeg = positions.length / 6;
  23217. var lg = 0;
  23218. var nb = 0;
  23219. var shft = 0;
  23220. var dashshft = 0;
  23221. var curshft = 0;
  23222. var p = 0;
  23223. var i = 0;
  23224. var j = 0;
  23225. for (i = 0; i < points.length - 1; i++) {
  23226. points[i + 1].subtractToRef(points[i], curvect);
  23227. lg += curvect.length();
  23228. }
  23229. shft = lg / nbSeg;
  23230. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  23231. for (i = 0; i < points.length - 1; i++) {
  23232. points[i + 1].subtractToRef(points[i], curvect);
  23233. nb = Math.floor(curvect.length() / shft);
  23234. curvect.normalize();
  23235. j = 0;
  23236. while (j < nb && p < positions.length) {
  23237. curshft = shft * j;
  23238. positions[p] = points[i].x + curshft * curvect.x;
  23239. positions[p + 1] = points[i].y + curshft * curvect.y;
  23240. positions[p + 2] = points[i].z + curshft * curvect.z;
  23241. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  23242. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  23243. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  23244. p += 6;
  23245. j++;
  23246. }
  23247. }
  23248. while (p < positions.length) {
  23249. positions[p] = points[i].x;
  23250. positions[p + 1] = points[i].y;
  23251. positions[p + 2] = points[i].z;
  23252. p += 3;
  23253. }
  23254. };
  23255. instance.updateMeshPositions(positionFunction, false);
  23256. return instance;
  23257. }
  23258. // dashed lines creation
  23259. var dashedLines = new BABYLON.LinesMesh(name, scene);
  23260. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  23261. vertexData.applyToMesh(dashedLines, options.updatable);
  23262. dashedLines.dashSize = dashSize;
  23263. dashedLines.gapSize = gapSize;
  23264. return dashedLines;
  23265. };
  23266. /**
  23267. * Creates an extruded shape mesh.
  23268. * 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.
  23269. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  23270. *
  23271. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23272. * 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
  23273. * extruded along the Z axis.
  23274. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23275. * 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.
  23276. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23277. * 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
  23278. * 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
  23279. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23280. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23281. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23282. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23284. */
  23285. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  23286. var path = options.path;
  23287. var shape = options.shape;
  23288. var scale = options.scale || 1;
  23289. var rotation = options.rotation || 0;
  23290. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23291. var updatable = options.updatable;
  23292. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23293. var instance = options.instance;
  23294. var invertUV = options.invertUV || false;
  23295. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  23296. };
  23297. /**
  23298. * Creates an custom extruded shape mesh.
  23299. * 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.
  23300. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  23301. *
  23302. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23303. * 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
  23304. * extruded along the Z axis.
  23305. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23306. * 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
  23307. * and the distance of this point from the begining of the path :
  23308. * ```javascript
  23309. * var rotationFunction = function(i, distance) {
  23310. * // do things
  23311. * return rotationValue; }
  23312. * ```
  23313. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23314. * 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
  23315. * and the distance of this point from the begining of the path :
  23316. * ```javascript
  23317. * var scaleFunction = function(i, distance) {
  23318. * // do things
  23319. * return scaleValue;}
  23320. * ```
  23321. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23322. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23323. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23324. * 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
  23325. * 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
  23326. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23327. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23329. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23331. */
  23332. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  23333. var path = options.path;
  23334. var shape = options.shape;
  23335. var scaleFunction = options.scaleFunction || (function () { return 1; });
  23336. var rotationFunction = options.rotationFunction || (function () { return 0; });
  23337. var ribbonCloseArray = options.ribbonCloseArray || false;
  23338. var ribbonClosePath = options.ribbonClosePath || false;
  23339. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23340. var updatable = options.updatable;
  23341. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23342. var instance = options.instance;
  23343. var invertUV = options.invertUV || false;
  23344. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  23345. };
  23346. /**
  23347. * Creates lathe mesh.
  23348. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23349. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  23350. *
  23351. * 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
  23352. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23353. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23354. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23355. * 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.
  23356. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  23357. * 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
  23358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23360. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23362. */
  23363. MeshBuilder.CreateLathe = function (name, options, scene) {
  23364. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  23365. var closed = (options.closed === undefined) ? true : options.closed;
  23366. var shape = options.shape;
  23367. var radius = options.radius || 1;
  23368. var tessellation = options.tessellation || 64;
  23369. var updatable = options.updatable;
  23370. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23371. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23372. var pi2 = Math.PI * 2;
  23373. var paths = new Array();
  23374. var invertUV = options.invertUV || false;
  23375. var i = 0;
  23376. var p = 0;
  23377. var step = pi2 / tessellation * arc;
  23378. var rotated;
  23379. var path = new Array();
  23380. ;
  23381. for (i = 0; i <= tessellation; i++) {
  23382. var path = [];
  23383. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  23384. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  23385. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  23386. }
  23387. for (p = 0; p < shape.length; p++) {
  23388. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  23389. path.push(rotated);
  23390. }
  23391. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  23392. 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));
  23393. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  23394. }
  23395. paths.push(path);
  23396. }
  23397. // lathe ribbon
  23398. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  23399. return lathe;
  23400. };
  23401. /**
  23402. * Creates a plane mesh.
  23403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23404. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23405. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  23406. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  23407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23410. */
  23411. MeshBuilder.CreatePlane = function (name, options, scene) {
  23412. var plane = new BABYLON.Mesh(name, scene);
  23413. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23414. plane.sideOrientation = options.sideOrientation;
  23415. var vertexData = BABYLON.VertexData.CreatePlane(options);
  23416. vertexData.applyToMesh(plane, options.updatable);
  23417. if (options.sourcePlane) {
  23418. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  23419. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  23420. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  23421. plane.rotate(vectorProduct, product);
  23422. }
  23423. return plane;
  23424. };
  23425. /**
  23426. * Creates a ground mesh.
  23427. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23428. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23429. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23431. */
  23432. MeshBuilder.CreateGround = function (name, options, scene) {
  23433. var ground = new BABYLON.GroundMesh(name, scene);
  23434. ground._setReady(false);
  23435. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  23436. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  23437. ground._width = options.width || 1;
  23438. ground._height = options.height || 1;
  23439. ground._maxX = ground._width / 2;
  23440. ground._maxZ = ground._height / 2;
  23441. ground._minX = -ground._maxX;
  23442. ground._minZ = -ground._maxZ;
  23443. var vertexData = BABYLON.VertexData.CreateGround(options);
  23444. vertexData.applyToMesh(ground, options.updatable);
  23445. ground._setReady(true);
  23446. return ground;
  23447. };
  23448. /**
  23449. * Creates a tiled ground mesh.
  23450. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  23451. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23452. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23453. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23454. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23455. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23456. * numbers of subdivisions on the ground width and height of each tile.
  23457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23458. */
  23459. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  23460. var tiledGround = new BABYLON.Mesh(name, scene);
  23461. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  23462. vertexData.applyToMesh(tiledGround, options.updatable);
  23463. return tiledGround;
  23464. };
  23465. /**
  23466. * Creates a ground mesh from a height map.
  23467. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23468. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  23469. * The parameter `url` sets the URL of the height map image resource.
  23470. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23471. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23472. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23473. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23474. * 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).
  23475. * This function is passed the newly built mesh :
  23476. * ```javascript
  23477. * function(mesh) { // do things
  23478. * return; }
  23479. * ```
  23480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23481. */
  23482. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  23483. var width = options.width || 10.0;
  23484. var height = options.height || 10.0;
  23485. var subdivisions = options.subdivisions || 1 | 0;
  23486. var minHeight = options.minHeight || 0.0;
  23487. var maxHeight = options.maxHeight || 10.0;
  23488. var updatable = options.updatable;
  23489. var onReady = options.onReady;
  23490. var ground = new BABYLON.GroundMesh(name, scene);
  23491. ground._subdivisionsX = subdivisions;
  23492. ground._subdivisionsY = subdivisions;
  23493. ground._width = width;
  23494. ground._height = height;
  23495. ground._maxX = ground._width / 2.0;
  23496. ground._maxZ = ground._height / 2.0;
  23497. ground._minX = -ground._maxX;
  23498. ground._minZ = -ground._maxZ;
  23499. ground._setReady(false);
  23500. var onload = function (img) {
  23501. // Getting height map data
  23502. var canvas = document.createElement("canvas");
  23503. var context = canvas.getContext("2d");
  23504. var bufferWidth = img.width;
  23505. var bufferHeight = img.height;
  23506. canvas.width = bufferWidth;
  23507. canvas.height = bufferHeight;
  23508. context.drawImage(img, 0, 0);
  23509. // Create VertexData from map data
  23510. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23511. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  23512. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  23513. width: width, height: height,
  23514. subdivisions: subdivisions,
  23515. minHeight: minHeight, maxHeight: maxHeight,
  23516. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  23517. });
  23518. vertexData.applyToMesh(ground, updatable);
  23519. ground._setReady(true);
  23520. //execute ready callback, if set
  23521. if (onReady) {
  23522. onReady(ground);
  23523. }
  23524. };
  23525. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23526. return ground;
  23527. };
  23528. /**
  23529. * Creates a tube mesh.
  23530. * 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.
  23531. *
  23532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  23533. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23534. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23535. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23536. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23537. * 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.
  23538. * It must return a radius value (positive float) :
  23539. * ```javascript
  23540. * var radiusFunction = function(i, distance) {
  23541. * // do things
  23542. * return radius; }
  23543. * ```
  23544. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  23545. * 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
  23546. * 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
  23547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23548. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23549. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23551. */
  23552. MeshBuilder.CreateTube = function (name, options, scene) {
  23553. var path = options.path;
  23554. var radius = options.radius || 1.0;
  23555. var tessellation = options.tessellation || 64 | 0;
  23556. var radiusFunction = options.radiusFunction;
  23557. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23558. var invertUV = options.invertUV || false;
  23559. var updatable = options.updatable;
  23560. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23561. var instance = options.instance;
  23562. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  23563. // tube geometry
  23564. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  23565. var tangents = path3D.getTangents();
  23566. var normals = path3D.getNormals();
  23567. var distances = path3D.getDistances();
  23568. var pi2 = Math.PI * 2;
  23569. var step = pi2 / tessellation * arc;
  23570. var returnRadius = function () { return radius; };
  23571. var radiusFunctionFinal = radiusFunction || returnRadius;
  23572. var circlePath;
  23573. var rad;
  23574. var normal;
  23575. var rotated;
  23576. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23577. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23578. for (var i = 0; i < path.length; i++) {
  23579. rad = radiusFunctionFinal(i, distances[i]); // current radius
  23580. circlePath = Array(); // current circle array
  23581. normal = normals[i]; // current normal
  23582. for (var t = 0; t < tessellation; t++) {
  23583. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  23584. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  23585. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  23586. rotated.scaleInPlace(rad).addInPlace(path[i]);
  23587. circlePath[t] = rotated;
  23588. }
  23589. circlePaths[index] = circlePath;
  23590. index++;
  23591. }
  23592. // cap
  23593. var capPath = function (nbPoints, pathIndex) {
  23594. var pointCap = Array();
  23595. for (var i = 0; i < nbPoints; i++) {
  23596. pointCap.push(path[pathIndex]);
  23597. }
  23598. return pointCap;
  23599. };
  23600. switch (cap) {
  23601. case BABYLON.Mesh.NO_CAP:
  23602. break;
  23603. case BABYLON.Mesh.CAP_START:
  23604. circlePaths[0] = capPath(tessellation, 0);
  23605. circlePaths[1] = circlePaths[2].slice(0);
  23606. break;
  23607. case BABYLON.Mesh.CAP_END:
  23608. circlePaths[index] = circlePaths[index - 1].slice(0);
  23609. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23610. break;
  23611. case BABYLON.Mesh.CAP_ALL:
  23612. circlePaths[0] = capPath(tessellation, 0);
  23613. circlePaths[1] = circlePaths[2].slice(0);
  23614. circlePaths[index] = circlePaths[index - 1].slice(0);
  23615. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23616. break;
  23617. default:
  23618. break;
  23619. }
  23620. return circlePaths;
  23621. };
  23622. var path3D;
  23623. var pathArray;
  23624. if (instance) {
  23625. var arc = options.arc || instance.arc;
  23626. path3D = (instance.path3D).update(path);
  23627. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23628. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23629. instance.path3D = path3D;
  23630. instance.pathArray = pathArray;
  23631. instance.arc = arc;
  23632. return instance;
  23633. }
  23634. // tube creation
  23635. path3D = new BABYLON.Path3D(path);
  23636. var newPathArray = new Array();
  23637. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23638. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23639. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23640. tube.pathArray = pathArray;
  23641. tube.path3D = path3D;
  23642. tube.tessellation = tessellation;
  23643. tube.cap = cap;
  23644. tube.arc = options.arc;
  23645. return tube;
  23646. };
  23647. /**
  23648. * Creates a polyhedron mesh.
  23649. *
  23650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23651. * 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
  23652. * to choose the wanted type.
  23653. * The parameter `size` (positive float, default 1) sets the polygon size.
  23654. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23655. * 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`.
  23656. * 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
  23657. * 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)`).
  23658. * 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
  23659. * 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.
  23660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23663. */
  23664. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23665. var polyhedron = new BABYLON.Mesh(name, scene);
  23666. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23667. polyhedron.sideOrientation = options.sideOrientation;
  23668. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23669. vertexData.applyToMesh(polyhedron, options.updatable);
  23670. return polyhedron;
  23671. };
  23672. /**
  23673. * Creates a decal mesh.
  23674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23675. * 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.
  23676. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23677. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23678. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23679. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23680. */
  23681. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23682. var indices = sourceMesh.getIndices();
  23683. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23684. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23685. var position = options.position || BABYLON.Vector3.Zero();
  23686. var normal = options.normal || BABYLON.Vector3.Up();
  23687. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23688. var angle = options.angle || 0;
  23689. // Getting correct rotation
  23690. if (!normal) {
  23691. var target = new BABYLON.Vector3(0, 0, 1);
  23692. var camera = sourceMesh.getScene().activeCamera;
  23693. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23694. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23695. }
  23696. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23697. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23698. var pitch = Math.atan2(normal.y, len);
  23699. // Matrix
  23700. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23701. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23702. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23703. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23704. var vertexData = new BABYLON.VertexData();
  23705. vertexData.indices = [];
  23706. vertexData.positions = [];
  23707. vertexData.normals = [];
  23708. vertexData.uvs = [];
  23709. var currentVertexDataIndex = 0;
  23710. var extractDecalVector3 = function (indexId) {
  23711. var vertexId = indices[indexId];
  23712. var result = new BABYLON.PositionNormalVertex();
  23713. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23714. // Send vector to decal local world
  23715. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23716. // Get normal
  23717. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23718. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  23719. return result;
  23720. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23721. var clip = function (vertices, axis) {
  23722. if (vertices.length === 0) {
  23723. return vertices;
  23724. }
  23725. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23726. var clipVertices = function (v0, v1) {
  23727. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23728. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23729. };
  23730. var result = new Array();
  23731. for (var index = 0; index < vertices.length; index += 3) {
  23732. var v1Out;
  23733. var v2Out;
  23734. var v3Out;
  23735. var total = 0;
  23736. var nV1, nV2, nV3, nV4;
  23737. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23738. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23739. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23740. v1Out = d1 > 0;
  23741. v2Out = d2 > 0;
  23742. v3Out = d3 > 0;
  23743. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23744. switch (total) {
  23745. case 0:
  23746. result.push(vertices[index]);
  23747. result.push(vertices[index + 1]);
  23748. result.push(vertices[index + 2]);
  23749. break;
  23750. case 1:
  23751. if (v1Out) {
  23752. nV1 = vertices[index + 1];
  23753. nV2 = vertices[index + 2];
  23754. nV3 = clipVertices(vertices[index], nV1);
  23755. nV4 = clipVertices(vertices[index], nV2);
  23756. }
  23757. if (v2Out) {
  23758. nV1 = vertices[index];
  23759. nV2 = vertices[index + 2];
  23760. nV3 = clipVertices(vertices[index + 1], nV1);
  23761. nV4 = clipVertices(vertices[index + 1], nV2);
  23762. result.push(nV3);
  23763. result.push(nV2.clone());
  23764. result.push(nV1.clone());
  23765. result.push(nV2.clone());
  23766. result.push(nV3.clone());
  23767. result.push(nV4);
  23768. break;
  23769. }
  23770. if (v3Out) {
  23771. nV1 = vertices[index];
  23772. nV2 = vertices[index + 1];
  23773. nV3 = clipVertices(vertices[index + 2], nV1);
  23774. nV4 = clipVertices(vertices[index + 2], nV2);
  23775. }
  23776. result.push(nV1.clone());
  23777. result.push(nV2.clone());
  23778. result.push(nV3);
  23779. result.push(nV4);
  23780. result.push(nV3.clone());
  23781. result.push(nV2.clone());
  23782. break;
  23783. case 2:
  23784. if (!v1Out) {
  23785. nV1 = vertices[index].clone();
  23786. nV2 = clipVertices(nV1, vertices[index + 1]);
  23787. nV3 = clipVertices(nV1, vertices[index + 2]);
  23788. result.push(nV1);
  23789. result.push(nV2);
  23790. result.push(nV3);
  23791. }
  23792. if (!v2Out) {
  23793. nV1 = vertices[index + 1].clone();
  23794. nV2 = clipVertices(nV1, vertices[index + 2]);
  23795. nV3 = clipVertices(nV1, vertices[index]);
  23796. result.push(nV1);
  23797. result.push(nV2);
  23798. result.push(nV3);
  23799. }
  23800. if (!v3Out) {
  23801. nV1 = vertices[index + 2].clone();
  23802. nV2 = clipVertices(nV1, vertices[index]);
  23803. nV3 = clipVertices(nV1, vertices[index + 1]);
  23804. result.push(nV1);
  23805. result.push(nV2);
  23806. result.push(nV3);
  23807. }
  23808. break;
  23809. case 3:
  23810. break;
  23811. }
  23812. }
  23813. return result;
  23814. };
  23815. for (var index = 0; index < indices.length; index += 3) {
  23816. var faceVertices = new Array();
  23817. faceVertices.push(extractDecalVector3(index));
  23818. faceVertices.push(extractDecalVector3(index + 1));
  23819. faceVertices.push(extractDecalVector3(index + 2));
  23820. // Clip
  23821. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23822. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23823. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23824. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23825. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23826. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23827. if (faceVertices.length === 0) {
  23828. continue;
  23829. }
  23830. // Add UVs and get back to world
  23831. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23832. var vertex = faceVertices[vIndex];
  23833. //TODO check for Int32Array | Uint32Array | Uint16Array
  23834. vertexData.indices.push(currentVertexDataIndex);
  23835. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23836. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23837. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23838. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23839. currentVertexDataIndex++;
  23840. }
  23841. }
  23842. // Return mesh
  23843. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23844. vertexData.applyToMesh(decal);
  23845. decal.position = position.clone();
  23846. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23847. return decal;
  23848. };
  23849. // Privates
  23850. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23851. // extrusion geometry
  23852. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23853. var tangents = path3D.getTangents();
  23854. var normals = path3D.getNormals();
  23855. var binormals = path3D.getBinormals();
  23856. var distances = path3D.getDistances();
  23857. var angle = 0;
  23858. var returnScale = function () { return scale; };
  23859. var returnRotation = function () { return rotation; };
  23860. var rotate = custom ? rotateFunction : returnRotation;
  23861. var scl = custom ? scaleFunction : returnScale;
  23862. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23863. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23864. for (var i = 0; i < curve.length; i++) {
  23865. var shapePath = new Array();
  23866. var angleStep = rotate(i, distances[i]);
  23867. var scaleRatio = scl(i, distances[i]);
  23868. for (var p = 0; p < shape.length; p++) {
  23869. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23870. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23871. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23872. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23873. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23874. shapePath[p] = rotated;
  23875. }
  23876. shapePaths[index] = shapePath;
  23877. angle += angleStep;
  23878. index++;
  23879. }
  23880. // cap
  23881. var capPath = function (shapePath) {
  23882. var pointCap = Array();
  23883. var barycenter = BABYLON.Vector3.Zero();
  23884. var i;
  23885. for (i = 0; i < shapePath.length; i++) {
  23886. barycenter.addInPlace(shapePath[i]);
  23887. }
  23888. barycenter.scaleInPlace(1.0 / shapePath.length);
  23889. for (i = 0; i < shapePath.length; i++) {
  23890. pointCap.push(barycenter);
  23891. }
  23892. return pointCap;
  23893. };
  23894. switch (cap) {
  23895. case BABYLON.Mesh.NO_CAP:
  23896. break;
  23897. case BABYLON.Mesh.CAP_START:
  23898. shapePaths[0] = capPath(shapePaths[2]);
  23899. shapePaths[1] = shapePaths[2];
  23900. break;
  23901. case BABYLON.Mesh.CAP_END:
  23902. shapePaths[index] = shapePaths[index - 1];
  23903. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23904. break;
  23905. case BABYLON.Mesh.CAP_ALL:
  23906. shapePaths[0] = capPath(shapePaths[2]);
  23907. shapePaths[1] = shapePaths[2];
  23908. shapePaths[index] = shapePaths[index - 1];
  23909. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23910. break;
  23911. default:
  23912. break;
  23913. }
  23914. return shapePaths;
  23915. };
  23916. var path3D;
  23917. var pathArray;
  23918. if (instance) {
  23919. path3D = (instance.path3D).update(curve);
  23920. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23921. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23922. return instance;
  23923. }
  23924. // extruded shape creation
  23925. path3D = new BABYLON.Path3D(curve);
  23926. var newShapePaths = new Array();
  23927. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23928. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23929. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23930. extrudedGeneric.pathArray = pathArray;
  23931. extrudedGeneric.path3D = path3D;
  23932. extrudedGeneric.cap = cap;
  23933. return extrudedGeneric;
  23934. };
  23935. return MeshBuilder;
  23936. }());
  23937. BABYLON.MeshBuilder = MeshBuilder;
  23938. })(BABYLON || (BABYLON = {}));
  23939. //# sourceMappingURL=babylon.meshBuilder.js.map
  23940. var BABYLON;
  23941. (function (BABYLON) {
  23942. var BaseTexture = (function () {
  23943. function BaseTexture(scene) {
  23944. this.hasAlpha = false;
  23945. this.getAlphaFromRGB = false;
  23946. this.level = 1;
  23947. this.coordinatesIndex = 0;
  23948. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23949. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23950. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23951. this.anisotropicFilteringLevel = 4;
  23952. this.isCube = false;
  23953. this.isRenderTarget = false;
  23954. this.animations = new Array();
  23955. /**
  23956. * An event triggered when the texture is disposed.
  23957. * @type {BABYLON.Observable}
  23958. */
  23959. this.onDisposeObservable = new BABYLON.Observable();
  23960. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23961. this._scene = scene;
  23962. this._scene.textures.push(this);
  23963. this._uid = null;
  23964. }
  23965. Object.defineProperty(BaseTexture.prototype, "uid", {
  23966. get: function () {
  23967. if (!this._uid) {
  23968. this._uid = BABYLON.Tools.RandomId();
  23969. }
  23970. return this._uid;
  23971. },
  23972. enumerable: true,
  23973. configurable: true
  23974. });
  23975. BaseTexture.prototype.toString = function () {
  23976. return this.name;
  23977. };
  23978. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23979. set: function (callback) {
  23980. if (this._onDisposeObserver) {
  23981. this.onDisposeObservable.remove(this._onDisposeObserver);
  23982. }
  23983. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23984. },
  23985. enumerable: true,
  23986. configurable: true
  23987. });
  23988. BaseTexture.prototype.getScene = function () {
  23989. return this._scene;
  23990. };
  23991. BaseTexture.prototype.getTextureMatrix = function () {
  23992. return null;
  23993. };
  23994. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23995. return null;
  23996. };
  23997. BaseTexture.prototype.getInternalTexture = function () {
  23998. return this._texture;
  23999. };
  24000. BaseTexture.prototype.isReady = function () {
  24001. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24002. return true;
  24003. }
  24004. if (this._texture) {
  24005. return this._texture.isReady;
  24006. }
  24007. return false;
  24008. };
  24009. BaseTexture.prototype.getSize = function () {
  24010. if (this._texture._width) {
  24011. return new BABYLON.Size(this._texture._width, this._texture._height);
  24012. }
  24013. if (this._texture._size) {
  24014. return new BABYLON.Size(this._texture._size, this._texture._size);
  24015. }
  24016. return BABYLON.Size.Zero();
  24017. };
  24018. BaseTexture.prototype.getBaseSize = function () {
  24019. if (!this.isReady() || !this._texture)
  24020. return BABYLON.Size.Zero();
  24021. if (this._texture._size) {
  24022. return new BABYLON.Size(this._texture._size, this._texture._size);
  24023. }
  24024. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  24025. };
  24026. BaseTexture.prototype.scale = function (ratio) {
  24027. };
  24028. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24029. get: function () {
  24030. return false;
  24031. },
  24032. enumerable: true,
  24033. configurable: true
  24034. });
  24035. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  24036. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24037. for (var index = 0; index < texturesCache.length; index++) {
  24038. var texturesCacheEntry = texturesCache[index];
  24039. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24040. texturesCache.splice(index, 1);
  24041. return;
  24042. }
  24043. }
  24044. };
  24045. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24046. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24047. for (var index = 0; index < texturesCache.length; index++) {
  24048. var texturesCacheEntry = texturesCache[index];
  24049. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24050. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24051. texturesCacheEntry.references++;
  24052. return texturesCacheEntry;
  24053. }
  24054. }
  24055. }
  24056. return null;
  24057. };
  24058. BaseTexture.prototype.delayLoad = function () {
  24059. };
  24060. BaseTexture.prototype.clone = function () {
  24061. return null;
  24062. };
  24063. BaseTexture.prototype.releaseInternalTexture = function () {
  24064. if (this._texture) {
  24065. this._scene.getEngine().releaseInternalTexture(this._texture);
  24066. delete this._texture;
  24067. }
  24068. };
  24069. BaseTexture.prototype.dispose = function () {
  24070. // Animations
  24071. this.getScene().stopAnimation(this);
  24072. // Remove from scene
  24073. var index = this._scene.textures.indexOf(this);
  24074. if (index >= 0) {
  24075. this._scene.textures.splice(index, 1);
  24076. }
  24077. if (this._texture === undefined) {
  24078. return;
  24079. }
  24080. // Release
  24081. this.releaseInternalTexture();
  24082. // Callback
  24083. this.onDisposeObservable.notifyObservers(this);
  24084. this.onDisposeObservable.clear();
  24085. };
  24086. BaseTexture.prototype.serialize = function () {
  24087. if (!this.name) {
  24088. return null;
  24089. }
  24090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24091. // Animations
  24092. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24093. return serializationObject;
  24094. };
  24095. return BaseTexture;
  24096. }());
  24097. __decorate([
  24098. BABYLON.serialize()
  24099. ], BaseTexture.prototype, "name", void 0);
  24100. __decorate([
  24101. BABYLON.serialize()
  24102. ], BaseTexture.prototype, "hasAlpha", void 0);
  24103. __decorate([
  24104. BABYLON.serialize()
  24105. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24106. __decorate([
  24107. BABYLON.serialize()
  24108. ], BaseTexture.prototype, "level", void 0);
  24109. __decorate([
  24110. BABYLON.serialize()
  24111. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24112. __decorate([
  24113. BABYLON.serialize()
  24114. ], BaseTexture.prototype, "coordinatesMode", void 0);
  24115. __decorate([
  24116. BABYLON.serialize()
  24117. ], BaseTexture.prototype, "wrapU", void 0);
  24118. __decorate([
  24119. BABYLON.serialize()
  24120. ], BaseTexture.prototype, "wrapV", void 0);
  24121. __decorate([
  24122. BABYLON.serialize()
  24123. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24124. __decorate([
  24125. BABYLON.serialize()
  24126. ], BaseTexture.prototype, "isCube", void 0);
  24127. __decorate([
  24128. BABYLON.serialize()
  24129. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24130. BABYLON.BaseTexture = BaseTexture;
  24131. })(BABYLON || (BABYLON = {}));
  24132. //# sourceMappingURL=babylon.baseTexture.js.map
  24133. var BABYLON;
  24134. (function (BABYLON) {
  24135. var Texture = (function (_super) {
  24136. __extends(Texture, _super);
  24137. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  24138. if (noMipmap === void 0) { noMipmap = false; }
  24139. if (invertY === void 0) { invertY = true; }
  24140. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24141. if (onLoad === void 0) { onLoad = null; }
  24142. if (onError === void 0) { onError = null; }
  24143. if (buffer === void 0) { buffer = null; }
  24144. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24145. var _this = _super.call(this, scene) || this;
  24146. _this.uOffset = 0;
  24147. _this.vOffset = 0;
  24148. _this.uScale = 1.0;
  24149. _this.vScale = 1.0;
  24150. _this.uAng = 0;
  24151. _this.vAng = 0;
  24152. _this.wAng = 0;
  24153. _this.name = url;
  24154. _this.url = url;
  24155. _this._noMipmap = noMipmap;
  24156. _this._invertY = invertY;
  24157. _this._samplingMode = samplingMode;
  24158. _this._buffer = buffer;
  24159. _this._deleteBuffer = deleteBuffer;
  24160. if (!url) {
  24161. return _this;
  24162. }
  24163. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  24164. var load = function () {
  24165. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  24166. _this.onLoadObservable.notifyObservers(true);
  24167. }
  24168. if (onLoad) {
  24169. onLoad();
  24170. }
  24171. };
  24172. if (!_this._texture) {
  24173. if (!scene.useDelayedTextureLoading) {
  24174. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  24175. if (deleteBuffer) {
  24176. delete _this._buffer;
  24177. }
  24178. }
  24179. else {
  24180. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24181. _this._delayedOnLoad = load;
  24182. _this._delayedOnError = onError;
  24183. }
  24184. }
  24185. else {
  24186. if (_this._texture.isReady) {
  24187. BABYLON.Tools.SetImmediate(function () { return load(); });
  24188. }
  24189. else {
  24190. _this._texture.onLoadedCallbacks.push(load);
  24191. }
  24192. }
  24193. return _this;
  24194. }
  24195. Object.defineProperty(Texture.prototype, "noMipmap", {
  24196. get: function () {
  24197. return this._noMipmap;
  24198. },
  24199. enumerable: true,
  24200. configurable: true
  24201. });
  24202. Texture.prototype.delayLoad = function () {
  24203. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24204. return;
  24205. }
  24206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24207. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24208. if (!this._texture) {
  24209. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  24210. if (this._deleteBuffer) {
  24211. delete this._buffer;
  24212. }
  24213. }
  24214. };
  24215. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24216. if (!this._texture) {
  24217. return;
  24218. }
  24219. this._samplingMode = samplingMode;
  24220. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24221. };
  24222. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24223. x *= this.uScale;
  24224. y *= this.vScale;
  24225. x -= 0.5 * this.uScale;
  24226. y -= 0.5 * this.vScale;
  24227. z -= 0.5;
  24228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24229. t.x += 0.5 * this.uScale + this.uOffset;
  24230. t.y += 0.5 * this.vScale + this.vOffset;
  24231. t.z += 0.5;
  24232. };
  24233. Texture.prototype.getTextureMatrix = function () {
  24234. if (this.uOffset === this._cachedUOffset &&
  24235. this.vOffset === this._cachedVOffset &&
  24236. this.uScale === this._cachedUScale &&
  24237. this.vScale === this._cachedVScale &&
  24238. this.uAng === this._cachedUAng &&
  24239. this.vAng === this._cachedVAng &&
  24240. this.wAng === this._cachedWAng) {
  24241. return this._cachedTextureMatrix;
  24242. }
  24243. this._cachedUOffset = this.uOffset;
  24244. this._cachedVOffset = this.vOffset;
  24245. this._cachedUScale = this.uScale;
  24246. this._cachedVScale = this.vScale;
  24247. this._cachedUAng = this.uAng;
  24248. this._cachedVAng = this.vAng;
  24249. this._cachedWAng = this.wAng;
  24250. if (!this._cachedTextureMatrix) {
  24251. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24252. this._rowGenerationMatrix = new BABYLON.Matrix();
  24253. this._t0 = BABYLON.Vector3.Zero();
  24254. this._t1 = BABYLON.Vector3.Zero();
  24255. this._t2 = BABYLON.Vector3.Zero();
  24256. }
  24257. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24258. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24259. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24260. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24261. this._t1.subtractInPlace(this._t0);
  24262. this._t2.subtractInPlace(this._t0);
  24263. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24264. this._cachedTextureMatrix.m[0] = this._t1.x;
  24265. this._cachedTextureMatrix.m[1] = this._t1.y;
  24266. this._cachedTextureMatrix.m[2] = this._t1.z;
  24267. this._cachedTextureMatrix.m[4] = this._t2.x;
  24268. this._cachedTextureMatrix.m[5] = this._t2.y;
  24269. this._cachedTextureMatrix.m[6] = this._t2.z;
  24270. this._cachedTextureMatrix.m[8] = this._t0.x;
  24271. this._cachedTextureMatrix.m[9] = this._t0.y;
  24272. this._cachedTextureMatrix.m[10] = this._t0.z;
  24273. return this._cachedTextureMatrix;
  24274. };
  24275. Texture.prototype.getReflectionTextureMatrix = function () {
  24276. if (this.uOffset === this._cachedUOffset &&
  24277. this.vOffset === this._cachedVOffset &&
  24278. this.uScale === this._cachedUScale &&
  24279. this.vScale === this._cachedVScale &&
  24280. this.coordinatesMode === this._cachedCoordinatesMode) {
  24281. return this._cachedTextureMatrix;
  24282. }
  24283. if (!this._cachedTextureMatrix) {
  24284. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24285. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24286. }
  24287. this._cachedCoordinatesMode = this.coordinatesMode;
  24288. switch (this.coordinatesMode) {
  24289. case Texture.PLANAR_MODE:
  24290. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24291. this._cachedTextureMatrix[0] = this.uScale;
  24292. this._cachedTextureMatrix[5] = this.vScale;
  24293. this._cachedTextureMatrix[12] = this.uOffset;
  24294. this._cachedTextureMatrix[13] = this.vOffset;
  24295. break;
  24296. case Texture.PROJECTION_MODE:
  24297. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24298. this._projectionModeMatrix.m[0] = 0.5;
  24299. this._projectionModeMatrix.m[5] = -0.5;
  24300. this._projectionModeMatrix.m[10] = 0.0;
  24301. this._projectionModeMatrix.m[12] = 0.5;
  24302. this._projectionModeMatrix.m[13] = 0.5;
  24303. this._projectionModeMatrix.m[14] = 1.0;
  24304. this._projectionModeMatrix.m[15] = 1.0;
  24305. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24306. break;
  24307. default:
  24308. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24309. break;
  24310. }
  24311. return this._cachedTextureMatrix;
  24312. };
  24313. Texture.prototype.clone = function () {
  24314. var _this = this;
  24315. return BABYLON.SerializationHelper.Clone(function () {
  24316. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24317. }, this);
  24318. };
  24319. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24320. get: function () {
  24321. if (!this._onLoadObservarble) {
  24322. this._onLoadObservarble = new BABYLON.Observable();
  24323. }
  24324. return this._onLoadObservarble;
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. // Statics
  24330. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  24331. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24332. if (onLoad === void 0) { onLoad = null; }
  24333. if (onError === void 0) { onError = null; }
  24334. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  24335. };
  24336. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24337. if (parsedTexture.customType) {
  24338. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24339. return customTexture.Parse(parsedTexture, scene, rootUrl);
  24340. }
  24341. if (parsedTexture.isCube) {
  24342. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24343. }
  24344. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24345. return null;
  24346. }
  24347. var texture = BABYLON.SerializationHelper.Parse(function () {
  24348. if (parsedTexture.mirrorPlane) {
  24349. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24350. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24351. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24352. return mirrorTexture;
  24353. }
  24354. else if (parsedTexture.isRenderTarget) {
  24355. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24356. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24357. return renderTargetTexture;
  24358. }
  24359. else {
  24360. var texture;
  24361. if (parsedTexture.base64String) {
  24362. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  24363. }
  24364. else {
  24365. texture = new Texture(rootUrl + parsedTexture.name, scene);
  24366. }
  24367. return texture;
  24368. }
  24369. }, parsedTexture, scene);
  24370. // Animations
  24371. if (parsedTexture.animations) {
  24372. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24373. var parsedAnimation = parsedTexture.animations[animationIndex];
  24374. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24375. }
  24376. }
  24377. return texture;
  24378. };
  24379. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  24380. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24381. if (noMipmap === void 0) { noMipmap = false; }
  24382. if (invertY === void 0) { invertY = true; }
  24383. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24384. if (onLoad === void 0) { onLoad = null; }
  24385. if (onError === void 0) { onError = null; }
  24386. if (name.substr(0, 5) !== "data:") {
  24387. name = "data:" + name;
  24388. }
  24389. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  24390. };
  24391. return Texture;
  24392. }(BABYLON.BaseTexture));
  24393. // Constants
  24394. Texture.NEAREST_SAMPLINGMODE = 1;
  24395. Texture.BILINEAR_SAMPLINGMODE = 2;
  24396. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24397. Texture.EXPLICIT_MODE = 0;
  24398. Texture.SPHERICAL_MODE = 1;
  24399. Texture.PLANAR_MODE = 2;
  24400. Texture.CUBIC_MODE = 3;
  24401. Texture.PROJECTION_MODE = 4;
  24402. Texture.SKYBOX_MODE = 5;
  24403. Texture.INVCUBIC_MODE = 6;
  24404. Texture.EQUIRECTANGULAR_MODE = 7;
  24405. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24406. Texture.CLAMP_ADDRESSMODE = 0;
  24407. Texture.WRAP_ADDRESSMODE = 1;
  24408. Texture.MIRROR_ADDRESSMODE = 2;
  24409. __decorate([
  24410. BABYLON.serialize()
  24411. ], Texture.prototype, "url", void 0);
  24412. __decorate([
  24413. BABYLON.serialize()
  24414. ], Texture.prototype, "uOffset", void 0);
  24415. __decorate([
  24416. BABYLON.serialize()
  24417. ], Texture.prototype, "vOffset", void 0);
  24418. __decorate([
  24419. BABYLON.serialize()
  24420. ], Texture.prototype, "uScale", void 0);
  24421. __decorate([
  24422. BABYLON.serialize()
  24423. ], Texture.prototype, "vScale", void 0);
  24424. __decorate([
  24425. BABYLON.serialize()
  24426. ], Texture.prototype, "uAng", void 0);
  24427. __decorate([
  24428. BABYLON.serialize()
  24429. ], Texture.prototype, "vAng", void 0);
  24430. __decorate([
  24431. BABYLON.serialize()
  24432. ], Texture.prototype, "wAng", void 0);
  24433. BABYLON.Texture = Texture;
  24434. })(BABYLON || (BABYLON = {}));
  24435. //# sourceMappingURL=babylon.texture.js.map
  24436. var BABYLON;
  24437. (function (BABYLON) {
  24438. var CubeTexture = (function (_super) {
  24439. __extends(CubeTexture, _super);
  24440. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  24441. if (onLoad === void 0) { onLoad = null; }
  24442. if (onError === void 0) { onError = null; }
  24443. var _this = _super.call(this, scene) || this;
  24444. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  24445. _this.name = rootUrl;
  24446. _this.url = rootUrl;
  24447. _this._noMipmap = noMipmap;
  24448. _this.hasAlpha = false;
  24449. if (!rootUrl && !files) {
  24450. return _this;
  24451. }
  24452. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  24453. if (!files) {
  24454. if (!extensions) {
  24455. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  24456. }
  24457. files = [];
  24458. for (var index = 0; index < extensions.length; index++) {
  24459. files.push(rootUrl + extensions[index]);
  24460. }
  24461. _this._extensions = extensions;
  24462. }
  24463. _this._files = files;
  24464. if (!_this._texture) {
  24465. if (!scene.useDelayedTextureLoading) {
  24466. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  24467. }
  24468. else {
  24469. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24470. }
  24471. }
  24472. else if (onLoad) {
  24473. if (_this._texture.isReady) {
  24474. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  24475. }
  24476. else {
  24477. _this._texture.onLoadedCallbacks.push(onLoad);
  24478. }
  24479. }
  24480. _this.isCube = true;
  24481. _this._textureMatrix = BABYLON.Matrix.Identity();
  24482. return _this;
  24483. }
  24484. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  24485. return new CubeTexture("", scene, null, noMipmap, files);
  24486. };
  24487. // Methods
  24488. CubeTexture.prototype.delayLoad = function () {
  24489. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24490. return;
  24491. }
  24492. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24493. this._texture = this._getFromCache(this.url, this._noMipmap);
  24494. if (!this._texture) {
  24495. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  24496. }
  24497. };
  24498. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  24499. return this._textureMatrix;
  24500. };
  24501. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  24502. var texture = BABYLON.SerializationHelper.Parse(function () {
  24503. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  24504. }, parsedTexture, scene);
  24505. // Animations
  24506. if (parsedTexture.animations) {
  24507. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24508. var parsedAnimation = parsedTexture.animations[animationIndex];
  24509. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24510. }
  24511. }
  24512. return texture;
  24513. };
  24514. CubeTexture.prototype.clone = function () {
  24515. var _this = this;
  24516. return BABYLON.SerializationHelper.Clone(function () {
  24517. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  24518. }, this);
  24519. };
  24520. return CubeTexture;
  24521. }(BABYLON.BaseTexture));
  24522. BABYLON.CubeTexture = CubeTexture;
  24523. })(BABYLON || (BABYLON = {}));
  24524. //# sourceMappingURL=babylon.cubeTexture.js.map
  24525. var BABYLON;
  24526. (function (BABYLON) {
  24527. var RenderTargetTexture = (function (_super) {
  24528. __extends(RenderTargetTexture, _super);
  24529. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  24530. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  24531. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24532. if (isCube === void 0) { isCube = false; }
  24533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24534. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24535. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  24536. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24537. _this.isCube = isCube;
  24538. /**
  24539. * Use this list to define the list of mesh you want to render.
  24540. */
  24541. _this.renderList = new Array();
  24542. _this.renderParticles = true;
  24543. _this.renderSprites = false;
  24544. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  24545. // Events
  24546. /**
  24547. * An event triggered when the texture is unbind.
  24548. * @type {BABYLON.Observable}
  24549. */
  24550. _this.onAfterUnbindObservable = new BABYLON.Observable();
  24551. /**
  24552. * An event triggered before rendering the texture
  24553. * @type {BABYLON.Observable}
  24554. */
  24555. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24556. /**
  24557. * An event triggered after rendering the texture
  24558. * @type {BABYLON.Observable}
  24559. */
  24560. _this.onAfterRenderObservable = new BABYLON.Observable();
  24561. /**
  24562. * An event triggered after the texture clear
  24563. * @type {BABYLON.Observable}
  24564. */
  24565. _this.onClearObservable = new BABYLON.Observable();
  24566. _this._currentRefreshId = -1;
  24567. _this._refreshRate = 1;
  24568. _this.name = name;
  24569. _this.isRenderTarget = true;
  24570. _this._size = size;
  24571. _this._generateMipMaps = generateMipMaps;
  24572. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  24573. _this._renderTargetOptions = {
  24574. generateMipMaps: generateMipMaps,
  24575. type: type,
  24576. samplingMode: samplingMode,
  24577. generateDepthBuffer: generateDepthBuffer,
  24578. generateStencilBuffer: generateStencilBuffer
  24579. };
  24580. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  24581. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24582. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24583. }
  24584. if (isCube) {
  24585. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  24586. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  24587. _this._textureMatrix = BABYLON.Matrix.Identity();
  24588. }
  24589. else {
  24590. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  24591. }
  24592. // Rendering groups
  24593. _this._renderingManager = new BABYLON.RenderingManager(scene);
  24594. return _this;
  24595. }
  24596. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  24597. get: function () {
  24598. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  24599. },
  24600. enumerable: true,
  24601. configurable: true
  24602. });
  24603. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  24604. get: function () {
  24605. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  24606. },
  24607. enumerable: true,
  24608. configurable: true
  24609. });
  24610. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  24611. get: function () {
  24612. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  24613. },
  24614. enumerable: true,
  24615. configurable: true
  24616. });
  24617. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  24618. set: function (callback) {
  24619. if (this._onAfterUnbindObserver) {
  24620. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  24621. }
  24622. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  24623. },
  24624. enumerable: true,
  24625. configurable: true
  24626. });
  24627. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24628. set: function (callback) {
  24629. if (this._onBeforeRenderObserver) {
  24630. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24631. }
  24632. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24633. },
  24634. enumerable: true,
  24635. configurable: true
  24636. });
  24637. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24638. set: function (callback) {
  24639. if (this._onAfterRenderObserver) {
  24640. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24641. }
  24642. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24643. },
  24644. enumerable: true,
  24645. configurable: true
  24646. });
  24647. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24648. set: function (callback) {
  24649. if (this._onClearObserver) {
  24650. this.onClearObservable.remove(this._onClearObserver);
  24651. }
  24652. this._onClearObserver = this.onClearObservable.add(callback);
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24658. this._currentRefreshId = -1;
  24659. };
  24660. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24661. get: function () {
  24662. return this._refreshRate;
  24663. },
  24664. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24665. set: function (value) {
  24666. this._refreshRate = value;
  24667. this.resetRefreshCounter();
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. RenderTargetTexture.prototype._shouldRender = function () {
  24673. if (this._currentRefreshId === -1) {
  24674. this._currentRefreshId = 1;
  24675. return true;
  24676. }
  24677. if (this.refreshRate === this._currentRefreshId) {
  24678. this._currentRefreshId = 1;
  24679. return true;
  24680. }
  24681. this._currentRefreshId++;
  24682. return false;
  24683. };
  24684. RenderTargetTexture.prototype.isReady = function () {
  24685. if (!this.getScene().renderTargetsEnabled) {
  24686. return false;
  24687. }
  24688. return _super.prototype.isReady.call(this);
  24689. };
  24690. RenderTargetTexture.prototype.getRenderSize = function () {
  24691. return this._size;
  24692. };
  24693. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24694. get: function () {
  24695. return true;
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. RenderTargetTexture.prototype.scale = function (ratio) {
  24701. var newSize = this._size * ratio;
  24702. this.resize(newSize);
  24703. };
  24704. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24705. if (this.isCube) {
  24706. return this._textureMatrix;
  24707. }
  24708. return _super.prototype.getReflectionTextureMatrix.call(this);
  24709. };
  24710. RenderTargetTexture.prototype.resize = function (size) {
  24711. this.releaseInternalTexture();
  24712. if (this.isCube) {
  24713. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24714. }
  24715. else {
  24716. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24717. }
  24718. };
  24719. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24720. var scene = this.getScene();
  24721. var engine = scene.getEngine();
  24722. if (this.useCameraPostProcesses !== undefined) {
  24723. useCameraPostProcess = this.useCameraPostProcesses;
  24724. }
  24725. if (this._waitingRenderList) {
  24726. this.renderList = [];
  24727. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24728. var id = this._waitingRenderList[index];
  24729. this.renderList.push(scene.getMeshByID(id));
  24730. }
  24731. delete this._waitingRenderList;
  24732. }
  24733. // Is predicate defined?
  24734. if (this.renderListPredicate) {
  24735. this.renderList.splice(0); // Clear previous renderList
  24736. var sceneMeshes = this.getScene().meshes;
  24737. for (var index = 0; index < sceneMeshes.length; index++) {
  24738. var mesh = sceneMeshes[index];
  24739. if (this.renderListPredicate(mesh)) {
  24740. this.renderList.push(mesh);
  24741. }
  24742. }
  24743. }
  24744. if (this.renderList && this.renderList.length === 0) {
  24745. return;
  24746. }
  24747. // Set custom projection.
  24748. // Needs to be before binding to prevent changing the aspect ratio.
  24749. if (this.activeCamera) {
  24750. engine.setViewport(this.activeCamera.viewport);
  24751. if (this.activeCamera !== scene.activeCamera) {
  24752. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24753. }
  24754. }
  24755. else {
  24756. engine.setViewport(scene.activeCamera.viewport);
  24757. }
  24758. // Prepare renderingManager
  24759. this._renderingManager.reset();
  24760. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24761. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24762. var sceneRenderId = scene.getRenderId();
  24763. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24764. var mesh = currentRenderList[meshIndex];
  24765. if (mesh) {
  24766. if (!mesh.isReady()) {
  24767. // Reset _currentRefreshId
  24768. this.resetRefreshCounter();
  24769. continue;
  24770. }
  24771. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24772. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24773. mesh._activate(sceneRenderId);
  24774. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24775. var subMesh = mesh.subMeshes[subIndex];
  24776. scene._activeIndices.addCount(subMesh.indexCount, false);
  24777. this._renderingManager.dispatch(subMesh);
  24778. }
  24779. }
  24780. }
  24781. }
  24782. if (this.isCube) {
  24783. for (var face = 0; face < 6; face++) {
  24784. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24785. scene.incrementRenderId();
  24786. scene.resetCachedMaterial();
  24787. }
  24788. }
  24789. else {
  24790. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24791. }
  24792. this.onAfterUnbindObservable.notifyObservers(this);
  24793. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24794. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24795. }
  24796. engine.setViewport(scene.activeCamera.viewport);
  24797. scene.resetCachedMaterial();
  24798. };
  24799. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24800. var scene = this.getScene();
  24801. var engine = scene.getEngine();
  24802. // Bind
  24803. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24804. if (this.isCube) {
  24805. engine.bindFramebuffer(this._texture, faceIndex);
  24806. }
  24807. else {
  24808. engine.bindFramebuffer(this._texture);
  24809. }
  24810. }
  24811. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24812. // Clear
  24813. if (this.onClearObservable.hasObservers()) {
  24814. this.onClearObservable.notifyObservers(engine);
  24815. }
  24816. else {
  24817. engine.clear(scene.clearColor, true, true, true);
  24818. }
  24819. if (!this._doNotChangeAspectRatio) {
  24820. scene.updateTransformMatrix(true);
  24821. }
  24822. // Render
  24823. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24824. if (useCameraPostProcess) {
  24825. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24826. }
  24827. if (!this._doNotChangeAspectRatio) {
  24828. scene.updateTransformMatrix(true);
  24829. }
  24830. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24831. // Dump ?
  24832. if (dumpForDebug) {
  24833. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24834. }
  24835. // Unbind
  24836. if (!this.isCube || faceIndex === 5) {
  24837. if (this.isCube) {
  24838. if (faceIndex === 5) {
  24839. engine.generateMipMapsForCubemap(this._texture);
  24840. }
  24841. }
  24842. engine.unBindFramebuffer(this._texture, this.isCube);
  24843. }
  24844. };
  24845. /**
  24846. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24847. * This allowed control for front to back rendering or reversly depending of the special needs.
  24848. *
  24849. * @param renderingGroupId The rendering group id corresponding to its index
  24850. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24851. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24852. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24853. */
  24854. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24855. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24856. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24857. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24858. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24859. };
  24860. /**
  24861. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24862. *
  24863. * @param renderingGroupId The rendering group id corresponding to its index
  24864. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24865. */
  24866. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24867. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24868. };
  24869. RenderTargetTexture.prototype.clone = function () {
  24870. var textureSize = this.getSize();
  24871. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  24872. // Base texture
  24873. newTexture.hasAlpha = this.hasAlpha;
  24874. newTexture.level = this.level;
  24875. // RenderTarget Texture
  24876. newTexture.coordinatesMode = this.coordinatesMode;
  24877. newTexture.renderList = this.renderList.slice(0);
  24878. return newTexture;
  24879. };
  24880. RenderTargetTexture.prototype.serialize = function () {
  24881. if (!this.name) {
  24882. return null;
  24883. }
  24884. var serializationObject = _super.prototype.serialize.call(this);
  24885. serializationObject.renderTargetSize = this.getRenderSize();
  24886. serializationObject.renderList = [];
  24887. for (var index = 0; index < this.renderList.length; index++) {
  24888. serializationObject.renderList.push(this.renderList[index].id);
  24889. }
  24890. return serializationObject;
  24891. };
  24892. return RenderTargetTexture;
  24893. }(BABYLON.Texture));
  24894. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24895. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24896. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24897. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24898. })(BABYLON || (BABYLON = {}));
  24899. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24900. var BABYLON;
  24901. (function (BABYLON) {
  24902. var ProceduralTexture = (function (_super) {
  24903. __extends(ProceduralTexture, _super);
  24904. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24905. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24906. if (isCube === void 0) { isCube = false; }
  24907. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24908. _this.isCube = isCube;
  24909. _this.isEnabled = true;
  24910. _this._currentRefreshId = -1;
  24911. _this._refreshRate = 1;
  24912. _this._vertexBuffers = {};
  24913. _this._uniforms = new Array();
  24914. _this._samplers = new Array();
  24915. _this._textures = new Array();
  24916. _this._floats = new Array();
  24917. _this._floatsArrays = {};
  24918. _this._colors3 = new Array();
  24919. _this._colors4 = new Array();
  24920. _this._vectors2 = new Array();
  24921. _this._vectors3 = new Array();
  24922. _this._matrices = new Array();
  24923. _this._fallbackTextureUsed = false;
  24924. scene._proceduralTextures.push(_this);
  24925. _this.name = name;
  24926. _this.isRenderTarget = true;
  24927. _this._size = size;
  24928. _this._generateMipMaps = generateMipMaps;
  24929. _this.setFragment(fragment);
  24930. _this._fallbackTexture = fallbackTexture;
  24931. var engine = scene.getEngine();
  24932. if (isCube) {
  24933. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24934. _this.setFloat("face", 0);
  24935. }
  24936. else {
  24937. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24938. }
  24939. // VBO
  24940. var vertices = [];
  24941. vertices.push(1, 1);
  24942. vertices.push(-1, 1);
  24943. vertices.push(-1, -1);
  24944. vertices.push(1, -1);
  24945. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24946. // Indices
  24947. var indices = [];
  24948. indices.push(0);
  24949. indices.push(1);
  24950. indices.push(2);
  24951. indices.push(0);
  24952. indices.push(2);
  24953. indices.push(3);
  24954. _this._indexBuffer = engine.createIndexBuffer(indices);
  24955. return _this;
  24956. }
  24957. ProceduralTexture.prototype.reset = function () {
  24958. if (this._effect === undefined) {
  24959. return;
  24960. }
  24961. var engine = this.getScene().getEngine();
  24962. engine._releaseEffect(this._effect);
  24963. };
  24964. ProceduralTexture.prototype.isReady = function () {
  24965. var _this = this;
  24966. var engine = this.getScene().getEngine();
  24967. var shaders;
  24968. if (!this._fragment) {
  24969. return false;
  24970. }
  24971. if (this._fallbackTextureUsed) {
  24972. return true;
  24973. }
  24974. if (this._fragment.fragmentElement !== undefined) {
  24975. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24976. }
  24977. else {
  24978. shaders = { vertex: "procedural", fragment: this._fragment };
  24979. }
  24980. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24981. _this.releaseInternalTexture();
  24982. if (_this._fallbackTexture) {
  24983. _this._texture = _this._fallbackTexture._texture;
  24984. _this._texture.references++;
  24985. }
  24986. _this._fallbackTextureUsed = true;
  24987. });
  24988. return this._effect.isReady();
  24989. };
  24990. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24991. this._currentRefreshId = -1;
  24992. };
  24993. ProceduralTexture.prototype.setFragment = function (fragment) {
  24994. this._fragment = fragment;
  24995. };
  24996. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24997. get: function () {
  24998. return this._refreshRate;
  24999. },
  25000. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  25001. set: function (value) {
  25002. this._refreshRate = value;
  25003. this.resetRefreshCounter();
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. ProceduralTexture.prototype._shouldRender = function () {
  25009. if (!this.isEnabled || !this.isReady() || !this._texture) {
  25010. return false;
  25011. }
  25012. if (this._fallbackTextureUsed) {
  25013. return false;
  25014. }
  25015. if (this._currentRefreshId === -1) {
  25016. this._currentRefreshId = 1;
  25017. return true;
  25018. }
  25019. if (this.refreshRate === this._currentRefreshId) {
  25020. this._currentRefreshId = 1;
  25021. return true;
  25022. }
  25023. this._currentRefreshId++;
  25024. return false;
  25025. };
  25026. ProceduralTexture.prototype.getRenderSize = function () {
  25027. return this._size;
  25028. };
  25029. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  25030. if (this._fallbackTextureUsed) {
  25031. return;
  25032. }
  25033. this.releaseInternalTexture();
  25034. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  25035. };
  25036. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  25037. if (this._uniforms.indexOf(uniformName) === -1) {
  25038. this._uniforms.push(uniformName);
  25039. }
  25040. };
  25041. ProceduralTexture.prototype.setTexture = function (name, texture) {
  25042. if (this._samplers.indexOf(name) === -1) {
  25043. this._samplers.push(name);
  25044. }
  25045. this._textures[name] = texture;
  25046. return this;
  25047. };
  25048. ProceduralTexture.prototype.setFloat = function (name, value) {
  25049. this._checkUniform(name);
  25050. this._floats[name] = value;
  25051. return this;
  25052. };
  25053. ProceduralTexture.prototype.setFloats = function (name, value) {
  25054. this._checkUniform(name);
  25055. this._floatsArrays[name] = value;
  25056. return this;
  25057. };
  25058. ProceduralTexture.prototype.setColor3 = function (name, value) {
  25059. this._checkUniform(name);
  25060. this._colors3[name] = value;
  25061. return this;
  25062. };
  25063. ProceduralTexture.prototype.setColor4 = function (name, value) {
  25064. this._checkUniform(name);
  25065. this._colors4[name] = value;
  25066. return this;
  25067. };
  25068. ProceduralTexture.prototype.setVector2 = function (name, value) {
  25069. this._checkUniform(name);
  25070. this._vectors2[name] = value;
  25071. return this;
  25072. };
  25073. ProceduralTexture.prototype.setVector3 = function (name, value) {
  25074. this._checkUniform(name);
  25075. this._vectors3[name] = value;
  25076. return this;
  25077. };
  25078. ProceduralTexture.prototype.setMatrix = function (name, value) {
  25079. this._checkUniform(name);
  25080. this._matrices[name] = value;
  25081. return this;
  25082. };
  25083. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25084. var scene = this.getScene();
  25085. var engine = scene.getEngine();
  25086. // Render
  25087. engine.enableEffect(this._effect);
  25088. engine.setState(false);
  25089. // Texture
  25090. for (var name in this._textures) {
  25091. this._effect.setTexture(name, this._textures[name]);
  25092. }
  25093. // Float
  25094. for (name in this._floats) {
  25095. this._effect.setFloat(name, this._floats[name]);
  25096. }
  25097. // Floats
  25098. for (name in this._floatsArrays) {
  25099. this._effect.setArray(name, this._floatsArrays[name]);
  25100. }
  25101. // Color3
  25102. for (name in this._colors3) {
  25103. this._effect.setColor3(name, this._colors3[name]);
  25104. }
  25105. // Color4
  25106. for (name in this._colors4) {
  25107. var color = this._colors4[name];
  25108. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25109. }
  25110. // Vector2
  25111. for (name in this._vectors2) {
  25112. this._effect.setVector2(name, this._vectors2[name]);
  25113. }
  25114. // Vector3
  25115. for (name in this._vectors3) {
  25116. this._effect.setVector3(name, this._vectors3[name]);
  25117. }
  25118. // Matrix
  25119. for (name in this._matrices) {
  25120. this._effect.setMatrix(name, this._matrices[name]);
  25121. }
  25122. if (this.isCube) {
  25123. for (var face = 0; face < 6; face++) {
  25124. engine.bindFramebuffer(this._texture, face);
  25125. // VBOs
  25126. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25127. this._effect.setFloat("face", face);
  25128. // Clear
  25129. engine.clear(scene.clearColor, true, true, true);
  25130. // Draw order
  25131. engine.draw(true, 0, 6);
  25132. // Mipmaps
  25133. if (face === 5) {
  25134. engine.generateMipMapsForCubemap(this._texture);
  25135. }
  25136. }
  25137. }
  25138. else {
  25139. engine.bindFramebuffer(this._texture);
  25140. // VBOs
  25141. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25142. // Clear
  25143. engine.clear(scene.clearColor, true, true, true);
  25144. // Draw order
  25145. engine.draw(true, 0, 6);
  25146. }
  25147. // Unbind
  25148. engine.unBindFramebuffer(this._texture, this.isCube);
  25149. if (this.onGenerated) {
  25150. this.onGenerated();
  25151. }
  25152. };
  25153. ProceduralTexture.prototype.clone = function () {
  25154. var textureSize = this.getSize();
  25155. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  25156. // Base texture
  25157. newTexture.hasAlpha = this.hasAlpha;
  25158. newTexture.level = this.level;
  25159. // RenderTarget Texture
  25160. newTexture.coordinatesMode = this.coordinatesMode;
  25161. return newTexture;
  25162. };
  25163. ProceduralTexture.prototype.dispose = function () {
  25164. var index = this.getScene()._proceduralTextures.indexOf(this);
  25165. if (index >= 0) {
  25166. this.getScene()._proceduralTextures.splice(index, 1);
  25167. }
  25168. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25169. if (vertexBuffer) {
  25170. vertexBuffer.dispose();
  25171. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25172. }
  25173. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  25174. this._indexBuffer = null;
  25175. }
  25176. _super.prototype.dispose.call(this);
  25177. };
  25178. return ProceduralTexture;
  25179. }(BABYLON.Texture));
  25180. BABYLON.ProceduralTexture = ProceduralTexture;
  25181. })(BABYLON || (BABYLON = {}));
  25182. //# sourceMappingURL=babylon.proceduralTexture.js.map
  25183. var BABYLON;
  25184. (function (BABYLON) {
  25185. var MirrorTexture = (function (_super) {
  25186. __extends(MirrorTexture, _super);
  25187. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  25188. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25189. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  25190. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  25191. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  25192. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  25193. _this._transformMatrix = BABYLON.Matrix.Zero();
  25194. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  25195. _this.onBeforeRenderObservable.add(function () {
  25196. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  25197. _this._savedViewMatrix = scene.getViewMatrix();
  25198. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  25199. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  25200. scene.clipPlane = _this.mirrorPlane;
  25201. scene.getEngine().cullBackFaces = false;
  25202. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  25203. });
  25204. _this.onAfterRenderObservable.add(function () {
  25205. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  25206. scene.getEngine().cullBackFaces = true;
  25207. scene._mirroredCameraPosition = null;
  25208. delete scene.clipPlane;
  25209. });
  25210. return _this;
  25211. }
  25212. MirrorTexture.prototype.clone = function () {
  25213. var textureSize = this.getSize();
  25214. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  25215. // Base texture
  25216. newTexture.hasAlpha = this.hasAlpha;
  25217. newTexture.level = this.level;
  25218. // Mirror Texture
  25219. newTexture.mirrorPlane = this.mirrorPlane.clone();
  25220. newTexture.renderList = this.renderList.slice(0);
  25221. return newTexture;
  25222. };
  25223. MirrorTexture.prototype.serialize = function () {
  25224. if (!this.name) {
  25225. return null;
  25226. }
  25227. var serializationObject = _super.prototype.serialize.call(this);
  25228. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  25229. return serializationObject;
  25230. };
  25231. return MirrorTexture;
  25232. }(BABYLON.RenderTargetTexture));
  25233. BABYLON.MirrorTexture = MirrorTexture;
  25234. })(BABYLON || (BABYLON = {}));
  25235. //# sourceMappingURL=babylon.mirrorTexture.js.map
  25236. var BABYLON;
  25237. (function (BABYLON) {
  25238. /**
  25239. * Creates a refraction texture used by refraction channel of the standard material.
  25240. * @param name the texture name
  25241. * @param size size of the underlying texture
  25242. * @param scene root scene
  25243. */
  25244. var RefractionTexture = (function (_super) {
  25245. __extends(RefractionTexture, _super);
  25246. function RefractionTexture(name, size, scene, generateMipMaps) {
  25247. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  25248. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  25249. _this.depth = 2.0;
  25250. _this.onBeforeRenderObservable.add(function () {
  25251. scene.clipPlane = _this.refractionPlane;
  25252. });
  25253. _this.onAfterRenderObservable.add(function () {
  25254. delete scene.clipPlane;
  25255. });
  25256. return _this;
  25257. }
  25258. RefractionTexture.prototype.clone = function () {
  25259. var textureSize = this.getSize();
  25260. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  25261. // Base texture
  25262. newTexture.hasAlpha = this.hasAlpha;
  25263. newTexture.level = this.level;
  25264. // Refraction Texture
  25265. newTexture.refractionPlane = this.refractionPlane.clone();
  25266. newTexture.renderList = this.renderList.slice(0);
  25267. newTexture.depth = this.depth;
  25268. return newTexture;
  25269. };
  25270. RefractionTexture.prototype.serialize = function () {
  25271. if (!this.name) {
  25272. return null;
  25273. }
  25274. var serializationObject = _super.prototype.serialize.call(this);
  25275. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  25276. serializationObject.depth = this.depth;
  25277. return serializationObject;
  25278. };
  25279. return RefractionTexture;
  25280. }(BABYLON.RenderTargetTexture));
  25281. BABYLON.RefractionTexture = RefractionTexture;
  25282. })(BABYLON || (BABYLON = {}));
  25283. //# sourceMappingURL=babylon.refractionTexture.js.map
  25284. var BABYLON;
  25285. (function (BABYLON) {
  25286. var DynamicTexture = (function (_super) {
  25287. __extends(DynamicTexture, _super);
  25288. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  25289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25290. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25291. _this.name = name;
  25292. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25293. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25294. _this._generateMipMaps = generateMipMaps;
  25295. if (options.getContext) {
  25296. _this._canvas = options;
  25297. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25298. }
  25299. else {
  25300. _this._canvas = document.createElement("canvas");
  25301. if (options.width) {
  25302. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25303. }
  25304. else {
  25305. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  25306. }
  25307. }
  25308. var textureSize = _this.getSize();
  25309. _this._canvas.width = textureSize.width;
  25310. _this._canvas.height = textureSize.height;
  25311. _this._context = _this._canvas.getContext("2d");
  25312. return _this;
  25313. }
  25314. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  25315. get: function () {
  25316. return true;
  25317. },
  25318. enumerable: true,
  25319. configurable: true
  25320. });
  25321. DynamicTexture.prototype.scale = function (ratio) {
  25322. var textureSize = this.getSize();
  25323. textureSize.width *= ratio;
  25324. textureSize.height *= ratio;
  25325. this._canvas.width = textureSize.width;
  25326. this._canvas.height = textureSize.height;
  25327. this.releaseInternalTexture();
  25328. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  25329. };
  25330. DynamicTexture.prototype.getContext = function () {
  25331. return this._context;
  25332. };
  25333. DynamicTexture.prototype.clear = function () {
  25334. var size = this.getSize();
  25335. this._context.fillRect(0, 0, size.width, size.height);
  25336. };
  25337. DynamicTexture.prototype.update = function (invertY) {
  25338. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  25339. };
  25340. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  25341. if (update === void 0) { update = true; }
  25342. var size = this.getSize();
  25343. if (clearColor) {
  25344. this._context.fillStyle = clearColor;
  25345. this._context.fillRect(0, 0, size.width, size.height);
  25346. }
  25347. this._context.font = font;
  25348. if (x === null) {
  25349. var textSize = this._context.measureText(text);
  25350. x = (size.width - textSize.width) / 2;
  25351. }
  25352. this._context.fillStyle = color;
  25353. this._context.fillText(text, x, y);
  25354. if (update) {
  25355. this.update(invertY);
  25356. }
  25357. };
  25358. DynamicTexture.prototype.clone = function () {
  25359. var textureSize = this.getSize();
  25360. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  25361. // Base texture
  25362. newTexture.hasAlpha = this.hasAlpha;
  25363. newTexture.level = this.level;
  25364. // Dynamic Texture
  25365. newTexture.wrapU = this.wrapU;
  25366. newTexture.wrapV = this.wrapV;
  25367. return newTexture;
  25368. };
  25369. return DynamicTexture;
  25370. }(BABYLON.Texture));
  25371. BABYLON.DynamicTexture = DynamicTexture;
  25372. })(BABYLON || (BABYLON = {}));
  25373. //# sourceMappingURL=babylon.dynamicTexture.js.map
  25374. var BABYLON;
  25375. (function (BABYLON) {
  25376. var VideoTexture = (function (_super) {
  25377. __extends(VideoTexture, _super);
  25378. /**
  25379. * Creates a video texture.
  25380. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  25381. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  25382. * @param {BABYLON.Scene} scene is obviously the current scene.
  25383. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  25384. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  25385. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  25386. */
  25387. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  25388. if (generateMipMaps === void 0) { generateMipMaps = false; }
  25389. if (invertY === void 0) { invertY = false; }
  25390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25391. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  25392. _this._autoLaunch = true;
  25393. var urls;
  25394. _this.name = name;
  25395. if (urlsOrVideo instanceof HTMLVideoElement) {
  25396. _this.video = urlsOrVideo;
  25397. }
  25398. else {
  25399. urls = urlsOrVideo;
  25400. _this.video = document.createElement("video");
  25401. _this.video.autoplay = false;
  25402. _this.video.loop = true;
  25403. }
  25404. _this._generateMipMaps = generateMipMaps;
  25405. _this._samplingMode = samplingMode;
  25406. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  25407. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25408. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25409. }
  25410. else {
  25411. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25412. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25413. _this._generateMipMaps = false;
  25414. }
  25415. if (urls) {
  25416. _this.video.addEventListener("canplaythrough", function () {
  25417. _this._createTexture();
  25418. });
  25419. urls.forEach(function (url) {
  25420. var source = document.createElement("source");
  25421. source.src = url;
  25422. _this.video.appendChild(source);
  25423. });
  25424. }
  25425. else {
  25426. _this._createTexture();
  25427. }
  25428. _this._lastUpdate = BABYLON.Tools.Now;
  25429. return _this;
  25430. }
  25431. VideoTexture.prototype._createTexture = function () {
  25432. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  25433. this._texture.isReady = true;
  25434. };
  25435. VideoTexture.prototype.update = function () {
  25436. if (this._autoLaunch) {
  25437. this._autoLaunch = false;
  25438. this.video.play();
  25439. }
  25440. var now = BABYLON.Tools.Now;
  25441. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  25442. return false;
  25443. }
  25444. this._lastUpdate = now;
  25445. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  25446. return true;
  25447. };
  25448. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  25449. var video = document.createElement("video");
  25450. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  25451. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  25452. if (navigator.getUserMedia) {
  25453. navigator.getUserMedia({
  25454. video: {
  25455. width: {
  25456. min: (constraints && constraints.minWidth) || 256,
  25457. max: (constraints && constraints.maxWidth) || 640
  25458. },
  25459. height: {
  25460. min: (constraints && constraints.minHeight) || 256,
  25461. max: (constraints && constraints.maxHeight) || 480
  25462. }
  25463. }
  25464. }, function (stream) {
  25465. if (video.mozSrcObject !== undefined) {
  25466. video.mozSrcObject = stream;
  25467. }
  25468. else {
  25469. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  25470. }
  25471. video.play();
  25472. if (onReady) {
  25473. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  25474. }
  25475. }, function (e) {
  25476. BABYLON.Tools.Error(e.name);
  25477. });
  25478. }
  25479. };
  25480. return VideoTexture;
  25481. }(BABYLON.Texture));
  25482. BABYLON.VideoTexture = VideoTexture;
  25483. })(BABYLON || (BABYLON = {}));
  25484. //# sourceMappingURL=babylon.videoTexture.js.map
  25485. var BABYLON;
  25486. (function (BABYLON) {
  25487. var CustomProceduralTexture = (function (_super) {
  25488. __extends(CustomProceduralTexture, _super);
  25489. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  25490. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  25491. _this._animate = true;
  25492. _this._time = 0;
  25493. _this._texturePath = texturePath;
  25494. //Try to load json
  25495. _this.loadJson(texturePath);
  25496. _this.refreshRate = 1;
  25497. return _this;
  25498. }
  25499. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  25500. var _this = this;
  25501. var that = this;
  25502. function noConfigFile() {
  25503. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  25504. try {
  25505. that.setFragment(that._texturePath);
  25506. }
  25507. catch (ex) {
  25508. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  25509. }
  25510. }
  25511. var configFileUrl = jsonUrl + "/config.json";
  25512. var xhr = new XMLHttpRequest();
  25513. xhr.open("GET", configFileUrl, true);
  25514. xhr.addEventListener("load", function () {
  25515. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  25516. try {
  25517. _this._config = JSON.parse(xhr.response);
  25518. _this.updateShaderUniforms();
  25519. _this.updateTextures();
  25520. _this.setFragment(_this._texturePath + "/custom");
  25521. _this._animate = _this._config.animate;
  25522. _this.refreshRate = _this._config.refreshrate;
  25523. }
  25524. catch (ex) {
  25525. noConfigFile();
  25526. }
  25527. }
  25528. else {
  25529. noConfigFile();
  25530. }
  25531. }, false);
  25532. xhr.addEventListener("error", function () {
  25533. noConfigFile();
  25534. }, false);
  25535. try {
  25536. xhr.send();
  25537. }
  25538. catch (ex) {
  25539. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  25540. }
  25541. };
  25542. CustomProceduralTexture.prototype.isReady = function () {
  25543. if (!_super.prototype.isReady.call(this)) {
  25544. return false;
  25545. }
  25546. for (var name in this._textures) {
  25547. var texture = this._textures[name];
  25548. if (!texture.isReady()) {
  25549. return false;
  25550. }
  25551. }
  25552. return true;
  25553. };
  25554. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25555. if (this._animate) {
  25556. this._time += this.getScene().getAnimationRatio() * 0.03;
  25557. this.updateShaderUniforms();
  25558. }
  25559. _super.prototype.render.call(this, useCameraPostProcess);
  25560. };
  25561. CustomProceduralTexture.prototype.updateTextures = function () {
  25562. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  25563. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  25564. }
  25565. };
  25566. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  25567. if (this._config) {
  25568. for (var j = 0; j < this._config.uniforms.length; j++) {
  25569. var uniform = this._config.uniforms[j];
  25570. switch (uniform.type) {
  25571. case "float":
  25572. this.setFloat(uniform.name, uniform.value);
  25573. break;
  25574. case "color3":
  25575. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  25576. break;
  25577. case "color4":
  25578. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  25579. break;
  25580. case "vector2":
  25581. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  25582. break;
  25583. case "vector3":
  25584. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  25585. break;
  25586. }
  25587. }
  25588. }
  25589. this.setFloat("time", this._time);
  25590. };
  25591. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  25592. get: function () {
  25593. return this._animate;
  25594. },
  25595. set: function (value) {
  25596. this._animate = value;
  25597. },
  25598. enumerable: true,
  25599. configurable: true
  25600. });
  25601. return CustomProceduralTexture;
  25602. }(BABYLON.ProceduralTexture));
  25603. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  25604. })(BABYLON || (BABYLON = {}));
  25605. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  25606. var BABYLON;
  25607. (function (BABYLON) {
  25608. var EffectFallbacks = (function () {
  25609. function EffectFallbacks() {
  25610. this._defines = {};
  25611. this._currentRank = 32;
  25612. this._maxRank = -1;
  25613. }
  25614. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25615. if (!this._defines[rank]) {
  25616. if (rank < this._currentRank) {
  25617. this._currentRank = rank;
  25618. }
  25619. if (rank > this._maxRank) {
  25620. this._maxRank = rank;
  25621. }
  25622. this._defines[rank] = new Array();
  25623. }
  25624. this._defines[rank].push(define);
  25625. };
  25626. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25627. this._meshRank = rank;
  25628. this._mesh = mesh;
  25629. if (rank > this._maxRank) {
  25630. this._maxRank = rank;
  25631. }
  25632. };
  25633. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25634. get: function () {
  25635. return this._currentRank <= this._maxRank;
  25636. },
  25637. enumerable: true,
  25638. configurable: true
  25639. });
  25640. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25641. var currentFallbacks = this._defines[this._currentRank];
  25642. for (var index = 0; index < currentFallbacks.length; index++) {
  25643. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25644. }
  25645. if (this._mesh && this._currentRank === this._meshRank) {
  25646. this._mesh.computeBonesUsingShaders = false;
  25647. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25648. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25649. }
  25650. this._currentRank++;
  25651. return currentDefines;
  25652. };
  25653. return EffectFallbacks;
  25654. }());
  25655. BABYLON.EffectFallbacks = EffectFallbacks;
  25656. var Effect = (function () {
  25657. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25658. var _this = this;
  25659. this.uniqueId = 0;
  25660. this._isReady = false;
  25661. this._compilationError = "";
  25662. this._valueCache = {};
  25663. this._engine = engine;
  25664. this.name = baseName;
  25665. this.defines = defines;
  25666. this._uniformsNames = uniformsNames.concat(samplers);
  25667. this._samplers = samplers;
  25668. this._attributesNames = attributesNames;
  25669. this.onError = onError;
  25670. this.onCompiled = onCompiled;
  25671. this._indexParameters = indexParameters;
  25672. this.uniqueId = Effect._uniqueIdSeed++;
  25673. var vertexSource;
  25674. var fragmentSource;
  25675. if (baseName.vertexElement) {
  25676. vertexSource = document.getElementById(baseName.vertexElement);
  25677. if (!vertexSource) {
  25678. vertexSource = baseName.vertexElement;
  25679. }
  25680. }
  25681. else {
  25682. vertexSource = baseName.vertex || baseName;
  25683. }
  25684. if (baseName.fragmentElement) {
  25685. fragmentSource = document.getElementById(baseName.fragmentElement);
  25686. if (!fragmentSource) {
  25687. fragmentSource = baseName.fragmentElement;
  25688. }
  25689. }
  25690. else {
  25691. fragmentSource = baseName.fragment || baseName;
  25692. }
  25693. this._loadVertexShader(vertexSource, function (vertexCode) {
  25694. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25695. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25696. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25697. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25698. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25699. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  25700. });
  25701. });
  25702. });
  25703. });
  25704. });
  25705. });
  25706. }
  25707. Object.defineProperty(Effect.prototype, "key", {
  25708. get: function () {
  25709. return this._key;
  25710. },
  25711. enumerable: true,
  25712. configurable: true
  25713. });
  25714. // Properties
  25715. Effect.prototype.isReady = function () {
  25716. return this._isReady;
  25717. };
  25718. Effect.prototype.getProgram = function () {
  25719. return this._program;
  25720. };
  25721. Effect.prototype.getAttributesNames = function () {
  25722. return this._attributesNames;
  25723. };
  25724. Effect.prototype.getAttributeLocation = function (index) {
  25725. return this._attributes[index];
  25726. };
  25727. Effect.prototype.getAttributeLocationByName = function (name) {
  25728. var index = this._attributesNames.indexOf(name);
  25729. return this._attributes[index];
  25730. };
  25731. Effect.prototype.getAttributesCount = function () {
  25732. return this._attributes.length;
  25733. };
  25734. Effect.prototype.getUniformIndex = function (uniformName) {
  25735. return this._uniformsNames.indexOf(uniformName);
  25736. };
  25737. Effect.prototype.getUniform = function (uniformName) {
  25738. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25739. };
  25740. Effect.prototype.getSamplers = function () {
  25741. return this._samplers;
  25742. };
  25743. Effect.prototype.getCompilationError = function () {
  25744. return this._compilationError;
  25745. };
  25746. Effect.prototype.getVertexShaderSource = function () {
  25747. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25748. };
  25749. Effect.prototype.getFragmentShaderSource = function () {
  25750. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25751. };
  25752. // Methods
  25753. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25754. // DOM element ?
  25755. if (vertex instanceof HTMLElement) {
  25756. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25757. callback(vertexCode);
  25758. return;
  25759. }
  25760. // Base64 encoded ?
  25761. if (vertex.substr(0, 7) === "base64:") {
  25762. var vertexBinary = window.atob(vertex.substr(7));
  25763. callback(vertexBinary);
  25764. return;
  25765. }
  25766. // Is in local store ?
  25767. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25768. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25769. return;
  25770. }
  25771. var vertexShaderUrl;
  25772. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25773. vertexShaderUrl = vertex;
  25774. }
  25775. else {
  25776. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25777. }
  25778. // Vertex shader
  25779. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25780. };
  25781. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25782. // DOM element ?
  25783. if (fragment instanceof HTMLElement) {
  25784. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25785. callback(fragmentCode);
  25786. return;
  25787. }
  25788. // Base64 encoded ?
  25789. if (fragment.substr(0, 7) === "base64:") {
  25790. var fragmentBinary = window.atob(fragment.substr(7));
  25791. callback(fragmentBinary);
  25792. return;
  25793. }
  25794. // Is in local store ?
  25795. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25796. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25797. return;
  25798. }
  25799. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25800. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25801. return;
  25802. }
  25803. var fragmentShaderUrl;
  25804. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25805. fragmentShaderUrl = fragment;
  25806. }
  25807. else {
  25808. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25809. }
  25810. // Fragment shader
  25811. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25812. };
  25813. Effect.prototype._dumpShadersName = function () {
  25814. if (this.name.vertexElement) {
  25815. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25816. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25817. }
  25818. else if (this.name.vertex) {
  25819. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25820. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25821. }
  25822. else {
  25823. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25824. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25825. }
  25826. };
  25827. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25828. var preparedSourceCode = this._processPrecision(sourceCode);
  25829. if (this._engine.webGLVersion == 1) {
  25830. callback(preparedSourceCode);
  25831. return;
  25832. }
  25833. // Already converted
  25834. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25835. callback(preparedSourceCode);
  25836. return;
  25837. }
  25838. // Remove extensions
  25839. // #extension GL_OES_standard_derivatives : enable
  25840. // #extension GL_EXT_shader_texture_lod : enable
  25841. // #extension GL_EXT_frag_depth : enable
  25842. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  25843. var result = preparedSourceCode.replace(regex, "");
  25844. // Migrate to GLSL v300
  25845. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  25846. result = result.replace(/attribute[ \t]/g, "in ");
  25847. result = result.replace(/[ \t]attribute/g, " in");
  25848. if (isFragment) {
  25849. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  25850. result = result.replace(/texture2D\(/g, "texture(");
  25851. result = result.replace(/textureCube\(/g, "texture(");
  25852. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25853. result = result.replace(/gl_FragColor/g, "glFragColor");
  25854. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  25855. }
  25856. callback(result);
  25857. };
  25858. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25859. var _this = this;
  25860. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25861. var match = regex.exec(sourceCode);
  25862. var returnValue = new String(sourceCode);
  25863. while (match != null) {
  25864. var includeFile = match[1];
  25865. if (Effect.IncludesShadersStore[includeFile]) {
  25866. // Substitution
  25867. var includeContent = Effect.IncludesShadersStore[includeFile];
  25868. if (match[2]) {
  25869. var splits = match[3].split(",");
  25870. for (var index = 0; index < splits.length; index += 2) {
  25871. var source = new RegExp(splits[index], "g");
  25872. var dest = splits[index + 1];
  25873. includeContent = includeContent.replace(source, dest);
  25874. }
  25875. }
  25876. if (match[4]) {
  25877. var indexString = match[5];
  25878. if (indexString.indexOf("..") !== -1) {
  25879. var indexSplits = indexString.split("..");
  25880. var minIndex = parseInt(indexSplits[0]);
  25881. var maxIndex = parseInt(indexSplits[1]);
  25882. var sourceIncludeContent = includeContent.slice(0);
  25883. includeContent = "";
  25884. if (isNaN(maxIndex)) {
  25885. maxIndex = this._indexParameters[indexSplits[1]];
  25886. }
  25887. for (var i = minIndex; i <= maxIndex; i++) {
  25888. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25889. }
  25890. }
  25891. else {
  25892. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25893. }
  25894. }
  25895. // Replace
  25896. returnValue = returnValue.replace(match[0], includeContent);
  25897. }
  25898. else {
  25899. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25900. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25901. Effect.IncludesShadersStore[includeFile] = fileContent;
  25902. _this._processIncludes(returnValue, callback);
  25903. });
  25904. return;
  25905. }
  25906. match = regex.exec(sourceCode);
  25907. }
  25908. callback(returnValue);
  25909. };
  25910. Effect.prototype._processPrecision = function (source) {
  25911. if (source.indexOf("precision highp float") === -1) {
  25912. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25913. source = "precision mediump float;\n" + source;
  25914. }
  25915. else {
  25916. source = "precision highp float;\n" + source;
  25917. }
  25918. }
  25919. else {
  25920. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25921. source = source.replace("precision highp float", "precision mediump float");
  25922. }
  25923. }
  25924. return source;
  25925. };
  25926. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25927. try {
  25928. var engine = this._engine;
  25929. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25930. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25931. this._attributes = engine.getAttributes(this._program, attributesNames);
  25932. var index;
  25933. for (index = 0; index < this._samplers.length; index++) {
  25934. var sampler = this.getUniform(this._samplers[index]);
  25935. if (sampler == null) {
  25936. this._samplers.splice(index, 1);
  25937. index--;
  25938. }
  25939. }
  25940. engine.bindSamplers(this);
  25941. this._compilationError = "";
  25942. this._isReady = true;
  25943. if (this.onCompiled) {
  25944. this.onCompiled(this);
  25945. }
  25946. }
  25947. catch (e) {
  25948. this._compilationError = e.message;
  25949. // Let's go through fallbacks then
  25950. BABYLON.Tools.Error("Unable to compile effect: ");
  25951. BABYLON.Tools.Error("Defines: " + defines);
  25952. BABYLON.Tools.Error("Error: " + this._compilationError);
  25953. this._dumpShadersName();
  25954. if (fallbacks && fallbacks.isMoreFallbacks) {
  25955. BABYLON.Tools.Error("Trying next fallback.");
  25956. defines = fallbacks.reduce(defines);
  25957. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25958. }
  25959. else {
  25960. if (this.onError) {
  25961. this.onError(this, this._compilationError);
  25962. }
  25963. }
  25964. }
  25965. };
  25966. Object.defineProperty(Effect.prototype, "isSupported", {
  25967. get: function () {
  25968. return this._compilationError === "";
  25969. },
  25970. enumerable: true,
  25971. configurable: true
  25972. });
  25973. Effect.prototype._bindTexture = function (channel, texture) {
  25974. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25975. };
  25976. Effect.prototype.setTexture = function (channel, texture) {
  25977. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25978. };
  25979. Effect.prototype.setTextureArray = function (channel, textures) {
  25980. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25981. var initialPos = this._samplers.indexOf(channel);
  25982. for (var index = 1; index < textures.length; index++) {
  25983. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25984. }
  25985. }
  25986. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25987. };
  25988. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25989. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25990. };
  25991. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25992. var changed = false;
  25993. var cache = this._valueCache[uniformName];
  25994. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25995. changed = true;
  25996. cache = new BABYLON.Matrix();
  25997. }
  25998. var tm = cache.m;
  25999. var om = matrix.m;
  26000. for (var index = 0; index < 16; index++) {
  26001. if (tm[index] !== om[index]) {
  26002. tm[index] = om[index];
  26003. changed = true;
  26004. }
  26005. }
  26006. this._valueCache[uniformName] = cache;
  26007. return changed;
  26008. };
  26009. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26010. var cache = this._valueCache[uniformName];
  26011. if (!cache) {
  26012. cache = [x, y];
  26013. this._valueCache[uniformName] = cache;
  26014. return true;
  26015. }
  26016. var changed = false;
  26017. if (cache[0] !== x) {
  26018. cache[0] = x;
  26019. changed = true;
  26020. }
  26021. if (cache[1] !== y) {
  26022. cache[1] = y;
  26023. changed = true;
  26024. }
  26025. return changed;
  26026. };
  26027. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26028. var cache = this._valueCache[uniformName];
  26029. if (!cache) {
  26030. cache = [x, y, z];
  26031. this._valueCache[uniformName] = cache;
  26032. return true;
  26033. }
  26034. var changed = false;
  26035. if (cache[0] !== x) {
  26036. cache[0] = x;
  26037. changed = true;
  26038. }
  26039. if (cache[1] !== y) {
  26040. cache[1] = y;
  26041. changed = true;
  26042. }
  26043. if (cache[2] !== z) {
  26044. cache[2] = z;
  26045. changed = true;
  26046. }
  26047. return changed;
  26048. };
  26049. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26050. var cache = this._valueCache[uniformName];
  26051. if (!cache) {
  26052. cache = [x, y, z, w];
  26053. this._valueCache[uniformName] = cache;
  26054. return true;
  26055. }
  26056. var changed = false;
  26057. if (cache[0] !== x) {
  26058. cache[0] = x;
  26059. changed = true;
  26060. }
  26061. if (cache[1] !== y) {
  26062. cache[1] = y;
  26063. changed = true;
  26064. }
  26065. if (cache[2] !== z) {
  26066. cache[2] = z;
  26067. changed = true;
  26068. }
  26069. if (cache[3] !== w) {
  26070. cache[3] = w;
  26071. changed = true;
  26072. }
  26073. return changed;
  26074. };
  26075. Effect.prototype.setIntArray = function (uniformName, array) {
  26076. this._valueCache[uniformName] = null;
  26077. this._engine.setIntArray(this.getUniform(uniformName), array);
  26078. return this;
  26079. };
  26080. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26081. this._valueCache[uniformName] = null;
  26082. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26083. return this;
  26084. };
  26085. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26086. this._valueCache[uniformName] = null;
  26087. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26088. return this;
  26089. };
  26090. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26091. this._valueCache[uniformName] = null;
  26092. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26093. return this;
  26094. };
  26095. Effect.prototype.setFloatArray = function (uniformName, array) {
  26096. this._valueCache[uniformName] = null;
  26097. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26098. return this;
  26099. };
  26100. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26101. this._valueCache[uniformName] = null;
  26102. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26103. return this;
  26104. };
  26105. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26106. this._valueCache[uniformName] = null;
  26107. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26108. return this;
  26109. };
  26110. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26111. this._valueCache[uniformName] = null;
  26112. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26113. return this;
  26114. };
  26115. Effect.prototype.setArray = function (uniformName, array) {
  26116. this._valueCache[uniformName] = null;
  26117. this._engine.setArray(this.getUniform(uniformName), array);
  26118. return this;
  26119. };
  26120. Effect.prototype.setArray2 = function (uniformName, array) {
  26121. this._valueCache[uniformName] = null;
  26122. this._engine.setArray2(this.getUniform(uniformName), array);
  26123. return this;
  26124. };
  26125. Effect.prototype.setArray3 = function (uniformName, array) {
  26126. this._valueCache[uniformName] = null;
  26127. this._engine.setArray3(this.getUniform(uniformName), array);
  26128. return this;
  26129. };
  26130. Effect.prototype.setArray4 = function (uniformName, array) {
  26131. this._valueCache[uniformName] = null;
  26132. this._engine.setArray4(this.getUniform(uniformName), array);
  26133. return this;
  26134. };
  26135. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26136. this._valueCache[uniformName] = null;
  26137. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26138. return this;
  26139. };
  26140. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26141. if (this._cacheMatrix(uniformName, matrix)) {
  26142. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26143. }
  26144. return this;
  26145. };
  26146. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26147. this._valueCache[uniformName] = null;
  26148. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26149. return this;
  26150. };
  26151. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26152. this._valueCache[uniformName] = null;
  26153. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26154. return this;
  26155. };
  26156. Effect.prototype.setFloat = function (uniformName, value) {
  26157. var cache = this._valueCache[uniformName];
  26158. if (cache !== undefined && cache === value)
  26159. return this;
  26160. this._valueCache[uniformName] = value;
  26161. this._engine.setFloat(this.getUniform(uniformName), value);
  26162. return this;
  26163. };
  26164. Effect.prototype.setBool = function (uniformName, bool) {
  26165. var cache = this._valueCache[uniformName];
  26166. if (cache !== undefined && cache === bool)
  26167. return this;
  26168. this._valueCache[uniformName] = bool;
  26169. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26170. return this;
  26171. };
  26172. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26173. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26174. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26175. }
  26176. return this;
  26177. };
  26178. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26179. if (this._cacheFloat2(uniformName, x, y)) {
  26180. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26181. }
  26182. return this;
  26183. };
  26184. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26185. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26186. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26187. }
  26188. return this;
  26189. };
  26190. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26191. if (this._cacheFloat3(uniformName, x, y, z)) {
  26192. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26193. }
  26194. return this;
  26195. };
  26196. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26197. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26198. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26199. }
  26200. return this;
  26201. };
  26202. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26203. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26204. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26205. }
  26206. return this;
  26207. };
  26208. Effect.prototype.setColor3 = function (uniformName, color3) {
  26209. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26210. this._engine.setColor3(this.getUniform(uniformName), color3);
  26211. }
  26212. return this;
  26213. };
  26214. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26215. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26216. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26217. }
  26218. return this;
  26219. };
  26220. Effect.prototype._recombineShader = function (node) {
  26221. if (node.define) {
  26222. if (node.condition) {
  26223. var defineIndex = this.defines.indexOf("#define " + node.define);
  26224. if (defineIndex === -1) {
  26225. return null;
  26226. }
  26227. var nextComma = this.defines.indexOf("\n", defineIndex);
  26228. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  26229. var condition = defineValue + node.condition;
  26230. if (!eval(condition)) {
  26231. return null;
  26232. }
  26233. }
  26234. else if (node.ndef) {
  26235. if (this.defines.indexOf("#define " + node.define) !== -1) {
  26236. return null;
  26237. }
  26238. }
  26239. else if (this.defines.indexOf("#define " + node.define) === -1) {
  26240. return null;
  26241. }
  26242. }
  26243. var result = "";
  26244. for (var index = 0; index < node.children.length; index++) {
  26245. var line = node.children[index];
  26246. if (line.children) {
  26247. var combined = this._recombineShader(line);
  26248. if (combined !== null) {
  26249. result += combined + "\r\n";
  26250. }
  26251. continue;
  26252. }
  26253. if (line.length > 0) {
  26254. result += line + "\r\n";
  26255. }
  26256. }
  26257. return result;
  26258. };
  26259. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  26260. var root = {
  26261. children: []
  26262. };
  26263. var currentNode = root;
  26264. var lines = shaderString.split("\n");
  26265. for (var index = 0; index < lines.length; index++) {
  26266. var line = lines[index].trim();
  26267. // #ifdef
  26268. var pos = line.indexOf("#ifdef ");
  26269. if (pos !== -1) {
  26270. var define = line.substr(pos + 7);
  26271. var newNode = {
  26272. condition: null,
  26273. ndef: false,
  26274. define: define,
  26275. children: [],
  26276. parent: currentNode
  26277. };
  26278. currentNode.children.push(newNode);
  26279. currentNode = newNode;
  26280. continue;
  26281. }
  26282. // #ifndef
  26283. var pos = line.indexOf("#ifndef ");
  26284. if (pos !== -1) {
  26285. var define = line.substr(pos + 8);
  26286. newNode = {
  26287. condition: null,
  26288. define: define,
  26289. ndef: true,
  26290. children: [],
  26291. parent: currentNode
  26292. };
  26293. currentNode.children.push(newNode);
  26294. currentNode = newNode;
  26295. continue;
  26296. }
  26297. // #if
  26298. var pos = line.indexOf("#if ");
  26299. if (pos !== -1) {
  26300. var define = line.substr(pos + 4).trim();
  26301. var conditionPos = define.indexOf(" ");
  26302. newNode = {
  26303. condition: define.substr(conditionPos + 1),
  26304. define: define.substr(0, conditionPos),
  26305. ndef: false,
  26306. children: [],
  26307. parent: currentNode
  26308. };
  26309. currentNode.children.push(newNode);
  26310. currentNode = newNode;
  26311. continue;
  26312. }
  26313. // #endif
  26314. pos = line.indexOf("#endif");
  26315. if (pos !== -1) {
  26316. currentNode = currentNode.parent;
  26317. continue;
  26318. }
  26319. currentNode.children.push(line);
  26320. }
  26321. // Recombine
  26322. return this._recombineShader(root);
  26323. };
  26324. return Effect;
  26325. }());
  26326. Effect._uniqueIdSeed = 0;
  26327. // Statics
  26328. Effect.ShadersStore = {};
  26329. Effect.IncludesShadersStore = {};
  26330. BABYLON.Effect = Effect;
  26331. })(BABYLON || (BABYLON = {}));
  26332. //# sourceMappingURL=babylon.effect.js.map
  26333. var BABYLON;
  26334. (function (BABYLON) {
  26335. var MaterialHelper = (function () {
  26336. function MaterialHelper() {
  26337. }
  26338. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  26339. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26340. var lightIndex = 0;
  26341. var needNormals = false;
  26342. var needRebuild = false;
  26343. var needShadows = false;
  26344. var lightmapMode = false;
  26345. for (var index = 0; index < scene.lights.length; index++) {
  26346. var light = scene.lights[index];
  26347. if (!light.isEnabled()) {
  26348. continue;
  26349. }
  26350. // Excluded check
  26351. if (light._excludedMeshesIds.length > 0) {
  26352. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  26353. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  26354. if (excludedMesh) {
  26355. light.excludedMeshes.push(excludedMesh);
  26356. }
  26357. }
  26358. light._excludedMeshesIds = [];
  26359. }
  26360. // Included check
  26361. if (light._includedOnlyMeshesIds.length > 0) {
  26362. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  26363. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  26364. if (includedOnlyMesh) {
  26365. light.includedOnlyMeshes.push(includedOnlyMesh);
  26366. }
  26367. }
  26368. light._includedOnlyMeshesIds = [];
  26369. }
  26370. if (!light.canAffectMesh(mesh)) {
  26371. continue;
  26372. }
  26373. needNormals = true;
  26374. if (defines["LIGHT" + lightIndex] === undefined) {
  26375. needRebuild = true;
  26376. }
  26377. defines["LIGHT" + lightIndex] = true;
  26378. var type;
  26379. if (light instanceof BABYLON.SpotLight) {
  26380. type = "SPOTLIGHT" + lightIndex;
  26381. }
  26382. else if (light instanceof BABYLON.HemisphericLight) {
  26383. type = "HEMILIGHT" + lightIndex;
  26384. }
  26385. else if (light instanceof BABYLON.PointLight) {
  26386. type = "POINTLIGHT" + lightIndex;
  26387. }
  26388. else {
  26389. type = "DIRLIGHT" + lightIndex;
  26390. }
  26391. if (defines[type] === undefined) {
  26392. needRebuild = true;
  26393. }
  26394. defines[type] = true;
  26395. // Specular
  26396. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  26397. defines["SPECULARTERM"] = true;
  26398. }
  26399. // Shadows
  26400. if (scene.shadowsEnabled) {
  26401. var shadowGenerator = light.getShadowGenerator();
  26402. if (mesh && mesh.receiveShadows && shadowGenerator) {
  26403. if (defines["SHADOW" + lightIndex] === undefined) {
  26404. needRebuild = true;
  26405. }
  26406. defines["SHADOW" + lightIndex] = true;
  26407. defines["SHADOWS"] = true;
  26408. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  26409. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  26410. needRebuild = true;
  26411. }
  26412. defines["SHADOWVSM" + lightIndex] = true;
  26413. }
  26414. if (shadowGenerator.usePoissonSampling) {
  26415. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  26416. needRebuild = true;
  26417. }
  26418. defines["SHADOWPCF" + lightIndex] = true;
  26419. }
  26420. needShadows = true;
  26421. }
  26422. }
  26423. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26424. lightmapMode = true;
  26425. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  26426. needRebuild = true;
  26427. }
  26428. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  26429. needRebuild = true;
  26430. }
  26431. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26432. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  26433. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  26434. }
  26435. }
  26436. lightIndex++;
  26437. if (lightIndex === maxSimultaneousLights)
  26438. break;
  26439. }
  26440. var caps = scene.getEngine().getCaps();
  26441. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  26442. if (defines["SHADOWFULLFLOAT"] === undefined) {
  26443. needRebuild = true;
  26444. }
  26445. defines["SHADOWFULLFLOAT"] = true;
  26446. }
  26447. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  26448. needRebuild = true;
  26449. }
  26450. if (lightmapMode) {
  26451. defines["LIGHTMAPEXCLUDED"] = true;
  26452. }
  26453. if (needRebuild) {
  26454. defines.rebuild();
  26455. }
  26456. return needNormals;
  26457. };
  26458. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  26459. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26460. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26461. if (!defines["LIGHT" + lightIndex]) {
  26462. break;
  26463. }
  26464. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  26465. samplersList.push("shadowSampler" + lightIndex);
  26466. }
  26467. };
  26468. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26469. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26470. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26471. if (!defines["LIGHT" + lightIndex]) {
  26472. break;
  26473. }
  26474. if (lightIndex > 0) {
  26475. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26476. }
  26477. if (defines["SHADOW" + lightIndex]) {
  26478. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26479. }
  26480. if (defines["SHADOWPCF" + lightIndex]) {
  26481. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26482. }
  26483. if (defines["SHADOWVSM" + lightIndex]) {
  26484. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  26485. }
  26486. }
  26487. };
  26488. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26489. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26490. fallbacks.addCPUSkinningFallback(0, mesh);
  26491. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26492. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26493. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26496. }
  26497. }
  26498. };
  26499. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26500. if (defines["INSTANCES"]) {
  26501. attribs.push("world0");
  26502. attribs.push("world1");
  26503. attribs.push("world2");
  26504. attribs.push("world3");
  26505. }
  26506. };
  26507. // Bindings
  26508. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  26509. var shadowGenerator = light.getShadowGenerator();
  26510. if (mesh.receiveShadows && shadowGenerator) {
  26511. if (!light.needCube()) {
  26512. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  26513. }
  26514. else {
  26515. if (!depthValuesAlreadySet) {
  26516. depthValuesAlreadySet = true;
  26517. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  26518. }
  26519. }
  26520. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  26521. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  26522. }
  26523. return depthValuesAlreadySet;
  26524. };
  26525. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26526. if (light instanceof BABYLON.PointLight) {
  26527. // Point Light
  26528. light.transferToEffect(effect, "vLightData" + lightIndex);
  26529. }
  26530. else if (light instanceof BABYLON.DirectionalLight) {
  26531. // Directional Light
  26532. light.transferToEffect(effect, "vLightData" + lightIndex);
  26533. }
  26534. else if (light instanceof BABYLON.SpotLight) {
  26535. // Spot Light
  26536. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  26537. }
  26538. else if (light instanceof BABYLON.HemisphericLight) {
  26539. // Hemispheric Light
  26540. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  26541. }
  26542. };
  26543. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  26544. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26545. var lightIndex = 0;
  26546. var depthValuesAlreadySet = false;
  26547. for (var index = 0; index < scene.lights.length; index++) {
  26548. var light = scene.lights[index];
  26549. if (!light.isEnabled()) {
  26550. continue;
  26551. }
  26552. if (!light.canAffectMesh(mesh)) {
  26553. continue;
  26554. }
  26555. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26556. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  26557. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  26558. if (defines["SPECULARTERM"]) {
  26559. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  26560. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  26561. }
  26562. // Shadows
  26563. if (scene.shadowsEnabled) {
  26564. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  26565. }
  26566. lightIndex++;
  26567. if (lightIndex === maxSimultaneousLights)
  26568. break;
  26569. }
  26570. };
  26571. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26572. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26573. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26574. effect.setColor3("vFogColor", scene.fogColor);
  26575. }
  26576. };
  26577. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26578. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26579. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26580. if (matrices) {
  26581. effect.setMatrices("mBones", matrices);
  26582. }
  26583. }
  26584. };
  26585. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26586. if (defines["LOGARITHMICDEPTH"]) {
  26587. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26588. }
  26589. };
  26590. MaterialHelper.BindClipPlane = function (effect, scene) {
  26591. if (scene.clipPlane) {
  26592. var clipPlane = scene.clipPlane;
  26593. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26594. }
  26595. };
  26596. return MaterialHelper;
  26597. }());
  26598. BABYLON.MaterialHelper = MaterialHelper;
  26599. })(BABYLON || (BABYLON = {}));
  26600. //# sourceMappingURL=babylon.materialHelper.js.map
  26601. var BABYLON;
  26602. (function (BABYLON) {
  26603. var FresnelParameters = (function () {
  26604. function FresnelParameters() {
  26605. this.isEnabled = true;
  26606. this.leftColor = BABYLON.Color3.White();
  26607. this.rightColor = BABYLON.Color3.Black();
  26608. this.bias = 0;
  26609. this.power = 1;
  26610. }
  26611. FresnelParameters.prototype.clone = function () {
  26612. var newFresnelParameters = new FresnelParameters();
  26613. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  26614. return newFresnelParameters;
  26615. };
  26616. FresnelParameters.prototype.serialize = function () {
  26617. var serializationObject = {};
  26618. serializationObject.isEnabled = this.isEnabled;
  26619. serializationObject.leftColor = this.leftColor;
  26620. serializationObject.rightColor = this.rightColor;
  26621. serializationObject.bias = this.bias;
  26622. serializationObject.power = this.power;
  26623. return serializationObject;
  26624. };
  26625. FresnelParameters.Parse = function (parsedFresnelParameters) {
  26626. var fresnelParameters = new FresnelParameters();
  26627. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  26628. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  26629. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  26630. fresnelParameters.bias = parsedFresnelParameters.bias;
  26631. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  26632. return fresnelParameters;
  26633. };
  26634. return FresnelParameters;
  26635. }());
  26636. BABYLON.FresnelParameters = FresnelParameters;
  26637. })(BABYLON || (BABYLON = {}));
  26638. //# sourceMappingURL=babylon.fresnelParameters.js.map
  26639. var BABYLON;
  26640. (function (BABYLON) {
  26641. var MaterialDefines = (function () {
  26642. function MaterialDefines() {
  26643. }
  26644. MaterialDefines.prototype.rebuild = function () {
  26645. if (this._keys) {
  26646. delete this._keys;
  26647. }
  26648. this._keys = Object.keys(this);
  26649. };
  26650. MaterialDefines.prototype.isEqual = function (other) {
  26651. if (this._keys.length !== other._keys.length) {
  26652. return false;
  26653. }
  26654. for (var index = 0; index < this._keys.length; index++) {
  26655. var prop = this._keys[index];
  26656. if (this[prop] !== other[prop]) {
  26657. return false;
  26658. }
  26659. }
  26660. return true;
  26661. };
  26662. MaterialDefines.prototype.cloneTo = function (other) {
  26663. if (this._keys.length !== other._keys.length) {
  26664. other._keys = this._keys.slice(0);
  26665. }
  26666. for (var index = 0; index < this._keys.length; index++) {
  26667. var prop = this._keys[index];
  26668. other[prop] = this[prop];
  26669. }
  26670. };
  26671. MaterialDefines.prototype.reset = function () {
  26672. for (var index = 0; index < this._keys.length; index++) {
  26673. var prop = this._keys[index];
  26674. if (typeof (this[prop]) === "number") {
  26675. this[prop] = 0;
  26676. }
  26677. else {
  26678. this[prop] = false;
  26679. }
  26680. }
  26681. };
  26682. MaterialDefines.prototype.toString = function () {
  26683. var result = "";
  26684. for (var index = 0; index < this._keys.length; index++) {
  26685. var prop = this._keys[index];
  26686. if (typeof (this[prop]) === "number") {
  26687. result += "#define " + prop + " " + this[prop] + "\n";
  26688. }
  26689. else if (this[prop]) {
  26690. result += "#define " + prop + "\n";
  26691. }
  26692. }
  26693. return result;
  26694. };
  26695. return MaterialDefines;
  26696. }());
  26697. BABYLON.MaterialDefines = MaterialDefines;
  26698. var Material = (function () {
  26699. function Material(name, scene, doNotAdd) {
  26700. this.checkReadyOnEveryCall = false;
  26701. this.checkReadyOnlyOnce = false;
  26702. this.state = "";
  26703. this.alpha = 1.0;
  26704. this.backFaceCulling = true;
  26705. this.doNotSerialize = false;
  26706. /**
  26707. * An event triggered when the material is disposed.
  26708. * @type {BABYLON.Observable}
  26709. */
  26710. this.onDisposeObservable = new BABYLON.Observable();
  26711. /**
  26712. * An event triggered when the material is bound.
  26713. * @type {BABYLON.Observable}
  26714. */
  26715. this.onBindObservable = new BABYLON.Observable();
  26716. /**
  26717. * An event triggered when the material is unbound.
  26718. * @type {BABYLON.Observable}
  26719. */
  26720. this.onUnBindObservable = new BABYLON.Observable();
  26721. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26722. this.disableDepthWrite = false;
  26723. this.fogEnabled = true;
  26724. this.pointSize = 1.0;
  26725. this.zOffset = 0;
  26726. this._wasPreviouslyReady = false;
  26727. this._fillMode = Material.TriangleFillMode;
  26728. this.name = name;
  26729. this.id = name;
  26730. this._scene = scene;
  26731. if (scene.useRightHandedSystem) {
  26732. this.sideOrientation = Material.ClockWiseSideOrientation;
  26733. }
  26734. else {
  26735. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26736. }
  26737. if (!doNotAdd) {
  26738. scene.materials.push(this);
  26739. }
  26740. }
  26741. Object.defineProperty(Material, "TriangleFillMode", {
  26742. get: function () {
  26743. return Material._TriangleFillMode;
  26744. },
  26745. enumerable: true,
  26746. configurable: true
  26747. });
  26748. Object.defineProperty(Material, "WireFrameFillMode", {
  26749. get: function () {
  26750. return Material._WireFrameFillMode;
  26751. },
  26752. enumerable: true,
  26753. configurable: true
  26754. });
  26755. Object.defineProperty(Material, "PointFillMode", {
  26756. get: function () {
  26757. return Material._PointFillMode;
  26758. },
  26759. enumerable: true,
  26760. configurable: true
  26761. });
  26762. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26763. get: function () {
  26764. return Material._ClockWiseSideOrientation;
  26765. },
  26766. enumerable: true,
  26767. configurable: true
  26768. });
  26769. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26770. get: function () {
  26771. return Material._CounterClockWiseSideOrientation;
  26772. },
  26773. enumerable: true,
  26774. configurable: true
  26775. });
  26776. Object.defineProperty(Material.prototype, "onDispose", {
  26777. set: function (callback) {
  26778. if (this._onDisposeObserver) {
  26779. this.onDisposeObservable.remove(this._onDisposeObserver);
  26780. }
  26781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26782. },
  26783. enumerable: true,
  26784. configurable: true
  26785. });
  26786. Object.defineProperty(Material.prototype, "onBind", {
  26787. set: function (callback) {
  26788. if (this._onBindObserver) {
  26789. this.onBindObservable.remove(this._onBindObserver);
  26790. }
  26791. this._onBindObserver = this.onBindObservable.add(callback);
  26792. },
  26793. enumerable: true,
  26794. configurable: true
  26795. });
  26796. Object.defineProperty(Material.prototype, "wireframe", {
  26797. get: function () {
  26798. return this._fillMode === Material.WireFrameFillMode;
  26799. },
  26800. set: function (value) {
  26801. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26802. },
  26803. enumerable: true,
  26804. configurable: true
  26805. });
  26806. Object.defineProperty(Material.prototype, "pointsCloud", {
  26807. get: function () {
  26808. return this._fillMode === Material.PointFillMode;
  26809. },
  26810. set: function (value) {
  26811. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26812. },
  26813. enumerable: true,
  26814. configurable: true
  26815. });
  26816. Object.defineProperty(Material.prototype, "fillMode", {
  26817. get: function () {
  26818. return this._fillMode;
  26819. },
  26820. set: function (value) {
  26821. this._fillMode = value;
  26822. },
  26823. enumerable: true,
  26824. configurable: true
  26825. });
  26826. /**
  26827. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26828. * subclasses should override adding information pertainent to themselves
  26829. */
  26830. Material.prototype.toString = function (fullDetails) {
  26831. var ret = "Name: " + this.name;
  26832. if (fullDetails) {
  26833. }
  26834. return ret;
  26835. };
  26836. Material.prototype.getClassName = function () {
  26837. return "Material";
  26838. };
  26839. Object.defineProperty(Material.prototype, "isFrozen", {
  26840. get: function () {
  26841. return this.checkReadyOnlyOnce;
  26842. },
  26843. enumerable: true,
  26844. configurable: true
  26845. });
  26846. Material.prototype.freeze = function () {
  26847. this.checkReadyOnlyOnce = true;
  26848. };
  26849. Material.prototype.unfreeze = function () {
  26850. this.checkReadyOnlyOnce = false;
  26851. };
  26852. Material.prototype.isReady = function (mesh, useInstances) {
  26853. return true;
  26854. };
  26855. Material.prototype.getEffect = function () {
  26856. return this._effect;
  26857. };
  26858. Material.prototype.getScene = function () {
  26859. return this._scene;
  26860. };
  26861. Material.prototype.needAlphaBlending = function () {
  26862. return (this.alpha < 1.0);
  26863. };
  26864. Material.prototype.needAlphaTesting = function () {
  26865. return false;
  26866. };
  26867. Material.prototype.getAlphaTestTexture = function () {
  26868. return null;
  26869. };
  26870. Material.prototype.markDirty = function () {
  26871. this._wasPreviouslyReady = false;
  26872. };
  26873. Material.prototype._preBind = function () {
  26874. var engine = this._scene.getEngine();
  26875. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26876. engine.enableEffect(this._effect);
  26877. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26878. };
  26879. Material.prototype.bind = function (world, mesh) {
  26880. this._scene._cachedMaterial = this;
  26881. this.onBindObservable.notifyObservers(mesh);
  26882. if (this.disableDepthWrite) {
  26883. var engine = this._scene.getEngine();
  26884. this._cachedDepthWriteState = engine.getDepthWrite();
  26885. engine.setDepthWrite(false);
  26886. }
  26887. };
  26888. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26889. };
  26890. Material.prototype.unbind = function () {
  26891. this.onUnBindObservable.notifyObservers(this);
  26892. if (this.disableDepthWrite) {
  26893. var engine = this._scene.getEngine();
  26894. engine.setDepthWrite(this._cachedDepthWriteState);
  26895. }
  26896. };
  26897. Material.prototype.clone = function (name) {
  26898. return null;
  26899. };
  26900. Material.prototype.getBindedMeshes = function () {
  26901. var result = new Array();
  26902. for (var index = 0; index < this._scene.meshes.length; index++) {
  26903. var mesh = this._scene.meshes[index];
  26904. if (mesh.material === this) {
  26905. result.push(mesh);
  26906. }
  26907. }
  26908. return result;
  26909. };
  26910. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26911. // Animations
  26912. this.getScene().stopAnimation(this);
  26913. // Remove from scene
  26914. var index = this._scene.materials.indexOf(this);
  26915. if (index >= 0) {
  26916. this._scene.materials.splice(index, 1);
  26917. }
  26918. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26919. if (forceDisposeEffect && this._effect) {
  26920. this._scene.getEngine()._releaseEffect(this._effect);
  26921. this._effect = null;
  26922. }
  26923. // Remove from meshes
  26924. for (index = 0; index < this._scene.meshes.length; index++) {
  26925. var mesh = this._scene.meshes[index];
  26926. if (mesh.material === this) {
  26927. mesh.material = null;
  26928. }
  26929. }
  26930. // Callback
  26931. this.onDisposeObservable.notifyObservers(this);
  26932. this.onDisposeObservable.clear();
  26933. this.onBindObservable.clear();
  26934. this.onUnBindObservable.clear();
  26935. };
  26936. Material.prototype.serialize = function () {
  26937. return BABYLON.SerializationHelper.Serialize(this);
  26938. };
  26939. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26940. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26941. multiMaterial.id = parsedMultiMaterial.id;
  26942. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26943. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26944. var subMatId = parsedMultiMaterial.materials[matIndex];
  26945. if (subMatId) {
  26946. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26947. }
  26948. else {
  26949. multiMaterial.subMaterials.push(null);
  26950. }
  26951. }
  26952. return multiMaterial;
  26953. };
  26954. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26955. if (!parsedMaterial.customType) {
  26956. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26957. }
  26958. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26959. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26960. ;
  26961. };
  26962. return Material;
  26963. }());
  26964. Material._TriangleFillMode = 0;
  26965. Material._WireFrameFillMode = 1;
  26966. Material._PointFillMode = 2;
  26967. Material._ClockWiseSideOrientation = 0;
  26968. Material._CounterClockWiseSideOrientation = 1;
  26969. __decorate([
  26970. BABYLON.serialize()
  26971. ], Material.prototype, "id", void 0);
  26972. __decorate([
  26973. BABYLON.serialize()
  26974. ], Material.prototype, "name", void 0);
  26975. __decorate([
  26976. BABYLON.serialize()
  26977. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26978. __decorate([
  26979. BABYLON.serialize()
  26980. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26981. __decorate([
  26982. BABYLON.serialize()
  26983. ], Material.prototype, "state", void 0);
  26984. __decorate([
  26985. BABYLON.serialize()
  26986. ], Material.prototype, "alpha", void 0);
  26987. __decorate([
  26988. BABYLON.serialize()
  26989. ], Material.prototype, "backFaceCulling", void 0);
  26990. __decorate([
  26991. BABYLON.serialize()
  26992. ], Material.prototype, "sideOrientation", void 0);
  26993. __decorate([
  26994. BABYLON.serialize()
  26995. ], Material.prototype, "alphaMode", void 0);
  26996. __decorate([
  26997. BABYLON.serialize()
  26998. ], Material.prototype, "disableDepthWrite", void 0);
  26999. __decorate([
  27000. BABYLON.serialize()
  27001. ], Material.prototype, "fogEnabled", void 0);
  27002. __decorate([
  27003. BABYLON.serialize()
  27004. ], Material.prototype, "pointSize", void 0);
  27005. __decorate([
  27006. BABYLON.serialize()
  27007. ], Material.prototype, "zOffset", void 0);
  27008. __decorate([
  27009. BABYLON.serialize()
  27010. ], Material.prototype, "wireframe", null);
  27011. __decorate([
  27012. BABYLON.serialize()
  27013. ], Material.prototype, "pointsCloud", null);
  27014. __decorate([
  27015. BABYLON.serialize()
  27016. ], Material.prototype, "fillMode", null);
  27017. BABYLON.Material = Material;
  27018. })(BABYLON || (BABYLON = {}));
  27019. //# sourceMappingURL=babylon.material.js.map
  27020. var BABYLON;
  27021. (function (BABYLON) {
  27022. var StandardMaterialDefines = (function (_super) {
  27023. __extends(StandardMaterialDefines, _super);
  27024. function StandardMaterialDefines() {
  27025. var _this = _super.call(this) || this;
  27026. _this.DIFFUSE = false;
  27027. _this.AMBIENT = false;
  27028. _this.OPACITY = false;
  27029. _this.OPACITYRGB = false;
  27030. _this.REFLECTION = false;
  27031. _this.EMISSIVE = false;
  27032. _this.SPECULAR = false;
  27033. _this.BUMP = false;
  27034. _this.PARALLAX = false;
  27035. _this.PARALLAXOCCLUSION = false;
  27036. _this.SPECULAROVERALPHA = false;
  27037. _this.CLIPPLANE = false;
  27038. _this.ALPHATEST = false;
  27039. _this.ALPHAFROMDIFFUSE = false;
  27040. _this.POINTSIZE = false;
  27041. _this.FOG = false;
  27042. _this.SPECULARTERM = false;
  27043. _this.DIFFUSEFRESNEL = false;
  27044. _this.OPACITYFRESNEL = false;
  27045. _this.REFLECTIONFRESNEL = false;
  27046. _this.REFRACTIONFRESNEL = false;
  27047. _this.EMISSIVEFRESNEL = false;
  27048. _this.FRESNEL = false;
  27049. _this.NORMAL = false;
  27050. _this.UV1 = false;
  27051. _this.UV2 = false;
  27052. _this.VERTEXCOLOR = false;
  27053. _this.VERTEXALPHA = false;
  27054. _this.NUM_BONE_INFLUENCERS = 0;
  27055. _this.BonesPerMesh = 0;
  27056. _this.INSTANCES = false;
  27057. _this.GLOSSINESS = false;
  27058. _this.ROUGHNESS = false;
  27059. _this.EMISSIVEASILLUMINATION = false;
  27060. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27061. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27062. _this.LIGHTMAP = false;
  27063. _this.USELIGHTMAPASSHADOWMAP = false;
  27064. _this.REFLECTIONMAP_3D = false;
  27065. _this.REFLECTIONMAP_SPHERICAL = false;
  27066. _this.REFLECTIONMAP_PLANAR = false;
  27067. _this.REFLECTIONMAP_CUBIC = false;
  27068. _this.REFLECTIONMAP_PROJECTION = false;
  27069. _this.REFLECTIONMAP_SKYBOX = false;
  27070. _this.REFLECTIONMAP_EXPLICIT = false;
  27071. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27072. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27073. _this.INVERTCUBICMAP = false;
  27074. _this.LOGARITHMICDEPTH = false;
  27075. _this.REFRACTION = false;
  27076. _this.REFRACTIONMAP_3D = false;
  27077. _this.REFLECTIONOVERALPHA = false;
  27078. _this.INVERTNORMALMAPX = false;
  27079. _this.INVERTNORMALMAPY = false;
  27080. _this.SHADOWFULLFLOAT = false;
  27081. _this.CAMERACOLORGRADING = false;
  27082. _this.CAMERACOLORCURVES = false;
  27083. _this.rebuild();
  27084. return _this;
  27085. }
  27086. return StandardMaterialDefines;
  27087. }(BABYLON.MaterialDefines));
  27088. var StandardMaterial = (function (_super) {
  27089. __extends(StandardMaterial, _super);
  27090. function StandardMaterial(name, scene) {
  27091. var _this = _super.call(this, name, scene) || this;
  27092. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27093. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27094. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27095. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27096. _this.specularPower = 64;
  27097. _this.useAlphaFromDiffuseTexture = false;
  27098. _this.useEmissiveAsIllumination = false;
  27099. _this.linkEmissiveWithDiffuse = false;
  27100. _this.useReflectionFresnelFromSpecular = false;
  27101. _this.useSpecularOverAlpha = false;
  27102. _this.useReflectionOverAlpha = false;
  27103. _this.disableLighting = false;
  27104. _this.useParallax = false;
  27105. _this.useParallaxOcclusion = false;
  27106. _this.parallaxScaleBias = 0.05;
  27107. _this.roughness = 0;
  27108. _this.indexOfRefraction = 0.98;
  27109. _this.invertRefractionY = true;
  27110. _this.useLightmapAsShadowmap = false;
  27111. _this.useGlossinessFromSpecularMapAlpha = false;
  27112. _this.maxSimultaneousLights = 4;
  27113. /**
  27114. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27115. */
  27116. _this.invertNormalMapX = false;
  27117. /**
  27118. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27119. */
  27120. _this.invertNormalMapY = false;
  27121. /**
  27122. * Color Grading 2D Lookup Texture.
  27123. * This allows special effects like sepia, black and white to sixties rendering style.
  27124. */
  27125. _this.cameraColorGradingTexture = null;
  27126. /**
  27127. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27128. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27129. * 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;
  27130. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27131. */
  27132. _this.cameraColorCurves = null;
  27133. _this._renderTargets = new BABYLON.SmartArray(16);
  27134. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27135. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27136. _this._defines = new StandardMaterialDefines();
  27137. _this._cachedDefines = new StandardMaterialDefines();
  27138. _this._cachedDefines.BonesPerMesh = -1;
  27139. _this.getRenderTargetTextures = function () {
  27140. _this._renderTargets.reset();
  27141. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27142. _this._renderTargets.push(_this.reflectionTexture);
  27143. }
  27144. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27145. _this._renderTargets.push(_this.refractionTexture);
  27146. }
  27147. return _this._renderTargets;
  27148. };
  27149. return _this;
  27150. }
  27151. StandardMaterial.prototype.getClassName = function () {
  27152. return "StandardMaterial";
  27153. };
  27154. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27155. get: function () {
  27156. return this._useLogarithmicDepth;
  27157. },
  27158. set: function (value) {
  27159. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27160. },
  27161. enumerable: true,
  27162. configurable: true
  27163. });
  27164. StandardMaterial.prototype.needAlphaBlending = function () {
  27165. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27166. };
  27167. StandardMaterial.prototype.needAlphaTesting = function () {
  27168. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  27169. };
  27170. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27171. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  27172. };
  27173. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27174. return this.diffuseTexture;
  27175. };
  27176. // Methods
  27177. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27178. if (!mesh) {
  27179. return true;
  27180. }
  27181. if (this._defines.INSTANCES !== useInstances) {
  27182. return false;
  27183. }
  27184. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  27185. return true;
  27186. }
  27187. return false;
  27188. };
  27189. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  27190. if (this.isFrozen) {
  27191. if (this._wasPreviouslyReady) {
  27192. return true;
  27193. }
  27194. }
  27195. var scene = this.getScene();
  27196. var engine = scene.getEngine();
  27197. var needUVs = false;
  27198. var needNormals = false;
  27199. this._defines.reset();
  27200. // Lights
  27201. if (scene.lightsEnabled && !this.disableLighting) {
  27202. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  27203. }
  27204. if (!this.checkReadyOnEveryCall) {
  27205. if (this._renderId === scene.getRenderId()) {
  27206. if (this._checkCache(scene, mesh, useInstances)) {
  27207. return true;
  27208. }
  27209. }
  27210. }
  27211. // Textures
  27212. if (scene.texturesEnabled) {
  27213. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27214. if (!this.diffuseTexture.isReady()) {
  27215. return false;
  27216. }
  27217. else {
  27218. needUVs = true;
  27219. this._defines.DIFFUSE = true;
  27220. }
  27221. }
  27222. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27223. if (!this.ambientTexture.isReady()) {
  27224. return false;
  27225. }
  27226. else {
  27227. needUVs = true;
  27228. this._defines.AMBIENT = true;
  27229. }
  27230. }
  27231. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27232. if (!this.opacityTexture.isReady()) {
  27233. return false;
  27234. }
  27235. else {
  27236. needUVs = true;
  27237. this._defines.OPACITY = true;
  27238. if (this.opacityTexture.getAlphaFromRGB) {
  27239. this._defines.OPACITYRGB = true;
  27240. }
  27241. }
  27242. }
  27243. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27244. if (!this.reflectionTexture.isReady()) {
  27245. return false;
  27246. }
  27247. else {
  27248. needNormals = true;
  27249. this._defines.REFLECTION = true;
  27250. if (this.roughness > 0) {
  27251. this._defines.ROUGHNESS = true;
  27252. }
  27253. if (this.useReflectionOverAlpha) {
  27254. this._defines.REFLECTIONOVERALPHA = true;
  27255. }
  27256. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  27257. this._defines.INVERTCUBICMAP = true;
  27258. }
  27259. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  27260. switch (this.reflectionTexture.coordinatesMode) {
  27261. case BABYLON.Texture.CUBIC_MODE:
  27262. case BABYLON.Texture.INVCUBIC_MODE:
  27263. this._defines.REFLECTIONMAP_CUBIC = true;
  27264. break;
  27265. case BABYLON.Texture.EXPLICIT_MODE:
  27266. this._defines.REFLECTIONMAP_EXPLICIT = true;
  27267. break;
  27268. case BABYLON.Texture.PLANAR_MODE:
  27269. this._defines.REFLECTIONMAP_PLANAR = true;
  27270. break;
  27271. case BABYLON.Texture.PROJECTION_MODE:
  27272. this._defines.REFLECTIONMAP_PROJECTION = true;
  27273. break;
  27274. case BABYLON.Texture.SKYBOX_MODE:
  27275. this._defines.REFLECTIONMAP_SKYBOX = true;
  27276. break;
  27277. case BABYLON.Texture.SPHERICAL_MODE:
  27278. this._defines.REFLECTIONMAP_SPHERICAL = true;
  27279. break;
  27280. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27281. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  27282. break;
  27283. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27284. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  27285. break;
  27286. }
  27287. }
  27288. }
  27289. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27290. if (!this.emissiveTexture.isReady()) {
  27291. return false;
  27292. }
  27293. else {
  27294. needUVs = true;
  27295. this._defines.EMISSIVE = true;
  27296. }
  27297. }
  27298. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27299. if (!this.lightmapTexture.isReady()) {
  27300. return false;
  27301. }
  27302. else {
  27303. needUVs = true;
  27304. this._defines.LIGHTMAP = true;
  27305. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  27306. }
  27307. }
  27308. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27309. if (!this.specularTexture.isReady()) {
  27310. return false;
  27311. }
  27312. else {
  27313. needUVs = true;
  27314. this._defines.SPECULAR = true;
  27315. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  27316. }
  27317. }
  27318. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27319. if (!this.bumpTexture.isReady()) {
  27320. return false;
  27321. }
  27322. else {
  27323. needUVs = true;
  27324. this._defines.BUMP = true;
  27325. if (this.useParallax) {
  27326. this._defines.PARALLAX = true;
  27327. if (this.useParallaxOcclusion) {
  27328. this._defines.PARALLAXOCCLUSION = true;
  27329. }
  27330. }
  27331. if (this.invertNormalMapX) {
  27332. this._defines.INVERTNORMALMAPX = true;
  27333. }
  27334. if (this.invertNormalMapY) {
  27335. this._defines.INVERTNORMALMAPY = true;
  27336. }
  27337. if (scene._mirroredCameraPosition) {
  27338. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  27339. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  27340. }
  27341. }
  27342. }
  27343. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27344. if (!this.refractionTexture.isReady()) {
  27345. return false;
  27346. }
  27347. else {
  27348. needUVs = true;
  27349. this._defines.REFRACTION = true;
  27350. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  27351. }
  27352. }
  27353. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27354. if (!this.cameraColorGradingTexture.isReady()) {
  27355. return false;
  27356. }
  27357. else {
  27358. this._defines.CAMERACOLORGRADING = true;
  27359. }
  27360. }
  27361. }
  27362. // Effect
  27363. if (scene.clipPlane) {
  27364. this._defines.CLIPPLANE = true;
  27365. }
  27366. if (engine.getAlphaTesting()) {
  27367. this._defines.ALPHATEST = true;
  27368. }
  27369. if (this._shouldUseAlphaFromDiffuseTexture()) {
  27370. this._defines.ALPHAFROMDIFFUSE = true;
  27371. }
  27372. if (this.useEmissiveAsIllumination) {
  27373. this._defines.EMISSIVEASILLUMINATION = true;
  27374. }
  27375. if (this.linkEmissiveWithDiffuse) {
  27376. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  27377. }
  27378. if (this.useLogarithmicDepth) {
  27379. this._defines.LOGARITHMICDEPTH = true;
  27380. }
  27381. if (this.cameraColorCurves) {
  27382. this._defines.CAMERACOLORCURVES = true;
  27383. }
  27384. // Point size
  27385. if (this.pointsCloud || scene.forcePointsCloud) {
  27386. this._defines.POINTSIZE = true;
  27387. }
  27388. // Fog
  27389. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27390. this._defines.FOG = true;
  27391. }
  27392. if (StandardMaterial.FresnelEnabled) {
  27393. // Fresnel
  27394. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  27395. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  27396. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  27397. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  27398. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27399. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27400. this._defines.DIFFUSEFRESNEL = true;
  27401. }
  27402. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27403. this._defines.OPACITYFRESNEL = true;
  27404. }
  27405. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27406. this._defines.REFLECTIONFRESNEL = true;
  27407. if (this.useReflectionFresnelFromSpecular) {
  27408. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  27409. }
  27410. }
  27411. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27412. this._defines.REFRACTIONFRESNEL = true;
  27413. }
  27414. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27415. this._defines.EMISSIVEFRESNEL = true;
  27416. }
  27417. needNormals = true;
  27418. this._defines.FRESNEL = true;
  27419. }
  27420. }
  27421. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  27422. this._defines.SPECULAROVERALPHA = true;
  27423. }
  27424. // Attribs
  27425. if (mesh) {
  27426. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27427. this._defines.NORMAL = true;
  27428. }
  27429. if (needUVs) {
  27430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27431. this._defines.UV1 = true;
  27432. }
  27433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27434. this._defines.UV2 = true;
  27435. }
  27436. }
  27437. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27438. this._defines.VERTEXCOLOR = true;
  27439. if (mesh.hasVertexAlpha) {
  27440. this._defines.VERTEXALPHA = true;
  27441. }
  27442. }
  27443. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  27444. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  27445. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  27446. }
  27447. // Instances
  27448. if (useInstances) {
  27449. this._defines.INSTANCES = true;
  27450. }
  27451. }
  27452. // Get correct effect
  27453. if (!this._defines.isEqual(this._cachedDefines)) {
  27454. this._defines.cloneTo(this._cachedDefines);
  27455. scene.resetCachedMaterial();
  27456. // Fallbacks
  27457. var fallbacks = new BABYLON.EffectFallbacks();
  27458. if (this._defines.REFLECTION) {
  27459. fallbacks.addFallback(0, "REFLECTION");
  27460. }
  27461. if (this._defines.SPECULAR) {
  27462. fallbacks.addFallback(0, "SPECULAR");
  27463. }
  27464. if (this._defines.BUMP) {
  27465. fallbacks.addFallback(0, "BUMP");
  27466. }
  27467. if (this._defines.PARALLAX) {
  27468. fallbacks.addFallback(1, "PARALLAX");
  27469. }
  27470. if (this._defines.PARALLAXOCCLUSION) {
  27471. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27472. }
  27473. if (this._defines.SPECULAROVERALPHA) {
  27474. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27475. }
  27476. if (this._defines.FOG) {
  27477. fallbacks.addFallback(1, "FOG");
  27478. }
  27479. if (this._defines.POINTSIZE) {
  27480. fallbacks.addFallback(0, "POINTSIZE");
  27481. }
  27482. if (this._defines.LOGARITHMICDEPTH) {
  27483. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27484. }
  27485. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  27486. if (this._defines.SPECULARTERM) {
  27487. fallbacks.addFallback(0, "SPECULARTERM");
  27488. }
  27489. if (this._defines.DIFFUSEFRESNEL) {
  27490. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27491. }
  27492. if (this._defines.OPACITYFRESNEL) {
  27493. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27494. }
  27495. if (this._defines.REFLECTIONFRESNEL) {
  27496. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27497. }
  27498. if (this._defines.EMISSIVEFRESNEL) {
  27499. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27500. }
  27501. if (this._defines.FRESNEL) {
  27502. fallbacks.addFallback(4, "FRESNEL");
  27503. }
  27504. //Attributes
  27505. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27506. if (this._defines.NORMAL) {
  27507. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27508. }
  27509. if (this._defines.UV1) {
  27510. attribs.push(BABYLON.VertexBuffer.UVKind);
  27511. }
  27512. if (this._defines.UV2) {
  27513. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27514. }
  27515. if (this._defines.VERTEXCOLOR) {
  27516. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27517. }
  27518. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  27519. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  27520. var shaderName = "default";
  27521. var join = this._defines.toString();
  27522. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27523. "vFogInfos", "vFogColor", "pointSize",
  27524. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27525. "mBones",
  27526. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27527. "depthValues",
  27528. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27529. "logarithmicDepthConstant"
  27530. ];
  27531. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27532. if (this._defines.CAMERACOLORCURVES) {
  27533. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27534. }
  27535. if (this._defines.CAMERACOLORGRADING) {
  27536. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27537. }
  27538. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  27539. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  27540. }
  27541. if (!this._effect.isReady()) {
  27542. return false;
  27543. }
  27544. this._renderId = scene.getRenderId();
  27545. this._wasPreviouslyReady = true;
  27546. if (mesh) {
  27547. if (!mesh._materialDefines) {
  27548. mesh._materialDefines = new StandardMaterialDefines();
  27549. }
  27550. this._defines.cloneTo(mesh._materialDefines);
  27551. }
  27552. return true;
  27553. };
  27554. StandardMaterial.prototype.unbind = function () {
  27555. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  27556. this._effect.setTexture("reflection2DSampler", null);
  27557. }
  27558. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  27559. this._effect.setTexture("refraction2DSampler", null);
  27560. }
  27561. _super.prototype.unbind.call(this);
  27562. };
  27563. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27564. this._effect.setMatrix("world", world);
  27565. };
  27566. StandardMaterial.prototype.bind = function (world, mesh) {
  27567. var scene = this.getScene();
  27568. // Matrices
  27569. this.bindOnlyWorldMatrix(world);
  27570. // Bones
  27571. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  27572. if (scene.getCachedMaterial() !== this) {
  27573. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27574. if (StandardMaterial.FresnelEnabled) {
  27575. // Fresnel
  27576. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27577. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27578. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27579. }
  27580. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27581. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27582. }
  27583. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27584. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27585. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27586. }
  27587. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27588. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27589. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27590. }
  27591. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27592. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27593. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27594. }
  27595. }
  27596. // Textures
  27597. if (scene.texturesEnabled) {
  27598. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27599. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  27600. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  27601. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  27602. }
  27603. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27604. this._effect.setTexture("ambientSampler", this.ambientTexture);
  27605. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  27606. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  27607. }
  27608. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27609. this._effect.setTexture("opacitySampler", this.opacityTexture);
  27610. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  27611. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  27612. }
  27613. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27614. if (this.reflectionTexture.isCube) {
  27615. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  27616. }
  27617. else {
  27618. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  27619. }
  27620. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  27621. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  27622. }
  27623. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27624. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  27625. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  27626. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  27627. }
  27628. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27629. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  27630. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  27631. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  27632. }
  27633. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27634. this._effect.setTexture("specularSampler", this.specularTexture);
  27635. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  27636. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  27637. }
  27638. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27639. this._effect.setTexture("bumpSampler", this.bumpTexture);
  27640. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  27641. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  27642. }
  27643. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27644. var depth = 1.0;
  27645. if (this.refractionTexture.isCube) {
  27646. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  27647. }
  27648. else {
  27649. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  27650. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  27651. if (this.refractionTexture.depth) {
  27652. depth = this.refractionTexture.depth;
  27653. }
  27654. }
  27655. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27656. }
  27657. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27658. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  27659. }
  27660. }
  27661. // Clip plane
  27662. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  27663. // Point size
  27664. if (this.pointsCloud) {
  27665. this._effect.setFloat("pointSize", this.pointSize);
  27666. }
  27667. // Colors
  27668. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27669. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27670. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27671. if (this._defines.SPECULARTERM) {
  27672. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27673. }
  27674. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27675. }
  27676. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27677. // Diffuse
  27678. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27679. // Lights
  27680. if (scene.lightsEnabled && !this.disableLighting) {
  27681. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27682. }
  27683. // View
  27684. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27685. this._effect.setMatrix("view", scene.getViewMatrix());
  27686. }
  27687. // Fog
  27688. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27689. // Log. depth
  27690. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27691. // Color Curves
  27692. if (this.cameraColorCurves) {
  27693. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27694. }
  27695. }
  27696. _super.prototype.bind.call(this, world, mesh);
  27697. };
  27698. StandardMaterial.prototype.getAnimatables = function () {
  27699. var results = [];
  27700. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27701. results.push(this.diffuseTexture);
  27702. }
  27703. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27704. results.push(this.ambientTexture);
  27705. }
  27706. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27707. results.push(this.opacityTexture);
  27708. }
  27709. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27710. results.push(this.reflectionTexture);
  27711. }
  27712. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27713. results.push(this.emissiveTexture);
  27714. }
  27715. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27716. results.push(this.specularTexture);
  27717. }
  27718. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27719. results.push(this.bumpTexture);
  27720. }
  27721. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27722. results.push(this.lightmapTexture);
  27723. }
  27724. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27725. results.push(this.refractionTexture);
  27726. }
  27727. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27728. results.push(this.cameraColorGradingTexture);
  27729. }
  27730. return results;
  27731. };
  27732. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27733. if (forceDisposeTextures) {
  27734. if (this.diffuseTexture) {
  27735. this.diffuseTexture.dispose();
  27736. }
  27737. if (this.ambientTexture) {
  27738. this.ambientTexture.dispose();
  27739. }
  27740. if (this.opacityTexture) {
  27741. this.opacityTexture.dispose();
  27742. }
  27743. if (this.reflectionTexture) {
  27744. this.reflectionTexture.dispose();
  27745. }
  27746. if (this.emissiveTexture) {
  27747. this.emissiveTexture.dispose();
  27748. }
  27749. if (this.specularTexture) {
  27750. this.specularTexture.dispose();
  27751. }
  27752. if (this.bumpTexture) {
  27753. this.bumpTexture.dispose();
  27754. }
  27755. if (this.lightmapTexture) {
  27756. this.lightmapTexture.dispose();
  27757. }
  27758. if (this.refractionTexture) {
  27759. this.refractionTexture.dispose();
  27760. }
  27761. if (this.cameraColorGradingTexture) {
  27762. this.cameraColorGradingTexture.dispose();
  27763. }
  27764. }
  27765. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27766. };
  27767. StandardMaterial.prototype.clone = function (name) {
  27768. var _this = this;
  27769. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27770. };
  27771. StandardMaterial.prototype.serialize = function () {
  27772. return BABYLON.SerializationHelper.Serialize(this);
  27773. };
  27774. // Statics
  27775. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27776. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27777. };
  27778. return StandardMaterial;
  27779. }(BABYLON.Material));
  27780. // Flags used to enable or disable a type of texture for all Standard Materials
  27781. StandardMaterial.DiffuseTextureEnabled = true;
  27782. StandardMaterial.AmbientTextureEnabled = true;
  27783. StandardMaterial.OpacityTextureEnabled = true;
  27784. StandardMaterial.ReflectionTextureEnabled = true;
  27785. StandardMaterial.EmissiveTextureEnabled = true;
  27786. StandardMaterial.SpecularTextureEnabled = true;
  27787. StandardMaterial.BumpTextureEnabled = true;
  27788. StandardMaterial.FresnelEnabled = true;
  27789. StandardMaterial.LightmapTextureEnabled = true;
  27790. StandardMaterial.RefractionTextureEnabled = true;
  27791. StandardMaterial.ColorGradingTextureEnabled = true;
  27792. __decorate([
  27793. BABYLON.serializeAsTexture()
  27794. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27795. __decorate([
  27796. BABYLON.serializeAsTexture()
  27797. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27798. __decorate([
  27799. BABYLON.serializeAsTexture()
  27800. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27801. __decorate([
  27802. BABYLON.serializeAsTexture()
  27803. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27804. __decorate([
  27805. BABYLON.serializeAsTexture()
  27806. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27807. __decorate([
  27808. BABYLON.serializeAsTexture()
  27809. ], StandardMaterial.prototype, "specularTexture", void 0);
  27810. __decorate([
  27811. BABYLON.serializeAsTexture()
  27812. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27813. __decorate([
  27814. BABYLON.serializeAsTexture()
  27815. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27816. __decorate([
  27817. BABYLON.serializeAsTexture()
  27818. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27819. __decorate([
  27820. BABYLON.serializeAsColor3("ambient")
  27821. ], StandardMaterial.prototype, "ambientColor", void 0);
  27822. __decorate([
  27823. BABYLON.serializeAsColor3("diffuse")
  27824. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27825. __decorate([
  27826. BABYLON.serializeAsColor3("specular")
  27827. ], StandardMaterial.prototype, "specularColor", void 0);
  27828. __decorate([
  27829. BABYLON.serializeAsColor3("emissive")
  27830. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27831. __decorate([
  27832. BABYLON.serialize()
  27833. ], StandardMaterial.prototype, "specularPower", void 0);
  27834. __decorate([
  27835. BABYLON.serialize()
  27836. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27837. __decorate([
  27838. BABYLON.serialize()
  27839. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27840. __decorate([
  27841. BABYLON.serialize()
  27842. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27843. __decorate([
  27844. BABYLON.serialize()
  27845. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27846. __decorate([
  27847. BABYLON.serialize()
  27848. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27849. __decorate([
  27850. BABYLON.serialize()
  27851. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27852. __decorate([
  27853. BABYLON.serialize()
  27854. ], StandardMaterial.prototype, "disableLighting", void 0);
  27855. __decorate([
  27856. BABYLON.serialize()
  27857. ], StandardMaterial.prototype, "useParallax", void 0);
  27858. __decorate([
  27859. BABYLON.serialize()
  27860. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27861. __decorate([
  27862. BABYLON.serialize()
  27863. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27864. __decorate([
  27865. BABYLON.serialize()
  27866. ], StandardMaterial.prototype, "roughness", void 0);
  27867. __decorate([
  27868. BABYLON.serialize()
  27869. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27870. __decorate([
  27871. BABYLON.serialize()
  27872. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27873. __decorate([
  27874. BABYLON.serialize()
  27875. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27876. __decorate([
  27877. BABYLON.serializeAsFresnelParameters()
  27878. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27879. __decorate([
  27880. BABYLON.serializeAsFresnelParameters()
  27881. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27882. __decorate([
  27883. BABYLON.serializeAsFresnelParameters()
  27884. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27885. __decorate([
  27886. BABYLON.serializeAsFresnelParameters()
  27887. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27888. __decorate([
  27889. BABYLON.serializeAsFresnelParameters()
  27890. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27891. __decorate([
  27892. BABYLON.serialize()
  27893. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27894. __decorate([
  27895. BABYLON.serialize()
  27896. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27897. __decorate([
  27898. BABYLON.serialize()
  27899. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27900. __decorate([
  27901. BABYLON.serialize()
  27902. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27903. __decorate([
  27904. BABYLON.serializeAsTexture()
  27905. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27906. __decorate([
  27907. BABYLON.serializeAsColorCurves()
  27908. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27909. __decorate([
  27910. BABYLON.serialize()
  27911. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27912. BABYLON.StandardMaterial = StandardMaterial;
  27913. })(BABYLON || (BABYLON = {}));
  27914. //# sourceMappingURL=babylon.standardMaterial.js.map
  27915. var BABYLON;
  27916. (function (BABYLON) {
  27917. var MultiMaterial = (function (_super) {
  27918. __extends(MultiMaterial, _super);
  27919. function MultiMaterial(name, scene) {
  27920. var _this = _super.call(this, name, scene, true) || this;
  27921. _this.subMaterials = new Array();
  27922. scene.multiMaterials.push(_this);
  27923. return _this;
  27924. }
  27925. // Properties
  27926. MultiMaterial.prototype.getSubMaterial = function (index) {
  27927. if (index < 0 || index >= this.subMaterials.length) {
  27928. return this.getScene().defaultMaterial;
  27929. }
  27930. return this.subMaterials[index];
  27931. };
  27932. // Methods
  27933. MultiMaterial.prototype.getClassName = function () {
  27934. return "MultiMaterial";
  27935. };
  27936. MultiMaterial.prototype.isReady = function (mesh) {
  27937. for (var index = 0; index < this.subMaterials.length; index++) {
  27938. var subMaterial = this.subMaterials[index];
  27939. if (subMaterial) {
  27940. if (!this.subMaterials[index].isReady(mesh)) {
  27941. return false;
  27942. }
  27943. }
  27944. }
  27945. return true;
  27946. };
  27947. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27948. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27949. for (var index = 0; index < this.subMaterials.length; index++) {
  27950. var subMaterial = null;
  27951. if (cloneChildren) {
  27952. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27953. }
  27954. else {
  27955. subMaterial = this.subMaterials[index];
  27956. }
  27957. newMultiMaterial.subMaterials.push(subMaterial);
  27958. }
  27959. return newMultiMaterial;
  27960. };
  27961. MultiMaterial.prototype.serialize = function () {
  27962. var serializationObject = {};
  27963. serializationObject.name = this.name;
  27964. serializationObject.id = this.id;
  27965. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27966. serializationObject.materials = [];
  27967. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27968. var subMat = this.subMaterials[matIndex];
  27969. if (subMat) {
  27970. serializationObject.materials.push(subMat.id);
  27971. }
  27972. else {
  27973. serializationObject.materials.push(null);
  27974. }
  27975. }
  27976. return serializationObject;
  27977. };
  27978. return MultiMaterial;
  27979. }(BABYLON.Material));
  27980. BABYLON.MultiMaterial = MultiMaterial;
  27981. })(BABYLON || (BABYLON = {}));
  27982. //# sourceMappingURL=babylon.multiMaterial.js.map
  27983. var BABYLON;
  27984. (function (BABYLON) {
  27985. var SceneLoader = (function () {
  27986. function SceneLoader() {
  27987. }
  27988. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27989. get: function () {
  27990. return 0;
  27991. },
  27992. enumerable: true,
  27993. configurable: true
  27994. });
  27995. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27996. get: function () {
  27997. return 1;
  27998. },
  27999. enumerable: true,
  28000. configurable: true
  28001. });
  28002. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  28003. get: function () {
  28004. return 2;
  28005. },
  28006. enumerable: true,
  28007. configurable: true
  28008. });
  28009. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  28010. get: function () {
  28011. return 3;
  28012. },
  28013. enumerable: true,
  28014. configurable: true
  28015. });
  28016. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  28017. get: function () {
  28018. return SceneLoader._ForceFullSceneLoadingForIncremental;
  28019. },
  28020. set: function (value) {
  28021. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  28022. },
  28023. enumerable: true,
  28024. configurable: true
  28025. });
  28026. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  28027. get: function () {
  28028. return SceneLoader._ShowLoadingScreen;
  28029. },
  28030. set: function (value) {
  28031. SceneLoader._ShowLoadingScreen = value;
  28032. },
  28033. enumerable: true,
  28034. configurable: true
  28035. });
  28036. Object.defineProperty(SceneLoader, "loggingLevel", {
  28037. get: function () {
  28038. return SceneLoader._loggingLevel;
  28039. },
  28040. set: function (value) {
  28041. SceneLoader._loggingLevel = value;
  28042. },
  28043. enumerable: true,
  28044. configurable: true
  28045. });
  28046. SceneLoader._getDefaultPlugin = function () {
  28047. return SceneLoader._registeredPlugins[".babylon"];
  28048. };
  28049. SceneLoader._getPluginForExtension = function (extension) {
  28050. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  28051. if (registeredPlugin) {
  28052. return registeredPlugin;
  28053. }
  28054. return SceneLoader._getDefaultPlugin();
  28055. };
  28056. SceneLoader._getPluginForFilename = function (sceneFilename) {
  28057. if (sceneFilename.name) {
  28058. sceneFilename = sceneFilename.name;
  28059. }
  28060. var dotPosition = sceneFilename.lastIndexOf(".");
  28061. var queryStringPosition = sceneFilename.indexOf("?");
  28062. if (queryStringPosition === -1) {
  28063. queryStringPosition = sceneFilename.length;
  28064. }
  28065. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  28066. return SceneLoader._getPluginForExtension(extension);
  28067. };
  28068. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  28069. SceneLoader._getDirectLoad = function (sceneFilename) {
  28070. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  28071. return sceneFilename.substr(5);
  28072. }
  28073. return null;
  28074. };
  28075. // Public functions
  28076. SceneLoader.GetPluginForExtension = function (extension) {
  28077. return SceneLoader._getPluginForExtension(extension).plugin;
  28078. };
  28079. SceneLoader.RegisterPlugin = function (plugin) {
  28080. if (typeof plugin.extensions === "string") {
  28081. var extension = plugin.extensions;
  28082. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28083. plugin: plugin,
  28084. isBinary: false
  28085. };
  28086. }
  28087. else {
  28088. var extensions = plugin.extensions;
  28089. Object.keys(extensions).forEach(function (extension) {
  28090. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28091. plugin: plugin,
  28092. isBinary: extensions[extension].isBinary
  28093. };
  28094. });
  28095. }
  28096. };
  28097. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28098. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28099. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28100. return;
  28101. }
  28102. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28103. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28104. return;
  28105. }
  28106. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28107. var loadingToken = {};
  28108. scene._addPendingData(loadingToken);
  28109. var manifestChecked = function (success) {
  28110. scene.database = database;
  28111. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28112. var plugin = registeredPlugin.plugin;
  28113. var useArrayBuffer = registeredPlugin.isBinary;
  28114. var importMeshFromData = function (data) {
  28115. var meshes = [];
  28116. var particleSystems = [];
  28117. var skeletons = [];
  28118. try {
  28119. if (plugin.importMesh) {
  28120. var syncedPlugin = plugin;
  28121. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  28122. if (onerror) {
  28123. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28124. }
  28125. scene._removePendingData(loadingToken);
  28126. return;
  28127. }
  28128. if (onsuccess) {
  28129. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28130. onsuccess(meshes, particleSystems, skeletons);
  28131. scene._removePendingData(loadingToken);
  28132. }
  28133. }
  28134. else {
  28135. var asyncedPlugin = plugin;
  28136. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  28137. if (onsuccess) {
  28138. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28139. onsuccess(meshes, particleSystems, skeletons);
  28140. scene._removePendingData(loadingToken);
  28141. }
  28142. }, function () {
  28143. if (onerror) {
  28144. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28145. }
  28146. scene._removePendingData(loadingToken);
  28147. });
  28148. }
  28149. }
  28150. catch (e) {
  28151. if (onerror) {
  28152. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  28153. }
  28154. scene._removePendingData(loadingToken);
  28155. }
  28156. };
  28157. if (directLoad) {
  28158. importMeshFromData(directLoad);
  28159. return;
  28160. }
  28161. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  28162. importMeshFromData(data);
  28163. }, progressCallBack, database, useArrayBuffer);
  28164. };
  28165. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  28166. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28167. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28168. }
  28169. else {
  28170. // If the scene is a data stream or offline support is not enabled, it's a direct load
  28171. manifestChecked(true);
  28172. }
  28173. };
  28174. /**
  28175. * Load a scene
  28176. * @param rootUrl a string that defines the root url for scene and resources
  28177. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28178. * @param engine is the instance of BABYLON.Engine to use to create the scene
  28179. */
  28180. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  28181. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  28182. };
  28183. /**
  28184. * Append a scene
  28185. * @param rootUrl a string that defines the root url for scene and resources
  28186. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28187. * @param scene is the instance of BABYLON.Scene to append to
  28188. */
  28189. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28190. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28191. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28192. return;
  28193. }
  28194. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28195. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28196. var plugin = registeredPlugin.plugin;
  28197. var useArrayBuffer = registeredPlugin.isBinary;
  28198. var database;
  28199. var loadingToken = {};
  28200. scene._addPendingData(loadingToken);
  28201. if (SceneLoader.ShowLoadingScreen) {
  28202. scene.getEngine().displayLoadingUI();
  28203. }
  28204. var loadSceneFromData = function (data) {
  28205. scene.database = database;
  28206. if (plugin.load) {
  28207. var syncedPlugin = plugin;
  28208. if (!syncedPlugin.load(scene, data, rootUrl)) {
  28209. if (onerror) {
  28210. onerror(scene);
  28211. }
  28212. scene._removePendingData(loadingToken);
  28213. scene.getEngine().hideLoadingUI();
  28214. return;
  28215. }
  28216. if (onsuccess) {
  28217. onsuccess(scene);
  28218. }
  28219. scene._removePendingData(loadingToken);
  28220. }
  28221. else {
  28222. var asyncedPlugin = plugin;
  28223. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  28224. if (onsuccess) {
  28225. onsuccess(scene);
  28226. }
  28227. scene._removePendingData(loadingToken);
  28228. }, function () {
  28229. if (onerror) {
  28230. onerror(scene);
  28231. }
  28232. scene._removePendingData(loadingToken);
  28233. scene.getEngine().hideLoadingUI();
  28234. });
  28235. }
  28236. if (SceneLoader.ShowLoadingScreen) {
  28237. scene.executeWhenReady(function () {
  28238. scene.getEngine().hideLoadingUI();
  28239. });
  28240. }
  28241. };
  28242. var manifestChecked = function (success) {
  28243. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  28244. };
  28245. if (directLoad) {
  28246. loadSceneFromData(directLoad);
  28247. return;
  28248. }
  28249. if (rootUrl.indexOf("file:") === -1) {
  28250. if (scene.getEngine().enableOfflineSupport) {
  28251. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28252. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28253. }
  28254. else {
  28255. manifestChecked(true);
  28256. }
  28257. }
  28258. else {
  28259. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  28260. }
  28261. };
  28262. return SceneLoader;
  28263. }());
  28264. // Flags
  28265. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  28266. SceneLoader._ShowLoadingScreen = true;
  28267. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  28268. // Members
  28269. SceneLoader._registeredPlugins = {};
  28270. BABYLON.SceneLoader = SceneLoader;
  28271. ;
  28272. })(BABYLON || (BABYLON = {}));
  28273. //# sourceMappingURL=babylon.sceneLoader.js.map
  28274. var BABYLON;
  28275. (function (BABYLON) {
  28276. var Internals;
  28277. (function (Internals) {
  28278. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  28279. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28280. var parsedMaterial = parsedData.materials[index];
  28281. if (parsedMaterial.id === id) {
  28282. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28283. }
  28284. }
  28285. return null;
  28286. };
  28287. var isDescendantOf = function (mesh, names, hierarchyIds) {
  28288. names = (names instanceof Array) ? names : [names];
  28289. for (var i in names) {
  28290. if (mesh.name === names[i]) {
  28291. hierarchyIds.push(mesh.id);
  28292. return true;
  28293. }
  28294. }
  28295. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  28296. hierarchyIds.push(mesh.id);
  28297. return true;
  28298. }
  28299. return false;
  28300. };
  28301. var logOperation = function (operation, producer) {
  28302. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  28303. };
  28304. BABYLON.SceneLoader.RegisterPlugin({
  28305. extensions: ".babylon",
  28306. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  28307. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28308. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28309. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28310. // and avoid problems with multiple concurrent .babylon loads.
  28311. var log = "importMesh has failed JSON parse";
  28312. try {
  28313. var parsedData = JSON.parse(data);
  28314. log = "";
  28315. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28316. var loadedSkeletonsIds = [];
  28317. var loadedMaterialsIds = [];
  28318. var hierarchyIds = [];
  28319. var index;
  28320. var cache;
  28321. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28322. var parsedMesh = parsedData.meshes[index];
  28323. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  28324. if (meshesNames instanceof Array) {
  28325. // Remove found mesh name from list.
  28326. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  28327. }
  28328. //Geometry?
  28329. if (parsedMesh.geometryId) {
  28330. //does the file contain geometries?
  28331. if (parsedData.geometries) {
  28332. //find the correct geometry and add it to the scene
  28333. var found = false;
  28334. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  28335. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  28336. return;
  28337. }
  28338. else {
  28339. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  28340. if (parsedGeometryData.id === parsedMesh.geometryId) {
  28341. switch (geometryType) {
  28342. case "boxes":
  28343. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  28344. break;
  28345. case "spheres":
  28346. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  28347. break;
  28348. case "cylinders":
  28349. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  28350. break;
  28351. case "toruses":
  28352. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  28353. break;
  28354. case "grounds":
  28355. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  28356. break;
  28357. case "planes":
  28358. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  28359. break;
  28360. case "torusKnots":
  28361. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  28362. break;
  28363. case "vertexData":
  28364. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  28365. break;
  28366. }
  28367. found = true;
  28368. }
  28369. });
  28370. }
  28371. });
  28372. if (!found) {
  28373. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  28374. }
  28375. }
  28376. }
  28377. // Material ?
  28378. if (parsedMesh.materialId) {
  28379. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  28380. if (!materialFound && parsedData.multiMaterials) {
  28381. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  28382. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  28383. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  28384. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  28385. var subMatId = parsedMultiMaterial.materials[matIndex];
  28386. loadedMaterialsIds.push(subMatId);
  28387. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  28388. log += "\n\tMaterial " + mat.toString(fullDetails);
  28389. }
  28390. loadedMaterialsIds.push(parsedMultiMaterial.id);
  28391. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28392. materialFound = true;
  28393. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  28394. break;
  28395. }
  28396. }
  28397. }
  28398. if (!materialFound) {
  28399. loadedMaterialsIds.push(parsedMesh.materialId);
  28400. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  28401. if (!mat) {
  28402. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  28403. }
  28404. else {
  28405. log += "\n\tMaterial " + mat.toString(fullDetails);
  28406. }
  28407. }
  28408. }
  28409. // Skeleton ?
  28410. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  28411. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  28412. if (!skeletonAlreadyLoaded) {
  28413. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  28414. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  28415. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  28416. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28417. skeletons.push(skeleton);
  28418. loadedSkeletonsIds.push(parsedSkeleton.id);
  28419. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  28420. }
  28421. }
  28422. }
  28423. }
  28424. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28425. meshes.push(mesh);
  28426. log += "\n\tMesh " + mesh.toString(fullDetails);
  28427. }
  28428. }
  28429. // Connecting parents
  28430. var currentMesh;
  28431. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28432. currentMesh = scene.meshes[index];
  28433. if (currentMesh._waitingParentId) {
  28434. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  28435. currentMesh._waitingParentId = undefined;
  28436. }
  28437. }
  28438. // freeze and compute world matrix application
  28439. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28440. currentMesh = scene.meshes[index];
  28441. if (currentMesh._waitingFreezeWorldMatrix) {
  28442. currentMesh.freezeWorldMatrix();
  28443. currentMesh._waitingFreezeWorldMatrix = undefined;
  28444. }
  28445. else {
  28446. currentMesh.computeWorldMatrix(true);
  28447. }
  28448. }
  28449. // Particles
  28450. if (parsedData.particleSystems) {
  28451. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28452. var parsedParticleSystem = parsedData.particleSystems[index];
  28453. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  28454. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  28455. }
  28456. }
  28457. }
  28458. return true;
  28459. }
  28460. catch (err) {
  28461. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  28462. log = null;
  28463. throw err;
  28464. }
  28465. finally {
  28466. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28467. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28468. }
  28469. }
  28470. },
  28471. load: function (scene, data, rootUrl) {
  28472. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28473. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28474. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28475. // and avoid problems with multiple concurrent .babylon loads.
  28476. var log = "importScene has failed JSON parse";
  28477. try {
  28478. var parsedData = JSON.parse(data);
  28479. log = "";
  28480. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28481. // Scene
  28482. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  28483. scene.autoClear = parsedData.autoClear;
  28484. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  28485. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  28486. if (parsedData.gravity) {
  28487. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  28488. }
  28489. // Fog
  28490. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  28491. scene.fogMode = parsedData.fogMode;
  28492. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  28493. scene.fogStart = parsedData.fogStart;
  28494. scene.fogEnd = parsedData.fogEnd;
  28495. scene.fogDensity = parsedData.fogDensity;
  28496. log += "\tFog mode for scene: ";
  28497. switch (scene.fogMode) {
  28498. // getters not compiling, so using hardcoded
  28499. case 1:
  28500. log += "exp\n";
  28501. break;
  28502. case 2:
  28503. log += "exp2\n";
  28504. break;
  28505. case 3:
  28506. log += "linear\n";
  28507. break;
  28508. }
  28509. }
  28510. //Physics
  28511. if (parsedData.physicsEnabled) {
  28512. var physicsPlugin;
  28513. if (parsedData.physicsEngine === "cannon") {
  28514. physicsPlugin = new BABYLON.CannonJSPlugin();
  28515. }
  28516. else if (parsedData.physicsEngine === "oimo") {
  28517. physicsPlugin = new BABYLON.OimoJSPlugin();
  28518. }
  28519. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  28520. //else - default engine, which is currently oimo
  28521. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  28522. scene.enablePhysics(physicsGravity, physicsPlugin);
  28523. }
  28524. // Metadata
  28525. if (parsedData.metadata !== undefined) {
  28526. scene.metadata = parsedData.metadata;
  28527. }
  28528. //collisions, if defined. otherwise, default is true
  28529. if (parsedData.collisionsEnabled != undefined) {
  28530. scene.collisionsEnabled = parsedData.collisionsEnabled;
  28531. }
  28532. scene.workerCollisions = !!parsedData.workerCollisions;
  28533. var index;
  28534. var cache;
  28535. // Lights
  28536. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  28537. var parsedLight = parsedData.lights[index];
  28538. var light = BABYLON.Light.Parse(parsedLight, scene);
  28539. log += (index === 0 ? "\n\tLights:" : "");
  28540. log += "\n\t\t" + light.toString(fullDetails);
  28541. }
  28542. // Animations
  28543. if (parsedData.animations) {
  28544. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  28545. var parsedAnimation = parsedData.animations[index];
  28546. var animation = BABYLON.Animation.Parse(parsedAnimation);
  28547. scene.animations.push(animation);
  28548. log += (index === 0 ? "\n\tAnimations:" : "");
  28549. log += "\n\t\t" + animation.toString(fullDetails);
  28550. }
  28551. }
  28552. if (parsedData.autoAnimate) {
  28553. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  28554. }
  28555. // Materials
  28556. if (parsedData.materials) {
  28557. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28558. var parsedMaterial = parsedData.materials[index];
  28559. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28560. log += (index === 0 ? "\n\tMaterials:" : "");
  28561. log += "\n\t\t" + mat.toString(fullDetails);
  28562. }
  28563. }
  28564. if (parsedData.multiMaterials) {
  28565. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  28566. var parsedMultiMaterial = parsedData.multiMaterials[index];
  28567. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28568. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  28569. log += "\n\t\t" + mmat.toString(fullDetails);
  28570. }
  28571. }
  28572. // Skeletons
  28573. if (parsedData.skeletons) {
  28574. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  28575. var parsedSkeleton = parsedData.skeletons[index];
  28576. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28577. log += (index === 0 ? "\n\tSkeletons:" : "");
  28578. log += "\n\t\t" + skeleton.toString(fullDetails);
  28579. }
  28580. }
  28581. // Geometries
  28582. var geometries = parsedData.geometries;
  28583. if (geometries) {
  28584. // Boxes
  28585. var boxes = geometries.boxes;
  28586. if (boxes) {
  28587. for (index = 0, cache = boxes.length; index < cache; index++) {
  28588. var parsedBox = boxes[index];
  28589. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  28590. }
  28591. }
  28592. // Spheres
  28593. var spheres = geometries.spheres;
  28594. if (spheres) {
  28595. for (index = 0, cache = spheres.length; index < cache; index++) {
  28596. var parsedSphere = spheres[index];
  28597. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  28598. }
  28599. }
  28600. // Cylinders
  28601. var cylinders = geometries.cylinders;
  28602. if (cylinders) {
  28603. for (index = 0, cache = cylinders.length; index < cache; index++) {
  28604. var parsedCylinder = cylinders[index];
  28605. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  28606. }
  28607. }
  28608. // Toruses
  28609. var toruses = geometries.toruses;
  28610. if (toruses) {
  28611. for (index = 0, cache = toruses.length; index < cache; index++) {
  28612. var parsedTorus = toruses[index];
  28613. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  28614. }
  28615. }
  28616. // Grounds
  28617. var grounds = geometries.grounds;
  28618. if (grounds) {
  28619. for (index = 0, cache = grounds.length; index < cache; index++) {
  28620. var parsedGround = grounds[index];
  28621. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  28622. }
  28623. }
  28624. // Planes
  28625. var planes = geometries.planes;
  28626. if (planes) {
  28627. for (index = 0, cache = planes.length; index < cache; index++) {
  28628. var parsedPlane = planes[index];
  28629. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  28630. }
  28631. }
  28632. // TorusKnots
  28633. var torusKnots = geometries.torusKnots;
  28634. if (torusKnots) {
  28635. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  28636. var parsedTorusKnot = torusKnots[index];
  28637. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  28638. }
  28639. }
  28640. // VertexData
  28641. var vertexData = geometries.vertexData;
  28642. if (vertexData) {
  28643. for (index = 0, cache = vertexData.length; index < cache; index++) {
  28644. var parsedVertexData = vertexData[index];
  28645. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  28646. }
  28647. }
  28648. }
  28649. // Meshes
  28650. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28651. var parsedMesh = parsedData.meshes[index];
  28652. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28653. log += (index === 0 ? "\n\tMeshes:" : "");
  28654. log += "\n\t\t" + mesh.toString(fullDetails);
  28655. }
  28656. // Cameras
  28657. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  28658. var parsedCamera = parsedData.cameras[index];
  28659. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  28660. log += (index === 0 ? "\n\tCameras:" : "");
  28661. log += "\n\t\t" + camera.toString(fullDetails);
  28662. }
  28663. if (parsedData.activeCameraID) {
  28664. scene.setActiveCameraByID(parsedData.activeCameraID);
  28665. }
  28666. // Browsing all the graph to connect the dots
  28667. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28668. var camera = scene.cameras[index];
  28669. if (camera._waitingParentId) {
  28670. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28671. camera._waitingParentId = undefined;
  28672. }
  28673. }
  28674. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28675. var light = scene.lights[index];
  28676. if (light._waitingParentId) {
  28677. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28678. light._waitingParentId = undefined;
  28679. }
  28680. }
  28681. // Sounds
  28682. var loadedSounds = [];
  28683. var loadedSound;
  28684. if (BABYLON.AudioEngine && parsedData.sounds) {
  28685. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28686. var parsedSound = parsedData.sounds[index];
  28687. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28688. if (!parsedSound.url)
  28689. parsedSound.url = parsedSound.name;
  28690. if (!loadedSounds[parsedSound.url]) {
  28691. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28692. loadedSounds[parsedSound.url] = loadedSound;
  28693. }
  28694. else {
  28695. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28696. }
  28697. }
  28698. else {
  28699. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28700. }
  28701. }
  28702. }
  28703. loadedSounds = [];
  28704. // Connect parents & children and parse actions
  28705. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28706. var mesh = scene.meshes[index];
  28707. if (mesh._waitingParentId) {
  28708. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28709. mesh._waitingParentId = undefined;
  28710. }
  28711. if (mesh._waitingActions) {
  28712. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28713. mesh._waitingActions = undefined;
  28714. }
  28715. }
  28716. // freeze world matrix application
  28717. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28718. var currentMesh = scene.meshes[index];
  28719. if (currentMesh._waitingFreezeWorldMatrix) {
  28720. currentMesh.freezeWorldMatrix();
  28721. currentMesh._waitingFreezeWorldMatrix = undefined;
  28722. }
  28723. else {
  28724. currentMesh.computeWorldMatrix(true);
  28725. }
  28726. }
  28727. // Particles Systems
  28728. if (parsedData.particleSystems) {
  28729. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28730. var parsedParticleSystem = parsedData.particleSystems[index];
  28731. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28732. }
  28733. }
  28734. // Lens flares
  28735. if (parsedData.lensFlareSystems) {
  28736. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28737. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28738. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28739. }
  28740. }
  28741. // Shadows
  28742. if (parsedData.shadowGenerators) {
  28743. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28744. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28745. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28746. }
  28747. }
  28748. // Actions (scene)
  28749. if (parsedData.actions) {
  28750. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28751. }
  28752. // Finish
  28753. return true;
  28754. }
  28755. catch (err) {
  28756. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28757. log = null;
  28758. throw err;
  28759. }
  28760. finally {
  28761. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28762. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28763. }
  28764. }
  28765. }
  28766. });
  28767. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28768. })(BABYLON || (BABYLON = {}));
  28769. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28770. var BABYLON;
  28771. (function (BABYLON) {
  28772. var SpriteManager = (function () {
  28773. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28774. if (epsilon === void 0) { epsilon = 0.01; }
  28775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28776. this.name = name;
  28777. this.sprites = new Array();
  28778. this.renderingGroupId = 0;
  28779. this.layerMask = 0x0FFFFFFF;
  28780. this.fogEnabled = true;
  28781. this.isPickable = false;
  28782. /**
  28783. * An event triggered when the manager is disposed.
  28784. * @type {BABYLON.Observable}
  28785. */
  28786. this.onDisposeObservable = new BABYLON.Observable();
  28787. this._vertexBuffers = {};
  28788. this._capacity = capacity;
  28789. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28790. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28791. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28792. if (cellSize.width && cellSize.height) {
  28793. this.cellWidth = cellSize.width;
  28794. this.cellHeight = cellSize.height;
  28795. }
  28796. else if (cellSize !== undefined) {
  28797. this.cellWidth = cellSize;
  28798. this.cellHeight = cellSize;
  28799. }
  28800. else {
  28801. return;
  28802. }
  28803. this._epsilon = epsilon;
  28804. this._scene = scene;
  28805. this._scene.spriteManagers.push(this);
  28806. var indices = [];
  28807. var index = 0;
  28808. for (var count = 0; count < capacity; count++) {
  28809. indices.push(index);
  28810. indices.push(index + 1);
  28811. indices.push(index + 2);
  28812. indices.push(index);
  28813. indices.push(index + 2);
  28814. indices.push(index + 3);
  28815. index += 4;
  28816. }
  28817. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28818. // VBO
  28819. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28820. this._vertexData = new Float32Array(capacity * 16 * 4);
  28821. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28822. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28823. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28824. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28825. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28826. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28827. this._vertexBuffers["options"] = options;
  28828. this._vertexBuffers["cellInfo"] = cellInfo;
  28829. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28830. // Effects
  28831. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28832. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28833. }
  28834. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28835. set: function (callback) {
  28836. if (this._onDisposeObserver) {
  28837. this.onDisposeObservable.remove(this._onDisposeObserver);
  28838. }
  28839. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28840. },
  28841. enumerable: true,
  28842. configurable: true
  28843. });
  28844. Object.defineProperty(SpriteManager.prototype, "texture", {
  28845. get: function () {
  28846. return this._spriteTexture;
  28847. },
  28848. set: function (value) {
  28849. this._spriteTexture = value;
  28850. },
  28851. enumerable: true,
  28852. configurable: true
  28853. });
  28854. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28855. var arrayOffset = index * 16;
  28856. if (offsetX === 0)
  28857. offsetX = this._epsilon;
  28858. else if (offsetX === 1)
  28859. offsetX = 1 - this._epsilon;
  28860. if (offsetY === 0)
  28861. offsetY = this._epsilon;
  28862. else if (offsetY === 1)
  28863. offsetY = 1 - this._epsilon;
  28864. this._vertexData[arrayOffset] = sprite.position.x;
  28865. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28866. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28867. this._vertexData[arrayOffset + 3] = sprite.angle;
  28868. this._vertexData[arrayOffset + 4] = sprite.width;
  28869. this._vertexData[arrayOffset + 5] = sprite.height;
  28870. this._vertexData[arrayOffset + 6] = offsetX;
  28871. this._vertexData[arrayOffset + 7] = offsetY;
  28872. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28873. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28874. var offset = (sprite.cellIndex / rowSize) >> 0;
  28875. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28876. this._vertexData[arrayOffset + 11] = offset;
  28877. // Color
  28878. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28879. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28880. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28881. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28882. };
  28883. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28884. var count = Math.min(this._capacity, this.sprites.length);
  28885. var min = BABYLON.Vector3.Zero();
  28886. var max = BABYLON.Vector3.Zero();
  28887. var distance = Number.MAX_VALUE;
  28888. var currentSprite;
  28889. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28890. var cameraView = camera.getViewMatrix();
  28891. for (var index = 0; index < count; index++) {
  28892. var sprite = this.sprites[index];
  28893. if (!sprite) {
  28894. continue;
  28895. }
  28896. if (predicate) {
  28897. if (!predicate(sprite)) {
  28898. continue;
  28899. }
  28900. }
  28901. else if (!sprite.isPickable) {
  28902. continue;
  28903. }
  28904. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28905. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28906. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28907. if (ray.intersectsBoxMinMax(min, max)) {
  28908. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28909. if (distance > currentDistance) {
  28910. distance = currentDistance;
  28911. currentSprite = sprite;
  28912. if (fastCheck) {
  28913. break;
  28914. }
  28915. }
  28916. }
  28917. }
  28918. if (currentSprite) {
  28919. var result = new BABYLON.PickingInfo();
  28920. result.hit = true;
  28921. result.pickedSprite = currentSprite;
  28922. result.distance = distance;
  28923. return result;
  28924. }
  28925. return null;
  28926. };
  28927. SpriteManager.prototype.render = function () {
  28928. // Check
  28929. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28930. return;
  28931. var engine = this._scene.getEngine();
  28932. var baseSize = this._spriteTexture.getBaseSize();
  28933. // Sprites
  28934. var deltaTime = engine.getDeltaTime();
  28935. var max = Math.min(this._capacity, this.sprites.length);
  28936. var rowSize = baseSize.width / this.cellWidth;
  28937. var offset = 0;
  28938. for (var index = 0; index < max; index++) {
  28939. var sprite = this.sprites[index];
  28940. if (!sprite) {
  28941. continue;
  28942. }
  28943. sprite._animate(deltaTime);
  28944. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28945. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28946. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28947. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28948. }
  28949. this._buffer.update(this._vertexData);
  28950. // Render
  28951. var effect = this._effectBase;
  28952. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28953. effect = this._effectFog;
  28954. }
  28955. engine.enableEffect(effect);
  28956. var viewMatrix = this._scene.getViewMatrix();
  28957. effect.setTexture("diffuseSampler", this._spriteTexture);
  28958. effect.setMatrix("view", viewMatrix);
  28959. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28960. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28961. // Fog
  28962. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28963. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28964. effect.setColor3("vFogColor", this._scene.fogColor);
  28965. }
  28966. // VBOs
  28967. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28968. // Draw order
  28969. engine.setDepthFunctionToLessOrEqual();
  28970. effect.setBool("alphaTest", true);
  28971. engine.setColorWrite(false);
  28972. engine.draw(true, 0, max * 6);
  28973. engine.setColorWrite(true);
  28974. effect.setBool("alphaTest", false);
  28975. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28976. engine.draw(true, 0, max * 6);
  28977. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28978. };
  28979. SpriteManager.prototype.dispose = function () {
  28980. if (this._buffer) {
  28981. this._buffer.dispose();
  28982. this._buffer = null;
  28983. }
  28984. if (this._indexBuffer) {
  28985. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28986. this._indexBuffer = null;
  28987. }
  28988. if (this._spriteTexture) {
  28989. this._spriteTexture.dispose();
  28990. this._spriteTexture = null;
  28991. }
  28992. // Remove from scene
  28993. var index = this._scene.spriteManagers.indexOf(this);
  28994. this._scene.spriteManagers.splice(index, 1);
  28995. // Callback
  28996. this.onDisposeObservable.notifyObservers(this);
  28997. this.onDisposeObservable.clear();
  28998. };
  28999. return SpriteManager;
  29000. }());
  29001. BABYLON.SpriteManager = SpriteManager;
  29002. })(BABYLON || (BABYLON = {}));
  29003. //# sourceMappingURL=babylon.spriteManager.js.map
  29004. var BABYLON;
  29005. (function (BABYLON) {
  29006. var Sprite = (function () {
  29007. function Sprite(name, manager) {
  29008. this.name = name;
  29009. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29010. this.width = 1.0;
  29011. this.height = 1.0;
  29012. this.angle = 0;
  29013. this.cellIndex = 0;
  29014. this.invertU = 0;
  29015. this.invertV = 0;
  29016. this.animations = new Array();
  29017. this.isPickable = false;
  29018. this._animationStarted = false;
  29019. this._loopAnimation = false;
  29020. this._fromIndex = 0;
  29021. this._toIndex = 0;
  29022. this._delay = 0;
  29023. this._direction = 1;
  29024. this._frameCount = 0;
  29025. this._time = 0;
  29026. this._manager = manager;
  29027. this._manager.sprites.push(this);
  29028. this.position = BABYLON.Vector3.Zero();
  29029. }
  29030. Object.defineProperty(Sprite.prototype, "size", {
  29031. get: function () {
  29032. return this.width;
  29033. },
  29034. set: function (value) {
  29035. this.width = value;
  29036. this.height = value;
  29037. },
  29038. enumerable: true,
  29039. configurable: true
  29040. });
  29041. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  29042. this._fromIndex = from;
  29043. this._toIndex = to;
  29044. this._loopAnimation = loop;
  29045. this._delay = delay;
  29046. this._animationStarted = true;
  29047. this._direction = from < to ? 1 : -1;
  29048. this.cellIndex = from;
  29049. this._time = 0;
  29050. this._onAnimationEnd = onAnimationEnd;
  29051. };
  29052. Sprite.prototype.stopAnimation = function () {
  29053. this._animationStarted = false;
  29054. };
  29055. Sprite.prototype._animate = function (deltaTime) {
  29056. if (!this._animationStarted)
  29057. return;
  29058. this._time += deltaTime;
  29059. if (this._time > this._delay) {
  29060. this._time = this._time % this._delay;
  29061. this.cellIndex += this._direction;
  29062. if (this.cellIndex === this._toIndex) {
  29063. if (this._loopAnimation) {
  29064. this.cellIndex = this._fromIndex;
  29065. }
  29066. else {
  29067. this._animationStarted = false;
  29068. if (this._onAnimationEnd) {
  29069. this._onAnimationEnd();
  29070. }
  29071. if (this.disposeWhenFinishedAnimating) {
  29072. this.dispose();
  29073. }
  29074. }
  29075. }
  29076. }
  29077. };
  29078. Sprite.prototype.dispose = function () {
  29079. for (var i = 0; i < this._manager.sprites.length; i++) {
  29080. if (this._manager.sprites[i] == this) {
  29081. this._manager.sprites.splice(i, 1);
  29082. }
  29083. }
  29084. };
  29085. return Sprite;
  29086. }());
  29087. BABYLON.Sprite = Sprite;
  29088. })(BABYLON || (BABYLON = {}));
  29089. //# sourceMappingURL=babylon.sprite.js.map
  29090. var BABYLON;
  29091. (function (BABYLON) {
  29092. var Layer = (function () {
  29093. function Layer(name, imgUrl, scene, isBackground, color) {
  29094. this.name = name;
  29095. this.scale = new BABYLON.Vector2(1, 1);
  29096. this.offset = new BABYLON.Vector2(0, 0);
  29097. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  29098. this._vertexBuffers = {};
  29099. // Events
  29100. /**
  29101. * An event triggered when the layer is disposed.
  29102. * @type {BABYLON.Observable}
  29103. */
  29104. this.onDisposeObservable = new BABYLON.Observable();
  29105. /**
  29106. * An event triggered before rendering the scene
  29107. * @type {BABYLON.Observable}
  29108. */
  29109. this.onBeforeRenderObservable = new BABYLON.Observable();
  29110. /**
  29111. * An event triggered after rendering the scene
  29112. * @type {BABYLON.Observable}
  29113. */
  29114. this.onAfterRenderObservable = new BABYLON.Observable();
  29115. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  29116. this.isBackground = isBackground === undefined ? true : isBackground;
  29117. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  29118. this._scene = scene;
  29119. this._scene.layers.push(this);
  29120. var engine = scene.getEngine();
  29121. // VBO
  29122. var vertices = [];
  29123. vertices.push(1, 1);
  29124. vertices.push(-1, 1);
  29125. vertices.push(-1, -1);
  29126. vertices.push(1, -1);
  29127. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  29129. // Indices
  29130. var indices = [];
  29131. indices.push(0);
  29132. indices.push(1);
  29133. indices.push(2);
  29134. indices.push(0);
  29135. indices.push(2);
  29136. indices.push(3);
  29137. this._indexBuffer = engine.createIndexBuffer(indices);
  29138. // Effects
  29139. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  29140. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  29141. }
  29142. Object.defineProperty(Layer.prototype, "onDispose", {
  29143. set: function (callback) {
  29144. if (this._onDisposeObserver) {
  29145. this.onDisposeObservable.remove(this._onDisposeObserver);
  29146. }
  29147. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29148. },
  29149. enumerable: true,
  29150. configurable: true
  29151. });
  29152. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  29153. set: function (callback) {
  29154. if (this._onBeforeRenderObserver) {
  29155. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29156. }
  29157. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29158. },
  29159. enumerable: true,
  29160. configurable: true
  29161. });
  29162. Object.defineProperty(Layer.prototype, "onAfterRender", {
  29163. set: function (callback) {
  29164. if (this._onAfterRenderObserver) {
  29165. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29166. }
  29167. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29168. },
  29169. enumerable: true,
  29170. configurable: true
  29171. });
  29172. Layer.prototype.render = function () {
  29173. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  29174. // Check
  29175. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  29176. return;
  29177. var engine = this._scene.getEngine();
  29178. this.onBeforeRenderObservable.notifyObservers(this);
  29179. // Render
  29180. engine.enableEffect(currentEffect);
  29181. engine.setState(false);
  29182. // Texture
  29183. currentEffect.setTexture("textureSampler", this.texture);
  29184. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  29185. // Color
  29186. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  29187. // Scale / offset
  29188. currentEffect.setVector2("offset", this.offset);
  29189. currentEffect.setVector2("scale", this.scale);
  29190. // VBOs
  29191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  29192. // Draw order
  29193. if (!this.alphaTest) {
  29194. engine.setAlphaMode(this.alphaBlendingMode);
  29195. engine.draw(true, 0, 6);
  29196. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29197. }
  29198. else {
  29199. engine.draw(true, 0, 6);
  29200. }
  29201. this.onAfterRenderObservable.notifyObservers(this);
  29202. };
  29203. Layer.prototype.dispose = function () {
  29204. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29205. if (vertexBuffer) {
  29206. vertexBuffer.dispose();
  29207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29208. }
  29209. if (this._indexBuffer) {
  29210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29211. this._indexBuffer = null;
  29212. }
  29213. if (this.texture) {
  29214. this.texture.dispose();
  29215. this.texture = null;
  29216. }
  29217. // Remove from scene
  29218. var index = this._scene.layers.indexOf(this);
  29219. this._scene.layers.splice(index, 1);
  29220. // Callback
  29221. this.onDisposeObservable.notifyObservers(this);
  29222. this.onDisposeObservable.clear();
  29223. this.onAfterRenderObservable.clear();
  29224. this.onBeforeRenderObservable.clear();
  29225. };
  29226. return Layer;
  29227. }());
  29228. BABYLON.Layer = Layer;
  29229. })(BABYLON || (BABYLON = {}));
  29230. //# sourceMappingURL=babylon.layer.js.map
  29231. var BABYLON;
  29232. (function (BABYLON) {
  29233. var Particle = (function () {
  29234. function Particle() {
  29235. this.position = BABYLON.Vector3.Zero();
  29236. this.direction = BABYLON.Vector3.Zero();
  29237. this.color = new BABYLON.Color4(0, 0, 0, 0);
  29238. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  29239. this.lifeTime = 1.0;
  29240. this.age = 0;
  29241. this.size = 0;
  29242. this.angle = 0;
  29243. this.angularSpeed = 0;
  29244. }
  29245. Particle.prototype.copyTo = function (other) {
  29246. other.position.copyFrom(this.position);
  29247. other.direction.copyFrom(this.direction);
  29248. other.color.copyFrom(this.color);
  29249. other.colorStep.copyFrom(this.colorStep);
  29250. other.lifeTime = this.lifeTime;
  29251. other.age = this.age;
  29252. other.size = this.size;
  29253. other.angle = this.angle;
  29254. other.angularSpeed = this.angularSpeed;
  29255. };
  29256. return Particle;
  29257. }());
  29258. BABYLON.Particle = Particle;
  29259. })(BABYLON || (BABYLON = {}));
  29260. //# sourceMappingURL=babylon.particle.js.map
  29261. var BABYLON;
  29262. (function (BABYLON) {
  29263. var randomNumber = function (min, max) {
  29264. if (min === max) {
  29265. return (min);
  29266. }
  29267. var random = Math.random();
  29268. return ((random * (max - min)) + min);
  29269. };
  29270. var ParticleSystem = (function () {
  29271. function ParticleSystem(name, capacity, scene, customEffect) {
  29272. var _this = this;
  29273. this.name = name;
  29274. // Members
  29275. this.animations = [];
  29276. this.renderingGroupId = 0;
  29277. this.emitter = null;
  29278. this.emitRate = 10;
  29279. this.manualEmitCount = -1;
  29280. this.updateSpeed = 0.01;
  29281. this.targetStopDuration = 0;
  29282. this.disposeOnStop = false;
  29283. this.minEmitPower = 1;
  29284. this.maxEmitPower = 1;
  29285. this.minLifeTime = 1;
  29286. this.maxLifeTime = 1;
  29287. this.minSize = 1;
  29288. this.maxSize = 1;
  29289. this.minAngularSpeed = 0;
  29290. this.maxAngularSpeed = 0;
  29291. this.layerMask = 0x0FFFFFFF;
  29292. this.customShader = null;
  29293. this.preventAutoStart = false;
  29294. /**
  29295. * An event triggered when the system is disposed.
  29296. * @type {BABYLON.Observable}
  29297. */
  29298. this.onDisposeObservable = new BABYLON.Observable();
  29299. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  29300. this.forceDepthWrite = false;
  29301. this.gravity = BABYLON.Vector3.Zero();
  29302. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  29303. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  29304. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  29305. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  29306. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29307. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29308. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  29309. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29310. this.particles = new Array();
  29311. this._stockParticles = new Array();
  29312. this._newPartsExcess = 0;
  29313. this._vertexBuffers = {};
  29314. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  29315. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  29316. this._scaledDirection = BABYLON.Vector3.Zero();
  29317. this._scaledGravity = BABYLON.Vector3.Zero();
  29318. this._currentRenderId = -1;
  29319. this._started = false;
  29320. this._stopped = false;
  29321. this._actualFrame = 0;
  29322. this.id = name;
  29323. this._capacity = capacity;
  29324. this._scene = scene;
  29325. this._customEffect = customEffect;
  29326. scene.particleSystems.push(this);
  29327. var indices = [];
  29328. var index = 0;
  29329. for (var count = 0; count < capacity; count++) {
  29330. indices.push(index);
  29331. indices.push(index + 1);
  29332. indices.push(index + 2);
  29333. indices.push(index);
  29334. indices.push(index + 2);
  29335. indices.push(index + 3);
  29336. index += 4;
  29337. }
  29338. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  29339. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  29340. this._vertexData = new Float32Array(capacity * 11 * 4);
  29341. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  29342. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  29343. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  29344. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  29345. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  29346. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  29347. this._vertexBuffers["options"] = options;
  29348. // Default behaviors
  29349. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  29350. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  29351. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  29352. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  29353. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  29354. };
  29355. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  29356. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  29357. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  29358. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  29359. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  29360. };
  29361. this.updateFunction = function (particles) {
  29362. for (var index = 0; index < particles.length; index++) {
  29363. var particle = particles[index];
  29364. particle.age += _this._scaledUpdateSpeed;
  29365. if (particle.age >= particle.lifeTime) {
  29366. _this.recycleParticle(particle);
  29367. index--;
  29368. continue;
  29369. }
  29370. else {
  29371. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  29372. particle.color.addInPlace(_this._scaledColorStep);
  29373. if (particle.color.a < 0)
  29374. particle.color.a = 0;
  29375. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  29376. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  29377. particle.position.addInPlace(_this._scaledDirection);
  29378. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  29379. particle.direction.addInPlace(_this._scaledGravity);
  29380. }
  29381. }
  29382. };
  29383. }
  29384. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  29385. set: function (callback) {
  29386. if (this._onDisposeObserver) {
  29387. this.onDisposeObservable.remove(this._onDisposeObserver);
  29388. }
  29389. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29390. },
  29391. enumerable: true,
  29392. configurable: true
  29393. });
  29394. ParticleSystem.prototype.recycleParticle = function (particle) {
  29395. var lastParticle = this.particles.pop();
  29396. if (lastParticle !== particle) {
  29397. lastParticle.copyTo(particle);
  29398. this._stockParticles.push(lastParticle);
  29399. }
  29400. };
  29401. ParticleSystem.prototype.getCapacity = function () {
  29402. return this._capacity;
  29403. };
  29404. ParticleSystem.prototype.isAlive = function () {
  29405. return this._alive;
  29406. };
  29407. ParticleSystem.prototype.isStarted = function () {
  29408. return this._started;
  29409. };
  29410. ParticleSystem.prototype.start = function () {
  29411. this._started = true;
  29412. this._stopped = false;
  29413. this._actualFrame = 0;
  29414. };
  29415. ParticleSystem.prototype.stop = function () {
  29416. this._stopped = true;
  29417. };
  29418. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  29419. var offset = index * 11;
  29420. this._vertexData[offset] = particle.position.x;
  29421. this._vertexData[offset + 1] = particle.position.y;
  29422. this._vertexData[offset + 2] = particle.position.z;
  29423. this._vertexData[offset + 3] = particle.color.r;
  29424. this._vertexData[offset + 4] = particle.color.g;
  29425. this._vertexData[offset + 5] = particle.color.b;
  29426. this._vertexData[offset + 6] = particle.color.a;
  29427. this._vertexData[offset + 7] = particle.angle;
  29428. this._vertexData[offset + 8] = particle.size;
  29429. this._vertexData[offset + 9] = offsetX;
  29430. this._vertexData[offset + 10] = offsetY;
  29431. };
  29432. ParticleSystem.prototype._update = function (newParticles) {
  29433. // Update current
  29434. this._alive = this.particles.length > 0;
  29435. this.updateFunction(this.particles);
  29436. // Add new ones
  29437. var worldMatrix;
  29438. if (this.emitter.position) {
  29439. worldMatrix = this.emitter.getWorldMatrix();
  29440. }
  29441. else {
  29442. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  29443. }
  29444. var particle;
  29445. for (var index = 0; index < newParticles; index++) {
  29446. if (this.particles.length === this._capacity) {
  29447. break;
  29448. }
  29449. if (this._stockParticles.length !== 0) {
  29450. particle = this._stockParticles.pop();
  29451. particle.age = 0;
  29452. }
  29453. else {
  29454. particle = new BABYLON.Particle();
  29455. }
  29456. this.particles.push(particle);
  29457. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  29458. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  29459. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  29460. particle.size = randomNumber(this.minSize, this.maxSize);
  29461. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  29462. this.startPositionFunction(worldMatrix, particle.position, particle);
  29463. var step = randomNumber(0, 1.0);
  29464. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  29465. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  29466. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  29467. }
  29468. };
  29469. ParticleSystem.prototype._getEffect = function () {
  29470. if (this._customEffect) {
  29471. return this._customEffect;
  29472. }
  29473. ;
  29474. var defines = [];
  29475. if (this._scene.clipPlane) {
  29476. defines.push("#define CLIPPLANE");
  29477. }
  29478. // Effect
  29479. var join = defines.join("\n");
  29480. if (this._cachedDefines !== join) {
  29481. this._cachedDefines = join;
  29482. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  29483. }
  29484. return this._effect;
  29485. };
  29486. ParticleSystem.prototype.animate = function () {
  29487. if (!this._started)
  29488. return;
  29489. var effect = this._getEffect();
  29490. // Check
  29491. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  29492. return;
  29493. if (this._currentRenderId === this._scene.getRenderId()) {
  29494. return;
  29495. }
  29496. this._currentRenderId = this._scene.getRenderId();
  29497. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  29498. // determine the number of particles we need to create
  29499. var newParticles;
  29500. if (this.manualEmitCount > -1) {
  29501. newParticles = this.manualEmitCount;
  29502. this._newPartsExcess = 0;
  29503. this.manualEmitCount = 0;
  29504. }
  29505. else {
  29506. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  29507. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  29508. }
  29509. if (this._newPartsExcess > 1.0) {
  29510. newParticles += this._newPartsExcess >> 0;
  29511. this._newPartsExcess -= this._newPartsExcess >> 0;
  29512. }
  29513. this._alive = false;
  29514. if (!this._stopped) {
  29515. this._actualFrame += this._scaledUpdateSpeed;
  29516. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  29517. this.stop();
  29518. }
  29519. else {
  29520. newParticles = 0;
  29521. }
  29522. this._update(newParticles);
  29523. // Stopped?
  29524. if (this._stopped) {
  29525. if (!this._alive) {
  29526. this._started = false;
  29527. if (this.disposeOnStop) {
  29528. this._scene._toBeDisposed.push(this);
  29529. }
  29530. }
  29531. }
  29532. // Update VBO
  29533. var offset = 0;
  29534. for (var index = 0; index < this.particles.length; index++) {
  29535. var particle = this.particles[index];
  29536. this._appendParticleVertex(offset++, particle, 0, 0);
  29537. this._appendParticleVertex(offset++, particle, 1, 0);
  29538. this._appendParticleVertex(offset++, particle, 1, 1);
  29539. this._appendParticleVertex(offset++, particle, 0, 1);
  29540. }
  29541. this._vertexBuffer.update(this._vertexData);
  29542. };
  29543. ParticleSystem.prototype.render = function () {
  29544. var effect = this._getEffect();
  29545. // Check
  29546. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  29547. return 0;
  29548. var engine = this._scene.getEngine();
  29549. // Render
  29550. engine.enableEffect(effect);
  29551. engine.setState(false);
  29552. var viewMatrix = this._scene.getViewMatrix();
  29553. effect.setTexture("diffuseSampler", this.particleTexture);
  29554. effect.setMatrix("view", viewMatrix);
  29555. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29556. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  29557. if (this._scene.clipPlane) {
  29558. var clipPlane = this._scene.clipPlane;
  29559. var invView = viewMatrix.clone();
  29560. invView.invert();
  29561. effect.setMatrix("invView", invView);
  29562. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29563. }
  29564. // VBOs
  29565. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29566. // Draw order
  29567. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  29568. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  29569. }
  29570. else {
  29571. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29572. }
  29573. if (this.forceDepthWrite) {
  29574. engine.setDepthWrite(true);
  29575. }
  29576. engine.draw(true, 0, this.particles.length * 6);
  29577. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29578. return this.particles.length;
  29579. };
  29580. ParticleSystem.prototype.dispose = function () {
  29581. if (this._vertexBuffer) {
  29582. this._vertexBuffer.dispose();
  29583. this._vertexBuffer = null;
  29584. }
  29585. if (this._indexBuffer) {
  29586. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29587. this._indexBuffer = null;
  29588. }
  29589. if (this.particleTexture) {
  29590. this.particleTexture.dispose();
  29591. this.particleTexture = null;
  29592. }
  29593. // Remove from scene
  29594. var index = this._scene.particleSystems.indexOf(this);
  29595. this._scene.particleSystems.splice(index, 1);
  29596. // Callback
  29597. this.onDisposeObservable.notifyObservers(this);
  29598. this.onDisposeObservable.clear();
  29599. };
  29600. // Clone
  29601. ParticleSystem.prototype.clone = function (name, newEmitter) {
  29602. var custom = null;
  29603. var program = null;
  29604. if (this.customShader != null) {
  29605. program = this.customShader;
  29606. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29607. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29608. }
  29609. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  29610. result.customShader = program;
  29611. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  29612. if (newEmitter === undefined) {
  29613. newEmitter = this.emitter;
  29614. }
  29615. result.emitter = newEmitter;
  29616. if (this.particleTexture) {
  29617. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  29618. }
  29619. if (!this.preventAutoStart) {
  29620. result.start();
  29621. }
  29622. return result;
  29623. };
  29624. ParticleSystem.prototype.serialize = function () {
  29625. var serializationObject = {};
  29626. serializationObject.name = this.name;
  29627. serializationObject.id = this.id;
  29628. // Emitter
  29629. if (this.emitter.position) {
  29630. serializationObject.emitterId = this.emitter.id;
  29631. }
  29632. else {
  29633. serializationObject.emitter = this.emitter.asArray();
  29634. }
  29635. serializationObject.capacity = this.getCapacity();
  29636. if (this.particleTexture) {
  29637. serializationObject.textureName = this.particleTexture.name;
  29638. }
  29639. // Animations
  29640. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29641. // Particle system
  29642. serializationObject.minAngularSpeed = this.minAngularSpeed;
  29643. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  29644. serializationObject.minSize = this.minSize;
  29645. serializationObject.maxSize = this.maxSize;
  29646. serializationObject.minEmitPower = this.minEmitPower;
  29647. serializationObject.maxEmitPower = this.maxEmitPower;
  29648. serializationObject.minLifeTime = this.minLifeTime;
  29649. serializationObject.maxLifeTime = this.maxLifeTime;
  29650. serializationObject.emitRate = this.emitRate;
  29651. serializationObject.minEmitBox = this.minEmitBox.asArray();
  29652. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  29653. serializationObject.gravity = this.gravity.asArray();
  29654. serializationObject.direction1 = this.direction1.asArray();
  29655. serializationObject.direction2 = this.direction2.asArray();
  29656. serializationObject.color1 = this.color1.asArray();
  29657. serializationObject.color2 = this.color2.asArray();
  29658. serializationObject.colorDead = this.colorDead.asArray();
  29659. serializationObject.updateSpeed = this.updateSpeed;
  29660. serializationObject.targetStopDuration = this.targetStopDuration;
  29661. serializationObject.textureMask = this.textureMask.asArray();
  29662. serializationObject.blendMode = this.blendMode;
  29663. serializationObject.customShader = this.customShader;
  29664. serializationObject.preventAutoStart = this.preventAutoStart;
  29665. return serializationObject;
  29666. };
  29667. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  29668. var name = parsedParticleSystem.name;
  29669. var custom = null;
  29670. var program = null;
  29671. if (parsedParticleSystem.customShader) {
  29672. program = parsedParticleSystem.customShader;
  29673. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29674. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29675. }
  29676. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  29677. particleSystem.customShader = program;
  29678. if (parsedParticleSystem.id) {
  29679. particleSystem.id = parsedParticleSystem.id;
  29680. }
  29681. // Auto start
  29682. if (parsedParticleSystem.preventAutoStart) {
  29683. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  29684. }
  29685. // Texture
  29686. if (parsedParticleSystem.textureName) {
  29687. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  29688. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  29689. }
  29690. // Emitter
  29691. if (parsedParticleSystem.emitterId) {
  29692. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  29693. }
  29694. else {
  29695. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29696. }
  29697. // Animations
  29698. if (parsedParticleSystem.animations) {
  29699. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29700. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29701. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29702. }
  29703. }
  29704. if (parsedParticleSystem.autoAnimate) {
  29705. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29706. }
  29707. // Particle system
  29708. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29709. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29710. particleSystem.minSize = parsedParticleSystem.minSize;
  29711. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29712. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29713. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29714. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29715. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29716. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29717. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29718. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29719. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29720. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29721. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29722. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29723. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29724. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29725. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29726. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29727. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29728. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29729. if (!particleSystem.preventAutoStart) {
  29730. particleSystem.start();
  29731. }
  29732. return particleSystem;
  29733. };
  29734. return ParticleSystem;
  29735. }());
  29736. // Statics
  29737. ParticleSystem.BLENDMODE_ONEONE = 0;
  29738. ParticleSystem.BLENDMODE_STANDARD = 1;
  29739. BABYLON.ParticleSystem = ParticleSystem;
  29740. })(BABYLON || (BABYLON = {}));
  29741. //# sourceMappingURL=babylon.particleSystem.js.map
  29742. var BABYLON;
  29743. (function (BABYLON) {
  29744. var AnimationRange = (function () {
  29745. function AnimationRange(name, from, to) {
  29746. this.name = name;
  29747. this.from = from;
  29748. this.to = to;
  29749. }
  29750. AnimationRange.prototype.clone = function () {
  29751. return new AnimationRange(this.name, this.from, this.to);
  29752. };
  29753. return AnimationRange;
  29754. }());
  29755. BABYLON.AnimationRange = AnimationRange;
  29756. /**
  29757. * Composed of a frame, and an action function
  29758. */
  29759. var AnimationEvent = (function () {
  29760. function AnimationEvent(frame, action, onlyOnce) {
  29761. this.frame = frame;
  29762. this.action = action;
  29763. this.onlyOnce = onlyOnce;
  29764. this.isDone = false;
  29765. }
  29766. return AnimationEvent;
  29767. }());
  29768. BABYLON.AnimationEvent = AnimationEvent;
  29769. var PathCursor = (function () {
  29770. function PathCursor(path) {
  29771. this.path = path;
  29772. this._onchange = new Array();
  29773. this.value = 0;
  29774. this.animations = new Array();
  29775. }
  29776. PathCursor.prototype.getPoint = function () {
  29777. var point = this.path.getPointAtLengthPosition(this.value);
  29778. return new BABYLON.Vector3(point.x, 0, point.y);
  29779. };
  29780. PathCursor.prototype.moveAhead = function (step) {
  29781. if (step === void 0) { step = 0.002; }
  29782. this.move(step);
  29783. return this;
  29784. };
  29785. PathCursor.prototype.moveBack = function (step) {
  29786. if (step === void 0) { step = 0.002; }
  29787. this.move(-step);
  29788. return this;
  29789. };
  29790. PathCursor.prototype.move = function (step) {
  29791. if (Math.abs(step) > 1) {
  29792. throw "step size should be less than 1.";
  29793. }
  29794. this.value += step;
  29795. this.ensureLimits();
  29796. this.raiseOnChange();
  29797. return this;
  29798. };
  29799. PathCursor.prototype.ensureLimits = function () {
  29800. while (this.value > 1) {
  29801. this.value -= 1;
  29802. }
  29803. while (this.value < 0) {
  29804. this.value += 1;
  29805. }
  29806. return this;
  29807. };
  29808. // used by animation engine
  29809. PathCursor.prototype.markAsDirty = function (propertyName) {
  29810. this.ensureLimits();
  29811. this.raiseOnChange();
  29812. return this;
  29813. };
  29814. PathCursor.prototype.raiseOnChange = function () {
  29815. var _this = this;
  29816. this._onchange.forEach(function (f) { return f(_this); });
  29817. return this;
  29818. };
  29819. PathCursor.prototype.onchange = function (f) {
  29820. this._onchange.push(f);
  29821. return this;
  29822. };
  29823. return PathCursor;
  29824. }());
  29825. BABYLON.PathCursor = PathCursor;
  29826. var Animation = (function () {
  29827. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29828. this.name = name;
  29829. this.targetProperty = targetProperty;
  29830. this.framePerSecond = framePerSecond;
  29831. this.dataType = dataType;
  29832. this.loopMode = loopMode;
  29833. this.enableBlending = enableBlending;
  29834. this._offsetsCache = {};
  29835. this._highLimitsCache = {};
  29836. this._stopped = false;
  29837. this._blendingFactor = 0;
  29838. // The set of event that will be linked to this animation
  29839. this._events = new Array();
  29840. this.allowMatricesInterpolation = false;
  29841. this.blendingSpeed = 0.01;
  29842. this._ranges = {};
  29843. this.targetPropertyPath = targetProperty.split(".");
  29844. this.dataType = dataType;
  29845. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29846. }
  29847. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29848. var dataType = undefined;
  29849. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29850. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29851. }
  29852. else if (from instanceof BABYLON.Quaternion) {
  29853. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29854. }
  29855. else if (from instanceof BABYLON.Vector3) {
  29856. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29857. }
  29858. else if (from instanceof BABYLON.Vector2) {
  29859. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29860. }
  29861. else if (from instanceof BABYLON.Color3) {
  29862. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29863. }
  29864. else if (from instanceof BABYLON.Size) {
  29865. dataType = Animation.ANIMATIONTYPE_SIZE;
  29866. }
  29867. if (dataType == undefined) {
  29868. return null;
  29869. }
  29870. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29871. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29872. animation.setKeys(keys);
  29873. if (easingFunction !== undefined) {
  29874. animation.setEasingFunction(easingFunction);
  29875. }
  29876. return animation;
  29877. };
  29878. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29879. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29880. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29881. };
  29882. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29883. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29884. node.animations.push(animation);
  29885. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29886. };
  29887. // Methods
  29888. /**
  29889. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29890. */
  29891. Animation.prototype.toString = function (fullDetails) {
  29892. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29893. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29894. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29895. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29896. if (fullDetails) {
  29897. ret += ", Ranges: {";
  29898. var first = true;
  29899. for (var name in this._ranges) {
  29900. if (first) {
  29901. ret += ", ";
  29902. first = false;
  29903. }
  29904. ret += name;
  29905. }
  29906. ret += "}";
  29907. }
  29908. return ret;
  29909. };
  29910. /**
  29911. * Add an event to this animation.
  29912. */
  29913. Animation.prototype.addEvent = function (event) {
  29914. this._events.push(event);
  29915. };
  29916. /**
  29917. * Remove all events found at the given frame
  29918. * @param frame
  29919. */
  29920. Animation.prototype.removeEvents = function (frame) {
  29921. for (var index = 0; index < this._events.length; index++) {
  29922. if (this._events[index].frame === frame) {
  29923. this._events.splice(index, 1);
  29924. index--;
  29925. }
  29926. }
  29927. };
  29928. Animation.prototype.createRange = function (name, from, to) {
  29929. // check name not already in use; could happen for bones after serialized
  29930. if (!this._ranges[name]) {
  29931. this._ranges[name] = new AnimationRange(name, from, to);
  29932. }
  29933. };
  29934. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29935. if (deleteFrames === void 0) { deleteFrames = true; }
  29936. if (this._ranges[name]) {
  29937. if (deleteFrames) {
  29938. var from = this._ranges[name].from;
  29939. var to = this._ranges[name].to;
  29940. // this loop MUST go high to low for multiple splices to work
  29941. for (var key = this._keys.length - 1; key >= 0; key--) {
  29942. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29943. this._keys.splice(key, 1);
  29944. }
  29945. }
  29946. }
  29947. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29948. }
  29949. };
  29950. Animation.prototype.getRange = function (name) {
  29951. return this._ranges[name];
  29952. };
  29953. Animation.prototype.reset = function () {
  29954. this._offsetsCache = {};
  29955. this._highLimitsCache = {};
  29956. this.currentFrame = 0;
  29957. this._blendingFactor = 0;
  29958. this._originalBlendValue = null;
  29959. };
  29960. Animation.prototype.isStopped = function () {
  29961. return this._stopped;
  29962. };
  29963. Animation.prototype.getKeys = function () {
  29964. return this._keys;
  29965. };
  29966. Animation.prototype.getHighestFrame = function () {
  29967. var ret = 0;
  29968. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29969. if (ret < this._keys[key].frame) {
  29970. ret = this._keys[key].frame;
  29971. }
  29972. }
  29973. return ret;
  29974. };
  29975. Animation.prototype.getEasingFunction = function () {
  29976. return this._easingFunction;
  29977. };
  29978. Animation.prototype.setEasingFunction = function (easingFunction) {
  29979. this._easingFunction = easingFunction;
  29980. };
  29981. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29982. return startValue + (endValue - startValue) * gradient;
  29983. };
  29984. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29985. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29986. };
  29987. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29988. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29989. };
  29990. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29991. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29992. };
  29993. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29994. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29995. };
  29996. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29997. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29998. };
  29999. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30000. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30001. };
  30002. Animation.prototype.clone = function () {
  30003. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30004. clone.enableBlending = this.enableBlending;
  30005. clone.blendingSpeed = this.blendingSpeed;
  30006. if (this._keys) {
  30007. clone.setKeys(this._keys);
  30008. }
  30009. if (this._ranges) {
  30010. clone._ranges = {};
  30011. for (var name in this._ranges) {
  30012. clone._ranges[name] = this._ranges[name].clone();
  30013. }
  30014. }
  30015. return clone;
  30016. };
  30017. Animation.prototype.setKeys = function (values) {
  30018. this._keys = values.slice(0);
  30019. this._offsetsCache = {};
  30020. this._highLimitsCache = {};
  30021. };
  30022. Animation.prototype._getKeyValue = function (value) {
  30023. if (typeof value === "function") {
  30024. return value();
  30025. }
  30026. return value;
  30027. };
  30028. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30029. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30030. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30031. }
  30032. this.currentFrame = currentFrame;
  30033. // Try to get a hash to find the right key
  30034. 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));
  30035. if (this._keys[startKey].frame >= currentFrame) {
  30036. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  30037. startKey--;
  30038. }
  30039. }
  30040. for (var key = startKey; key < this._keys.length; key++) {
  30041. if (this._keys[key + 1].frame >= currentFrame) {
  30042. var startValue = this._getKeyValue(this._keys[key].value);
  30043. var endValue = this._getKeyValue(this._keys[key + 1].value);
  30044. // gradient : percent of currentFrame between the frame inf and the frame sup
  30045. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  30046. // check for easingFunction and correction of gradient
  30047. if (this._easingFunction != null) {
  30048. gradient = this._easingFunction.ease(gradient);
  30049. }
  30050. switch (this.dataType) {
  30051. // Float
  30052. case Animation.ANIMATIONTYPE_FLOAT:
  30053. switch (loopMode) {
  30054. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30055. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30056. return this.floatInterpolateFunction(startValue, endValue, gradient);
  30057. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30058. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  30059. }
  30060. break;
  30061. // Quaternion
  30062. case Animation.ANIMATIONTYPE_QUATERNION:
  30063. var quaternion = null;
  30064. switch (loopMode) {
  30065. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30066. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30067. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30068. break;
  30069. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30070. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30071. break;
  30072. }
  30073. return quaternion;
  30074. // Vector3
  30075. case Animation.ANIMATIONTYPE_VECTOR3:
  30076. switch (loopMode) {
  30077. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30078. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30079. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  30080. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30081. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30082. }
  30083. // Vector2
  30084. case Animation.ANIMATIONTYPE_VECTOR2:
  30085. switch (loopMode) {
  30086. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30087. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30088. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  30089. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30090. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30091. }
  30092. // Size
  30093. case Animation.ANIMATIONTYPE_SIZE:
  30094. switch (loopMode) {
  30095. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30096. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30097. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30098. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30099. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30100. }
  30101. // Color3
  30102. case Animation.ANIMATIONTYPE_COLOR3:
  30103. switch (loopMode) {
  30104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30106. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30108. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30109. }
  30110. // Matrix
  30111. case Animation.ANIMATIONTYPE_MATRIX:
  30112. switch (loopMode) {
  30113. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30114. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30115. if (this.allowMatricesInterpolation) {
  30116. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30117. }
  30118. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30119. return startValue;
  30120. }
  30121. default:
  30122. break;
  30123. }
  30124. break;
  30125. }
  30126. }
  30127. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30128. };
  30129. Animation.prototype.setValue = function (currentValue, blend) {
  30130. if (blend === void 0) { blend = false; }
  30131. // Set value
  30132. var path;
  30133. var destination;
  30134. if (this.targetPropertyPath.length > 1) {
  30135. var property = this._target[this.targetPropertyPath[0]];
  30136. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30137. property = property[this.targetPropertyPath[index]];
  30138. }
  30139. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30140. destination = property;
  30141. }
  30142. else {
  30143. path = this.targetPropertyPath[0];
  30144. destination = this._target;
  30145. }
  30146. // Blending
  30147. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30148. if (!this._originalBlendValue) {
  30149. if (destination[path].clone) {
  30150. this._originalBlendValue = destination[path].clone();
  30151. }
  30152. else {
  30153. this._originalBlendValue = destination[path];
  30154. }
  30155. }
  30156. if (this._originalBlendValue.prototype) {
  30157. if (this._originalBlendValue.prototype.Lerp) {
  30158. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30159. }
  30160. else {
  30161. destination[path] = currentValue;
  30162. }
  30163. }
  30164. else if (this._originalBlendValue.m) {
  30165. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30166. }
  30167. else {
  30168. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30169. }
  30170. this._blendingFactor += this.blendingSpeed;
  30171. }
  30172. else {
  30173. destination[path] = currentValue;
  30174. }
  30175. if (this._target.markAsDirty) {
  30176. this._target.markAsDirty(this.targetProperty);
  30177. }
  30178. };
  30179. Animation.prototype.goToFrame = function (frame) {
  30180. if (frame < this._keys[0].frame) {
  30181. frame = this._keys[0].frame;
  30182. }
  30183. else if (frame > this._keys[this._keys.length - 1].frame) {
  30184. frame = this._keys[this._keys.length - 1].frame;
  30185. }
  30186. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30187. this.setValue(currentValue);
  30188. };
  30189. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30190. if (blend === void 0) { blend = false; }
  30191. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30192. this._stopped = true;
  30193. return false;
  30194. }
  30195. var returnValue = true;
  30196. // Adding a start key at frame 0 if missing
  30197. if (this._keys[0].frame !== 0) {
  30198. var newKey = { frame: 0, value: this._keys[0].value };
  30199. this._keys.splice(0, 0, newKey);
  30200. }
  30201. // Check limits
  30202. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30203. from = this._keys[0].frame;
  30204. }
  30205. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30206. to = this._keys[this._keys.length - 1].frame;
  30207. }
  30208. //to and from cannot be the same key
  30209. if (from === to) {
  30210. from++;
  30211. }
  30212. // Compute ratio
  30213. var range = to - from;
  30214. var offsetValue;
  30215. // ratio represents the frame delta between from and to
  30216. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30217. var highLimitValue = 0;
  30218. if (ratio > range && !loop) {
  30219. returnValue = false;
  30220. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30221. }
  30222. else {
  30223. // Get max value if required
  30224. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30225. var keyOffset = to.toString() + from.toString();
  30226. if (!this._offsetsCache[keyOffset]) {
  30227. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30228. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30229. switch (this.dataType) {
  30230. // Float
  30231. case Animation.ANIMATIONTYPE_FLOAT:
  30232. this._offsetsCache[keyOffset] = toValue - fromValue;
  30233. break;
  30234. // Quaternion
  30235. case Animation.ANIMATIONTYPE_QUATERNION:
  30236. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30237. break;
  30238. // Vector3
  30239. case Animation.ANIMATIONTYPE_VECTOR3:
  30240. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30241. // Vector2
  30242. case Animation.ANIMATIONTYPE_VECTOR2:
  30243. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30244. // Size
  30245. case Animation.ANIMATIONTYPE_SIZE:
  30246. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30247. // Color3
  30248. case Animation.ANIMATIONTYPE_COLOR3:
  30249. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30250. default:
  30251. break;
  30252. }
  30253. this._highLimitsCache[keyOffset] = toValue;
  30254. }
  30255. highLimitValue = this._highLimitsCache[keyOffset];
  30256. offsetValue = this._offsetsCache[keyOffset];
  30257. }
  30258. }
  30259. if (offsetValue === undefined) {
  30260. switch (this.dataType) {
  30261. // Float
  30262. case Animation.ANIMATIONTYPE_FLOAT:
  30263. offsetValue = 0;
  30264. break;
  30265. // Quaternion
  30266. case Animation.ANIMATIONTYPE_QUATERNION:
  30267. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30268. break;
  30269. // Vector3
  30270. case Animation.ANIMATIONTYPE_VECTOR3:
  30271. offsetValue = BABYLON.Vector3.Zero();
  30272. break;
  30273. // Vector2
  30274. case Animation.ANIMATIONTYPE_VECTOR2:
  30275. offsetValue = BABYLON.Vector2.Zero();
  30276. break;
  30277. // Size
  30278. case Animation.ANIMATIONTYPE_SIZE:
  30279. offsetValue = BABYLON.Size.Zero();
  30280. break;
  30281. // Color3
  30282. case Animation.ANIMATIONTYPE_COLOR3:
  30283. offsetValue = BABYLON.Color3.Black();
  30284. }
  30285. }
  30286. // Compute value
  30287. var repeatCount = (ratio / range) >> 0;
  30288. var currentFrame = returnValue ? from + ratio % range : to;
  30289. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30290. // Set value
  30291. this.setValue(currentValue);
  30292. // Check events
  30293. for (var index = 0; index < this._events.length; index++) {
  30294. if (currentFrame >= this._events[index].frame) {
  30295. var event = this._events[index];
  30296. if (!event.isDone) {
  30297. // If event should be done only once, remove it.
  30298. if (event.onlyOnce) {
  30299. this._events.splice(index, 1);
  30300. index--;
  30301. }
  30302. event.isDone = true;
  30303. event.action();
  30304. } // Don't do anything if the event has already be done.
  30305. }
  30306. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30307. // reset event, the animation is looping
  30308. this._events[index].isDone = false;
  30309. }
  30310. }
  30311. if (!returnValue) {
  30312. this._stopped = true;
  30313. }
  30314. return returnValue;
  30315. };
  30316. Animation.prototype.serialize = function () {
  30317. var serializationObject = {};
  30318. serializationObject.name = this.name;
  30319. serializationObject.property = this.targetProperty;
  30320. serializationObject.framePerSecond = this.framePerSecond;
  30321. serializationObject.dataType = this.dataType;
  30322. serializationObject.loopBehavior = this.loopMode;
  30323. serializationObject.enableBlending = this.enableBlending;
  30324. serializationObject.blendingSpeed = this.blendingSpeed;
  30325. var dataType = this.dataType;
  30326. serializationObject.keys = [];
  30327. var keys = this.getKeys();
  30328. for (var index = 0; index < keys.length; index++) {
  30329. var animationKey = keys[index];
  30330. var key = {};
  30331. key.frame = animationKey.frame;
  30332. switch (dataType) {
  30333. case Animation.ANIMATIONTYPE_FLOAT:
  30334. key.values = [animationKey.value];
  30335. break;
  30336. case Animation.ANIMATIONTYPE_QUATERNION:
  30337. case Animation.ANIMATIONTYPE_MATRIX:
  30338. case Animation.ANIMATIONTYPE_VECTOR3:
  30339. case Animation.ANIMATIONTYPE_COLOR3:
  30340. key.values = animationKey.value.asArray();
  30341. break;
  30342. }
  30343. serializationObject.keys.push(key);
  30344. }
  30345. serializationObject.ranges = [];
  30346. for (var name in this._ranges) {
  30347. var range = {};
  30348. range.name = name;
  30349. range.from = this._ranges[name].from;
  30350. range.to = this._ranges[name].to;
  30351. serializationObject.ranges.push(range);
  30352. }
  30353. return serializationObject;
  30354. };
  30355. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30356. get: function () {
  30357. return Animation._ANIMATIONTYPE_FLOAT;
  30358. },
  30359. enumerable: true,
  30360. configurable: true
  30361. });
  30362. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30363. get: function () {
  30364. return Animation._ANIMATIONTYPE_VECTOR3;
  30365. },
  30366. enumerable: true,
  30367. configurable: true
  30368. });
  30369. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30370. get: function () {
  30371. return Animation._ANIMATIONTYPE_VECTOR2;
  30372. },
  30373. enumerable: true,
  30374. configurable: true
  30375. });
  30376. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30377. get: function () {
  30378. return Animation._ANIMATIONTYPE_SIZE;
  30379. },
  30380. enumerable: true,
  30381. configurable: true
  30382. });
  30383. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30384. get: function () {
  30385. return Animation._ANIMATIONTYPE_QUATERNION;
  30386. },
  30387. enumerable: true,
  30388. configurable: true
  30389. });
  30390. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30391. get: function () {
  30392. return Animation._ANIMATIONTYPE_MATRIX;
  30393. },
  30394. enumerable: true,
  30395. configurable: true
  30396. });
  30397. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30398. get: function () {
  30399. return Animation._ANIMATIONTYPE_COLOR3;
  30400. },
  30401. enumerable: true,
  30402. configurable: true
  30403. });
  30404. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30405. get: function () {
  30406. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30407. },
  30408. enumerable: true,
  30409. configurable: true
  30410. });
  30411. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30412. get: function () {
  30413. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30414. },
  30415. enumerable: true,
  30416. configurable: true
  30417. });
  30418. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30419. get: function () {
  30420. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30421. },
  30422. enumerable: true,
  30423. configurable: true
  30424. });
  30425. Animation.Parse = function (parsedAnimation) {
  30426. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30427. var dataType = parsedAnimation.dataType;
  30428. var keys = [];
  30429. var data;
  30430. var index;
  30431. if (parsedAnimation.enableBlending) {
  30432. animation.enableBlending = parsedAnimation.enableBlending;
  30433. }
  30434. if (parsedAnimation.blendingSpeed) {
  30435. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30436. }
  30437. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30438. var key = parsedAnimation.keys[index];
  30439. switch (dataType) {
  30440. case Animation.ANIMATIONTYPE_FLOAT:
  30441. data = key.values[0];
  30442. break;
  30443. case Animation.ANIMATIONTYPE_QUATERNION:
  30444. data = BABYLON.Quaternion.FromArray(key.values);
  30445. break;
  30446. case Animation.ANIMATIONTYPE_MATRIX:
  30447. data = BABYLON.Matrix.FromArray(key.values);
  30448. break;
  30449. case Animation.ANIMATIONTYPE_COLOR3:
  30450. data = BABYLON.Color3.FromArray(key.values);
  30451. break;
  30452. case Animation.ANIMATIONTYPE_VECTOR3:
  30453. default:
  30454. data = BABYLON.Vector3.FromArray(key.values);
  30455. break;
  30456. }
  30457. keys.push({
  30458. frame: key.frame,
  30459. value: data
  30460. });
  30461. }
  30462. animation.setKeys(keys);
  30463. if (parsedAnimation.ranges) {
  30464. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30465. data = parsedAnimation.ranges[index];
  30466. animation.createRange(data.name, data.from, data.to);
  30467. }
  30468. }
  30469. return animation;
  30470. };
  30471. Animation.AppendSerializedAnimations = function (source, destination) {
  30472. if (source.animations) {
  30473. destination.animations = [];
  30474. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30475. var animation = source.animations[animationIndex];
  30476. destination.animations.push(animation.serialize());
  30477. }
  30478. }
  30479. };
  30480. return Animation;
  30481. }());
  30482. // Statics
  30483. Animation._ANIMATIONTYPE_FLOAT = 0;
  30484. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30485. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30486. Animation._ANIMATIONTYPE_MATRIX = 3;
  30487. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30488. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30489. Animation._ANIMATIONTYPE_SIZE = 6;
  30490. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30491. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30492. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30493. BABYLON.Animation = Animation;
  30494. })(BABYLON || (BABYLON = {}));
  30495. //# sourceMappingURL=babylon.animation.js.map
  30496. var BABYLON;
  30497. (function (BABYLON) {
  30498. var Animatable = (function () {
  30499. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30500. if (fromFrame === void 0) { fromFrame = 0; }
  30501. if (toFrame === void 0) { toFrame = 100; }
  30502. if (loopAnimation === void 0) { loopAnimation = false; }
  30503. if (speedRatio === void 0) { speedRatio = 1.0; }
  30504. this.target = target;
  30505. this.fromFrame = fromFrame;
  30506. this.toFrame = toFrame;
  30507. this.loopAnimation = loopAnimation;
  30508. this.speedRatio = speedRatio;
  30509. this.onAnimationEnd = onAnimationEnd;
  30510. this._animations = new Array();
  30511. this._paused = false;
  30512. this.animationStarted = false;
  30513. if (animations) {
  30514. this.appendAnimations(target, animations);
  30515. }
  30516. this._scene = scene;
  30517. scene._activeAnimatables.push(this);
  30518. }
  30519. // Methods
  30520. Animatable.prototype.getAnimations = function () {
  30521. return this._animations;
  30522. };
  30523. Animatable.prototype.appendAnimations = function (target, animations) {
  30524. for (var index = 0; index < animations.length; index++) {
  30525. var animation = animations[index];
  30526. animation._target = target;
  30527. this._animations.push(animation);
  30528. }
  30529. };
  30530. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30531. var animations = this._animations;
  30532. for (var index = 0; index < animations.length; index++) {
  30533. if (animations[index].targetProperty === property) {
  30534. return animations[index];
  30535. }
  30536. }
  30537. return null;
  30538. };
  30539. Animatable.prototype.reset = function () {
  30540. var animations = this._animations;
  30541. for (var index = 0; index < animations.length; index++) {
  30542. animations[index].reset();
  30543. }
  30544. this._localDelayOffset = null;
  30545. this._pausedDelay = null;
  30546. };
  30547. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30548. var animations = this._animations;
  30549. for (var index = 0; index < animations.length; index++) {
  30550. animations[index].enableBlending = true;
  30551. animations[index].blendingSpeed = blendingSpeed;
  30552. }
  30553. };
  30554. Animatable.prototype.disableBlending = function () {
  30555. var animations = this._animations;
  30556. for (var index = 0; index < animations.length; index++) {
  30557. animations[index].enableBlending = false;
  30558. }
  30559. };
  30560. Animatable.prototype.goToFrame = function (frame) {
  30561. var animations = this._animations;
  30562. if (animations[0]) {
  30563. var fps = animations[0].framePerSecond;
  30564. var currentFrame = animations[0].currentFrame;
  30565. var adjustTime = frame - currentFrame;
  30566. var delay = adjustTime * 1000 / fps;
  30567. this._localDelayOffset -= delay;
  30568. }
  30569. for (var index = 0; index < animations.length; index++) {
  30570. animations[index].goToFrame(frame);
  30571. }
  30572. };
  30573. Animatable.prototype.pause = function () {
  30574. if (this._paused) {
  30575. return;
  30576. }
  30577. this._paused = true;
  30578. };
  30579. Animatable.prototype.restart = function () {
  30580. this._paused = false;
  30581. };
  30582. Animatable.prototype.stop = function (animationName) {
  30583. if (animationName) {
  30584. var idx = this._scene._activeAnimatables.indexOf(this);
  30585. if (idx > -1) {
  30586. var animations = this._animations;
  30587. var numberOfAnimationsStopped = 0;
  30588. for (var index = animations.length - 1; index >= 0; index--) {
  30589. if (typeof animationName === "string" && animations[index].name != animationName) {
  30590. continue;
  30591. }
  30592. animations[index].reset();
  30593. animations.splice(index, 1);
  30594. numberOfAnimationsStopped++;
  30595. }
  30596. if (animations.length == numberOfAnimationsStopped) {
  30597. this._scene._activeAnimatables.splice(idx, 1);
  30598. if (this.onAnimationEnd) {
  30599. this.onAnimationEnd();
  30600. }
  30601. }
  30602. }
  30603. }
  30604. else {
  30605. var index = this._scene._activeAnimatables.indexOf(this);
  30606. if (index > -1) {
  30607. this._scene._activeAnimatables.splice(index, 1);
  30608. var animations = this._animations;
  30609. for (var index = 0; index < animations.length; index++) {
  30610. animations[index].reset();
  30611. }
  30612. if (this.onAnimationEnd) {
  30613. this.onAnimationEnd();
  30614. }
  30615. }
  30616. }
  30617. };
  30618. Animatable.prototype._animate = function (delay) {
  30619. if (this._paused) {
  30620. this.animationStarted = false;
  30621. if (!this._pausedDelay) {
  30622. this._pausedDelay = delay;
  30623. }
  30624. return true;
  30625. }
  30626. if (!this._localDelayOffset) {
  30627. this._localDelayOffset = delay;
  30628. }
  30629. else if (this._pausedDelay) {
  30630. this._localDelayOffset += delay - this._pausedDelay;
  30631. this._pausedDelay = null;
  30632. }
  30633. // Animating
  30634. var running = false;
  30635. var animations = this._animations;
  30636. var index;
  30637. for (index = 0; index < animations.length; index++) {
  30638. var animation = animations[index];
  30639. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30640. running = running || isRunning;
  30641. }
  30642. this.animationStarted = running;
  30643. if (!running) {
  30644. // Remove from active animatables
  30645. index = this._scene._activeAnimatables.indexOf(this);
  30646. this._scene._activeAnimatables.splice(index, 1);
  30647. }
  30648. if (!running && this.onAnimationEnd) {
  30649. this.onAnimationEnd();
  30650. this.onAnimationEnd = null;
  30651. }
  30652. return running;
  30653. };
  30654. return Animatable;
  30655. }());
  30656. BABYLON.Animatable = Animatable;
  30657. })(BABYLON || (BABYLON = {}));
  30658. //# sourceMappingURL=babylon.animatable.js.map
  30659. var BABYLON;
  30660. (function (BABYLON) {
  30661. var EasingFunction = (function () {
  30662. function EasingFunction() {
  30663. // Properties
  30664. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30665. }
  30666. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30667. get: function () {
  30668. return EasingFunction._EASINGMODE_EASEIN;
  30669. },
  30670. enumerable: true,
  30671. configurable: true
  30672. });
  30673. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30674. get: function () {
  30675. return EasingFunction._EASINGMODE_EASEOUT;
  30676. },
  30677. enumerable: true,
  30678. configurable: true
  30679. });
  30680. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30681. get: function () {
  30682. return EasingFunction._EASINGMODE_EASEINOUT;
  30683. },
  30684. enumerable: true,
  30685. configurable: true
  30686. });
  30687. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30688. var n = Math.min(Math.max(easingMode, 0), 2);
  30689. this._easingMode = n;
  30690. };
  30691. EasingFunction.prototype.getEasingMode = function () {
  30692. return this._easingMode;
  30693. };
  30694. EasingFunction.prototype.easeInCore = function (gradient) {
  30695. throw new Error('You must implement this method');
  30696. };
  30697. EasingFunction.prototype.ease = function (gradient) {
  30698. switch (this._easingMode) {
  30699. case EasingFunction.EASINGMODE_EASEIN:
  30700. return this.easeInCore(gradient);
  30701. case EasingFunction.EASINGMODE_EASEOUT:
  30702. return (1 - this.easeInCore(1 - gradient));
  30703. }
  30704. if (gradient >= 0.5) {
  30705. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30706. }
  30707. return (this.easeInCore(gradient * 2) * 0.5);
  30708. };
  30709. return EasingFunction;
  30710. }());
  30711. //Statics
  30712. EasingFunction._EASINGMODE_EASEIN = 0;
  30713. EasingFunction._EASINGMODE_EASEOUT = 1;
  30714. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30715. BABYLON.EasingFunction = EasingFunction;
  30716. var CircleEase = (function (_super) {
  30717. __extends(CircleEase, _super);
  30718. function CircleEase() {
  30719. return _super.apply(this, arguments) || this;
  30720. }
  30721. CircleEase.prototype.easeInCore = function (gradient) {
  30722. gradient = Math.max(0, Math.min(1, gradient));
  30723. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30724. };
  30725. return CircleEase;
  30726. }(EasingFunction));
  30727. BABYLON.CircleEase = CircleEase;
  30728. var BackEase = (function (_super) {
  30729. __extends(BackEase, _super);
  30730. function BackEase(amplitude) {
  30731. if (amplitude === void 0) { amplitude = 1; }
  30732. var _this = _super.call(this) || this;
  30733. _this.amplitude = amplitude;
  30734. return _this;
  30735. }
  30736. BackEase.prototype.easeInCore = function (gradient) {
  30737. var num = Math.max(0, this.amplitude);
  30738. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30739. };
  30740. return BackEase;
  30741. }(EasingFunction));
  30742. BABYLON.BackEase = BackEase;
  30743. var BounceEase = (function (_super) {
  30744. __extends(BounceEase, _super);
  30745. function BounceEase(bounces, bounciness) {
  30746. if (bounces === void 0) { bounces = 3; }
  30747. if (bounciness === void 0) { bounciness = 2; }
  30748. var _this = _super.call(this) || this;
  30749. _this.bounces = bounces;
  30750. _this.bounciness = bounciness;
  30751. return _this;
  30752. }
  30753. BounceEase.prototype.easeInCore = function (gradient) {
  30754. var y = Math.max(0.0, this.bounces);
  30755. var bounciness = this.bounciness;
  30756. if (bounciness <= 1.0) {
  30757. bounciness = 1.001;
  30758. }
  30759. var num9 = Math.pow(bounciness, y);
  30760. var num5 = 1.0 - bounciness;
  30761. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30762. var num15 = gradient * num4;
  30763. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30764. var num3 = Math.floor(num65);
  30765. var num13 = num3 + 1.0;
  30766. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30767. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30768. var num7 = (num8 + num12) * 0.5;
  30769. var num6 = gradient - num7;
  30770. var num2 = num7 - num8;
  30771. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30772. };
  30773. return BounceEase;
  30774. }(EasingFunction));
  30775. BABYLON.BounceEase = BounceEase;
  30776. var CubicEase = (function (_super) {
  30777. __extends(CubicEase, _super);
  30778. function CubicEase() {
  30779. return _super.apply(this, arguments) || this;
  30780. }
  30781. CubicEase.prototype.easeInCore = function (gradient) {
  30782. return (gradient * gradient * gradient);
  30783. };
  30784. return CubicEase;
  30785. }(EasingFunction));
  30786. BABYLON.CubicEase = CubicEase;
  30787. var ElasticEase = (function (_super) {
  30788. __extends(ElasticEase, _super);
  30789. function ElasticEase(oscillations, springiness) {
  30790. if (oscillations === void 0) { oscillations = 3; }
  30791. if (springiness === void 0) { springiness = 3; }
  30792. var _this = _super.call(this) || this;
  30793. _this.oscillations = oscillations;
  30794. _this.springiness = springiness;
  30795. return _this;
  30796. }
  30797. ElasticEase.prototype.easeInCore = function (gradient) {
  30798. var num2;
  30799. var num3 = Math.max(0.0, this.oscillations);
  30800. var num = Math.max(0.0, this.springiness);
  30801. if (num == 0) {
  30802. num2 = gradient;
  30803. }
  30804. else {
  30805. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30806. }
  30807. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30808. };
  30809. return ElasticEase;
  30810. }(EasingFunction));
  30811. BABYLON.ElasticEase = ElasticEase;
  30812. var ExponentialEase = (function (_super) {
  30813. __extends(ExponentialEase, _super);
  30814. function ExponentialEase(exponent) {
  30815. if (exponent === void 0) { exponent = 2; }
  30816. var _this = _super.call(this) || this;
  30817. _this.exponent = exponent;
  30818. return _this;
  30819. }
  30820. ExponentialEase.prototype.easeInCore = function (gradient) {
  30821. if (this.exponent <= 0) {
  30822. return gradient;
  30823. }
  30824. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30825. };
  30826. return ExponentialEase;
  30827. }(EasingFunction));
  30828. BABYLON.ExponentialEase = ExponentialEase;
  30829. var PowerEase = (function (_super) {
  30830. __extends(PowerEase, _super);
  30831. function PowerEase(power) {
  30832. if (power === void 0) { power = 2; }
  30833. var _this = _super.call(this) || this;
  30834. _this.power = power;
  30835. return _this;
  30836. }
  30837. PowerEase.prototype.easeInCore = function (gradient) {
  30838. var y = Math.max(0.0, this.power);
  30839. return Math.pow(gradient, y);
  30840. };
  30841. return PowerEase;
  30842. }(EasingFunction));
  30843. BABYLON.PowerEase = PowerEase;
  30844. var QuadraticEase = (function (_super) {
  30845. __extends(QuadraticEase, _super);
  30846. function QuadraticEase() {
  30847. return _super.apply(this, arguments) || this;
  30848. }
  30849. QuadraticEase.prototype.easeInCore = function (gradient) {
  30850. return (gradient * gradient);
  30851. };
  30852. return QuadraticEase;
  30853. }(EasingFunction));
  30854. BABYLON.QuadraticEase = QuadraticEase;
  30855. var QuarticEase = (function (_super) {
  30856. __extends(QuarticEase, _super);
  30857. function QuarticEase() {
  30858. return _super.apply(this, arguments) || this;
  30859. }
  30860. QuarticEase.prototype.easeInCore = function (gradient) {
  30861. return (gradient * gradient * gradient * gradient);
  30862. };
  30863. return QuarticEase;
  30864. }(EasingFunction));
  30865. BABYLON.QuarticEase = QuarticEase;
  30866. var QuinticEase = (function (_super) {
  30867. __extends(QuinticEase, _super);
  30868. function QuinticEase() {
  30869. return _super.apply(this, arguments) || this;
  30870. }
  30871. QuinticEase.prototype.easeInCore = function (gradient) {
  30872. return (gradient * gradient * gradient * gradient * gradient);
  30873. };
  30874. return QuinticEase;
  30875. }(EasingFunction));
  30876. BABYLON.QuinticEase = QuinticEase;
  30877. var SineEase = (function (_super) {
  30878. __extends(SineEase, _super);
  30879. function SineEase() {
  30880. return _super.apply(this, arguments) || this;
  30881. }
  30882. SineEase.prototype.easeInCore = function (gradient) {
  30883. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30884. };
  30885. return SineEase;
  30886. }(EasingFunction));
  30887. BABYLON.SineEase = SineEase;
  30888. var BezierCurveEase = (function (_super) {
  30889. __extends(BezierCurveEase, _super);
  30890. function BezierCurveEase(x1, y1, x2, y2) {
  30891. if (x1 === void 0) { x1 = 0; }
  30892. if (y1 === void 0) { y1 = 0; }
  30893. if (x2 === void 0) { x2 = 1; }
  30894. if (y2 === void 0) { y2 = 1; }
  30895. var _this = _super.call(this) || this;
  30896. _this.x1 = x1;
  30897. _this.y1 = y1;
  30898. _this.x2 = x2;
  30899. _this.y2 = y2;
  30900. return _this;
  30901. }
  30902. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30903. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30904. };
  30905. return BezierCurveEase;
  30906. }(EasingFunction));
  30907. BABYLON.BezierCurveEase = BezierCurveEase;
  30908. })(BABYLON || (BABYLON = {}));
  30909. //# sourceMappingURL=babylon.easing.js.map
  30910. var BABYLON;
  30911. (function (BABYLON) {
  30912. var Bone = (function (_super) {
  30913. __extends(Bone, _super);
  30914. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30915. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30916. _this.name = name;
  30917. _this.children = new Array();
  30918. _this.animations = new Array();
  30919. _this._worldTransform = new BABYLON.Matrix();
  30920. _this._absoluteTransform = new BABYLON.Matrix();
  30921. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30922. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30923. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30924. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30925. _this._scalingDeterminant = 1;
  30926. _this._syncScaleVector = function () {
  30927. var lm = this.getLocalMatrix();
  30928. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30929. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30930. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30931. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30932. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30933. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30934. this._scaleVector.x = xs * Math.sqrt(xsq);
  30935. this._scaleVector.y = ys * Math.sqrt(ysq);
  30936. this._scaleVector.z = zs * Math.sqrt(zsq);
  30937. if (this._parent) {
  30938. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30939. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30940. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30941. }
  30942. 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);
  30943. };
  30944. _this._skeleton = skeleton;
  30945. _this._matrix = matrix;
  30946. _this._baseMatrix = matrix;
  30947. _this._restPose = restPose ? restPose : matrix.clone();
  30948. skeleton.bones.push(_this);
  30949. if (parentBone) {
  30950. _this._parent = parentBone;
  30951. parentBone.children.push(_this);
  30952. }
  30953. else {
  30954. _this._parent = null;
  30955. }
  30956. _this._updateDifferenceMatrix();
  30957. if (_this.getAbsoluteTransform().determinant() < 0) {
  30958. _this._scalingDeterminant *= -1;
  30959. }
  30960. return _this;
  30961. }
  30962. // Members
  30963. Bone.prototype.getParent = function () {
  30964. return this._parent;
  30965. };
  30966. Bone.prototype.getLocalMatrix = function () {
  30967. return this._matrix;
  30968. };
  30969. Bone.prototype.getBaseMatrix = function () {
  30970. return this._baseMatrix;
  30971. };
  30972. Bone.prototype.getRestPose = function () {
  30973. return this._restPose;
  30974. };
  30975. Bone.prototype.returnToRest = function () {
  30976. this.updateMatrix(this._restPose.clone());
  30977. };
  30978. Bone.prototype.getWorldMatrix = function () {
  30979. return this._worldTransform;
  30980. };
  30981. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30982. return this._invertedAbsoluteTransform;
  30983. };
  30984. Bone.prototype.getAbsoluteTransform = function () {
  30985. return this._absoluteTransform;
  30986. };
  30987. // Methods
  30988. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30989. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30990. this._baseMatrix = matrix.clone();
  30991. this._matrix = matrix.clone();
  30992. this._skeleton._markAsDirty();
  30993. if (updateDifferenceMatrix) {
  30994. this._updateDifferenceMatrix();
  30995. }
  30996. };
  30997. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30998. if (!rootMatrix) {
  30999. rootMatrix = this._baseMatrix;
  31000. }
  31001. if (this._parent) {
  31002. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31003. }
  31004. else {
  31005. this._absoluteTransform.copyFrom(rootMatrix);
  31006. }
  31007. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  31008. for (var index = 0; index < this.children.length; index++) {
  31009. this.children[index]._updateDifferenceMatrix();
  31010. }
  31011. };
  31012. Bone.prototype.markAsDirty = function () {
  31013. this._currentRenderId++;
  31014. this._skeleton._markAsDirty();
  31015. };
  31016. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  31017. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31018. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  31019. // all animation may be coming from a library skeleton, so may need to create animation
  31020. if (this.animations.length === 0) {
  31021. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  31022. this.animations[0].setKeys([]);
  31023. }
  31024. // get animation info / verify there is such a range from the source bone
  31025. var sourceRange = source.animations[0].getRange(rangeName);
  31026. if (!sourceRange) {
  31027. return false;
  31028. }
  31029. var from = sourceRange.from;
  31030. var to = sourceRange.to;
  31031. var sourceKeys = source.animations[0].getKeys();
  31032. // rescaling prep
  31033. var sourceBoneLength = source.length;
  31034. var sourceParent = source.getParent();
  31035. var parent = this.getParent();
  31036. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  31037. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  31038. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  31039. var destKeys = this.animations[0].getKeys();
  31040. // loop vars declaration
  31041. var orig;
  31042. var origTranslation;
  31043. var mat;
  31044. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  31045. orig = sourceKeys[key];
  31046. if (orig.frame >= from && orig.frame <= to) {
  31047. if (rescaleAsRequired) {
  31048. mat = orig.value.clone();
  31049. // scale based on parent ratio, when bone has parent
  31050. if (parentScalingReqd) {
  31051. origTranslation = mat.getTranslation();
  31052. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  31053. }
  31054. else if (dimensionsScalingReqd) {
  31055. origTranslation = mat.getTranslation();
  31056. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  31057. }
  31058. else {
  31059. mat = orig.value;
  31060. }
  31061. }
  31062. else {
  31063. mat = orig.value;
  31064. }
  31065. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  31066. }
  31067. }
  31068. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  31069. return true;
  31070. };
  31071. Bone.prototype.translate = function (vec, space, mesh) {
  31072. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31073. var lm = this.getLocalMatrix();
  31074. if (space == BABYLON.Space.LOCAL) {
  31075. lm.m[12] += vec.x;
  31076. lm.m[13] += vec.y;
  31077. lm.m[14] += vec.z;
  31078. }
  31079. else {
  31080. this._skeleton.computeAbsoluteTransforms();
  31081. var tmat = BABYLON.Tmp.Matrix[0];
  31082. var tvec = BABYLON.Tmp.Vector3[0];
  31083. if (mesh) {
  31084. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31085. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31086. }
  31087. else {
  31088. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31089. }
  31090. tmat.m[12] = 0;
  31091. tmat.m[13] = 0;
  31092. tmat.m[14] = 0;
  31093. tmat.invert();
  31094. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  31095. lm.m[12] += tvec.x;
  31096. lm.m[13] += tvec.y;
  31097. lm.m[14] += tvec.z;
  31098. }
  31099. this.markAsDirty();
  31100. };
  31101. Bone.prototype.setPosition = function (position, space, mesh) {
  31102. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31103. var lm = this.getLocalMatrix();
  31104. if (space == BABYLON.Space.LOCAL) {
  31105. lm.m[12] = position.x;
  31106. lm.m[13] = position.y;
  31107. lm.m[14] = position.z;
  31108. }
  31109. else {
  31110. this._skeleton.computeAbsoluteTransforms();
  31111. var tmat = BABYLON.Tmp.Matrix[0];
  31112. var vec = BABYLON.Tmp.Vector3[0];
  31113. if (mesh) {
  31114. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31115. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31116. }
  31117. else {
  31118. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31119. }
  31120. tmat.invert();
  31121. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  31122. lm.m[12] = vec.x;
  31123. lm.m[13] = vec.y;
  31124. lm.m[14] = vec.z;
  31125. }
  31126. this.markAsDirty();
  31127. };
  31128. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  31129. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  31130. };
  31131. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  31132. if (scaleChildren === void 0) { scaleChildren = false; }
  31133. if (this.animations[0] && !this.animations[0].isStopped()) {
  31134. if (!scaleChildren) {
  31135. this._negateScaleChildren.x = 1 / x;
  31136. this._negateScaleChildren.y = 1 / y;
  31137. this._negateScaleChildren.z = 1 / z;
  31138. }
  31139. this._syncScaleVector();
  31140. }
  31141. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  31142. };
  31143. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  31144. if (scaleChildren === void 0) { scaleChildren = false; }
  31145. var locMat = this.getLocalMatrix();
  31146. var origLocMat = BABYLON.Tmp.Matrix[0];
  31147. origLocMat.copyFrom(locMat);
  31148. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  31149. origLocMatInv.copyFrom(origLocMat);
  31150. origLocMatInv.invert();
  31151. var scaleMat = BABYLON.Tmp.Matrix[2];
  31152. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  31153. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  31154. this._scaleVector.x *= x;
  31155. this._scaleVector.y *= y;
  31156. this._scaleVector.z *= z;
  31157. locMat.multiplyToRef(origLocMatInv, locMat);
  31158. locMat.multiplyToRef(scaleMat, locMat);
  31159. locMat.multiplyToRef(origLocMat, locMat);
  31160. var parent = this.getParent();
  31161. if (parent) {
  31162. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  31163. }
  31164. else {
  31165. this.getAbsoluteTransform().copyFrom(locMat);
  31166. }
  31167. var len = this.children.length;
  31168. scaleMat.invert();
  31169. for (var i = 0; i < len; i++) {
  31170. var child = this.children[i];
  31171. var cm = child.getLocalMatrix();
  31172. cm.multiplyToRef(scaleMat, cm);
  31173. var lm = child.getLocalMatrix();
  31174. lm.m[12] *= x;
  31175. lm.m[13] *= y;
  31176. lm.m[14] *= z;
  31177. }
  31178. this.computeAbsoluteTransforms();
  31179. if (scaleChildren) {
  31180. for (var i = 0; i < len; i++) {
  31181. this.children[i].scale(x, y, z, scaleChildren);
  31182. }
  31183. }
  31184. this.markAsDirty();
  31185. };
  31186. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  31187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31188. var rotMat = BABYLON.Tmp.Matrix[0];
  31189. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  31190. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31191. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31192. rotMatInv.multiplyToRef(rotMat, rotMat);
  31193. this._rotateWithMatrix(rotMat, space, mesh);
  31194. };
  31195. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  31196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31197. var rmat = BABYLON.Tmp.Matrix[0];
  31198. rmat.m[12] = 0;
  31199. rmat.m[13] = 0;
  31200. rmat.m[14] = 0;
  31201. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  31202. this._rotateWithMatrix(rmat, space, mesh);
  31203. };
  31204. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  31205. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31206. var rotMat = BABYLON.Tmp.Matrix[0];
  31207. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  31208. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31209. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31210. rotMatInv.multiplyToRef(rotMat, rotMat);
  31211. this._rotateWithMatrix(rotMat, space, mesh);
  31212. };
  31213. Bone.prototype.setRotation = function (rotation, space, mesh) {
  31214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31215. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  31216. };
  31217. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  31218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31219. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31220. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31221. var rotMat = BABYLON.Tmp.Matrix[1];
  31222. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  31223. rotMatInv.multiplyToRef(rotMat, rotMat);
  31224. this._rotateWithMatrix(rotMat, space, mesh);
  31225. };
  31226. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  31227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31228. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31229. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31230. var rotMat2 = BABYLON.Tmp.Matrix[1];
  31231. rotMat2.copyFrom(rotMat);
  31232. rotMatInv.multiplyToRef(rotMat, rotMat2);
  31233. this._rotateWithMatrix(rotMat2, space, mesh);
  31234. };
  31235. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  31236. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31237. var lmat = this.getLocalMatrix();
  31238. var lx = lmat.m[12];
  31239. var ly = lmat.m[13];
  31240. var lz = lmat.m[14];
  31241. var parent = this.getParent();
  31242. var parentScale = BABYLON.Tmp.Matrix[3];
  31243. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  31244. if (parent) {
  31245. if (space == BABYLON.Space.WORLD) {
  31246. if (mesh) {
  31247. parentScale.copyFrom(mesh.getWorldMatrix());
  31248. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  31249. }
  31250. else {
  31251. parentScale.copyFrom(parent.getAbsoluteTransform());
  31252. }
  31253. }
  31254. else {
  31255. parentScale = parent._scaleMatrix;
  31256. }
  31257. parentScaleInv.copyFrom(parentScale);
  31258. parentScaleInv.invert();
  31259. lmat.multiplyToRef(parentScale, lmat);
  31260. lmat.multiplyToRef(rmat, lmat);
  31261. lmat.multiplyToRef(parentScaleInv, lmat);
  31262. }
  31263. else {
  31264. if (space == BABYLON.Space.WORLD && mesh) {
  31265. parentScale.copyFrom(mesh.getWorldMatrix());
  31266. parentScaleInv.copyFrom(parentScale);
  31267. parentScaleInv.invert();
  31268. lmat.multiplyToRef(parentScale, lmat);
  31269. lmat.multiplyToRef(rmat, lmat);
  31270. lmat.multiplyToRef(parentScaleInv, lmat);
  31271. }
  31272. else {
  31273. lmat.multiplyToRef(rmat, lmat);
  31274. }
  31275. }
  31276. lmat.m[12] = lx;
  31277. lmat.m[13] = ly;
  31278. lmat.m[14] = lz;
  31279. this.computeAbsoluteTransforms();
  31280. this.markAsDirty();
  31281. };
  31282. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  31283. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31284. if (space == BABYLON.Space.WORLD) {
  31285. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31286. scaleMatrix.copyFrom(this._scaleMatrix);
  31287. rotMatInv.copyFrom(this.getAbsoluteTransform());
  31288. if (mesh) {
  31289. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  31290. var meshScale = BABYLON.Tmp.Matrix[3];
  31291. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  31292. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  31293. }
  31294. rotMatInv.invert();
  31295. scaleMatrix.m[0] *= this._scalingDeterminant;
  31296. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31297. }
  31298. else {
  31299. rotMatInv.copyFrom(this.getLocalMatrix());
  31300. rotMatInv.invert();
  31301. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31302. scaleMatrix.copyFrom(this._scaleMatrix);
  31303. if (this._parent) {
  31304. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  31305. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  31306. pscaleMatrix.invert();
  31307. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  31308. }
  31309. else {
  31310. scaleMatrix.m[0] *= this._scalingDeterminant;
  31311. }
  31312. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31313. }
  31314. };
  31315. Bone.prototype.getScale = function () {
  31316. return this._scaleVector.clone();
  31317. };
  31318. Bone.prototype.getScaleToRef = function (result) {
  31319. result.copyFrom(this._scaleVector);
  31320. };
  31321. Bone.prototype.getPosition = function (space, mesh) {
  31322. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31323. var pos = BABYLON.Vector3.Zero();
  31324. this.getPositionToRef(space, mesh, pos);
  31325. return pos;
  31326. };
  31327. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  31328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31329. if (space == BABYLON.Space.LOCAL) {
  31330. var lm = this.getLocalMatrix();
  31331. result.x = lm.m[12];
  31332. result.y = lm.m[13];
  31333. result.z = lm.m[14];
  31334. }
  31335. else {
  31336. this._skeleton.computeAbsoluteTransforms();
  31337. var tmat = BABYLON.Tmp.Matrix[0];
  31338. if (mesh) {
  31339. tmat.copyFrom(this.getAbsoluteTransform());
  31340. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31341. }
  31342. else {
  31343. tmat = this.getAbsoluteTransform();
  31344. }
  31345. result.x = tmat.m[12];
  31346. result.y = tmat.m[13];
  31347. result.z = tmat.m[14];
  31348. }
  31349. };
  31350. Bone.prototype.getAbsolutePosition = function (mesh) {
  31351. var pos = BABYLON.Vector3.Zero();
  31352. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  31353. return pos;
  31354. };
  31355. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  31356. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  31357. };
  31358. Bone.prototype.computeAbsoluteTransforms = function () {
  31359. if (this._parent) {
  31360. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31361. }
  31362. else {
  31363. this._absoluteTransform.copyFrom(this._matrix);
  31364. var poseMatrix = this._skeleton.getPoseMatrix();
  31365. if (poseMatrix) {
  31366. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  31367. }
  31368. }
  31369. var children = this.children;
  31370. var len = children.length;
  31371. for (var i = 0; i < len; i++) {
  31372. children[i].computeAbsoluteTransforms();
  31373. }
  31374. };
  31375. Bone.prototype.getDirection = function (localAxis, mesh) {
  31376. var result = BABYLON.Vector3.Zero();
  31377. this.getDirectionToRef(localAxis, mesh, result);
  31378. return result;
  31379. };
  31380. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  31381. this._skeleton.computeAbsoluteTransforms();
  31382. var mat = BABYLON.Tmp.Matrix[0];
  31383. mat.copyFrom(this.getAbsoluteTransform());
  31384. if (mesh) {
  31385. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31386. }
  31387. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  31388. result.normalize();
  31389. };
  31390. Bone.prototype.getRotation = function (space, mesh) {
  31391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31392. var result = BABYLON.Vector3.Zero();
  31393. this.getRotationToRef(space, mesh, result);
  31394. return result;
  31395. };
  31396. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  31397. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31398. var quat = BABYLON.Tmp.Quaternion[0];
  31399. this.getRotationQuaternionToRef(space, mesh, quat);
  31400. quat.toEulerAnglesToRef(result);
  31401. };
  31402. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  31403. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31404. var result = BABYLON.Quaternion.Identity();
  31405. this.getRotationQuaternionToRef(space, mesh, result);
  31406. return result;
  31407. };
  31408. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  31409. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31410. if (space == BABYLON.Space.LOCAL) {
  31411. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31412. }
  31413. else {
  31414. var mat = BABYLON.Tmp.Matrix[0];
  31415. var amat = this.getAbsoluteTransform();
  31416. if (mesh) {
  31417. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31418. }
  31419. else {
  31420. mat.copyFrom(amat);
  31421. }
  31422. mat.m[0] *= this._scalingDeterminant;
  31423. mat.m[1] *= this._scalingDeterminant;
  31424. mat.m[2] *= this._scalingDeterminant;
  31425. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31426. }
  31427. };
  31428. Bone.prototype.getRotationMatrix = function (space, mesh) {
  31429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31430. var result = BABYLON.Matrix.Identity();
  31431. this.getRotationMatrixToRef(space, mesh, result);
  31432. return result;
  31433. };
  31434. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  31435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31436. if (space == BABYLON.Space.LOCAL) {
  31437. this.getLocalMatrix().getRotationMatrixToRef(result);
  31438. }
  31439. else {
  31440. var mat = BABYLON.Tmp.Matrix[0];
  31441. var amat = this.getAbsoluteTransform();
  31442. if (mesh) {
  31443. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31444. }
  31445. else {
  31446. mat.copyFrom(amat);
  31447. }
  31448. mat.m[0] *= this._scalingDeterminant;
  31449. mat.m[1] *= this._scalingDeterminant;
  31450. mat.m[2] *= this._scalingDeterminant;
  31451. mat.getRotationMatrixToRef(result);
  31452. }
  31453. };
  31454. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  31455. var result = BABYLON.Vector3.Zero();
  31456. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  31457. return result;
  31458. };
  31459. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  31460. this._skeleton.computeAbsoluteTransforms();
  31461. var tmat = BABYLON.Tmp.Matrix[0];
  31462. if (mesh) {
  31463. tmat.copyFrom(this.getAbsoluteTransform());
  31464. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31465. }
  31466. else {
  31467. tmat = this.getAbsoluteTransform();
  31468. }
  31469. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31470. };
  31471. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  31472. var result = BABYLON.Vector3.Zero();
  31473. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  31474. return result;
  31475. };
  31476. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  31477. this._skeleton.computeAbsoluteTransforms();
  31478. var tmat = BABYLON.Tmp.Matrix[0];
  31479. tmat.copyFrom(this.getAbsoluteTransform());
  31480. if (mesh) {
  31481. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31482. }
  31483. tmat.invert();
  31484. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31485. };
  31486. return Bone;
  31487. }(BABYLON.Node));
  31488. BABYLON.Bone = Bone;
  31489. })(BABYLON || (BABYLON = {}));
  31490. //# sourceMappingURL=babylon.bone.js.map
  31491. var BABYLON;
  31492. (function (BABYLON) {
  31493. var BoneIKController = (function () {
  31494. function BoneIKController(mesh, bone, options) {
  31495. this.targetPosition = BABYLON.Vector3.Zero();
  31496. this.poleTargetPosition = BABYLON.Vector3.Zero();
  31497. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  31498. this.poleAngle = 0;
  31499. this.slerpAmount = 1;
  31500. this._bone1Quat = BABYLON.Quaternion.Identity();
  31501. this._bone1Mat = BABYLON.Matrix.Identity();
  31502. this._bone2Ang = Math.PI;
  31503. this._maxAngle = Math.PI;
  31504. this._tmpVec1 = BABYLON.Vector3.Zero();
  31505. this._tmpVec2 = BABYLON.Vector3.Zero();
  31506. this._tmpVec3 = BABYLON.Vector3.Zero();
  31507. this._tmpVec4 = BABYLON.Vector3.Zero();
  31508. this._tmpVec5 = BABYLON.Vector3.Zero();
  31509. this._tmpMat1 = BABYLON.Matrix.Identity();
  31510. this._tmpMat2 = BABYLON.Matrix.Identity();
  31511. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  31512. this._rightHandedSystem = false;
  31513. this._bendAxis = BABYLON.Vector3.Right();
  31514. this._slerping = false;
  31515. this._bone2 = bone;
  31516. this._bone1 = bone.getParent();
  31517. this.mesh = mesh;
  31518. if (bone.getAbsoluteTransform().determinant() > 0) {
  31519. this._rightHandedSystem = true;
  31520. this._bendAxis.x = 0;
  31521. this._bendAxis.y = 0;
  31522. this._bendAxis.z = 1;
  31523. }
  31524. if (this._bone1.length) {
  31525. var boneScale1 = this._bone1.getScale();
  31526. var boneScale2 = this._bone2.getScale();
  31527. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  31528. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  31529. }
  31530. else if (this._bone1.children[0]) {
  31531. mesh.computeWorldMatrix(true);
  31532. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  31533. var pos2 = this._bone2.getAbsolutePosition(mesh);
  31534. var pos3 = this._bone1.getAbsolutePosition(mesh);
  31535. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  31536. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  31537. }
  31538. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  31539. this.maxAngle = Math.PI;
  31540. if (options) {
  31541. if (options.targetMesh) {
  31542. this.targetMesh = options.targetMesh;
  31543. this.targetMesh.computeWorldMatrix(true);
  31544. }
  31545. if (options.poleTargetMesh) {
  31546. this.poleTargetMesh = options.poleTargetMesh;
  31547. this.poleTargetMesh.computeWorldMatrix(true);
  31548. }
  31549. else if (options.poleTargetBone) {
  31550. this.poleTargetBone = options.poleTargetBone;
  31551. }
  31552. else if (this._bone1.getParent()) {
  31553. this.poleTargetBone = this._bone1.getParent();
  31554. }
  31555. if (options.poleTargetLocalOffset) {
  31556. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  31557. }
  31558. if (options.poleAngle) {
  31559. this.poleAngle = options.poleAngle;
  31560. }
  31561. if (options.bendAxis) {
  31562. this._bendAxis.copyFrom(options.bendAxis);
  31563. }
  31564. if (options.maxAngle) {
  31565. this.maxAngle = options.maxAngle;
  31566. }
  31567. if (options.slerpAmount) {
  31568. this.slerpAmount = options.slerpAmount;
  31569. }
  31570. }
  31571. }
  31572. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  31573. get: function () {
  31574. return this._maxAngle;
  31575. },
  31576. set: function (value) {
  31577. this._setMaxAngle(value);
  31578. },
  31579. enumerable: true,
  31580. configurable: true
  31581. });
  31582. BoneIKController.prototype._setMaxAngle = function (ang) {
  31583. if (ang < 0) {
  31584. ang = 0;
  31585. }
  31586. if (ang > Math.PI || ang == undefined) {
  31587. ang = Math.PI;
  31588. }
  31589. this._maxAngle = ang;
  31590. var a = this._bone1Length;
  31591. var b = this._bone2Length;
  31592. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  31593. };
  31594. BoneIKController.prototype.update = function () {
  31595. var bone1 = this._bone1;
  31596. var target = this.targetPosition;
  31597. var poleTarget = this.poleTargetPosition;
  31598. var mat1 = this._tmpMat1;
  31599. var mat2 = this._tmpMat2;
  31600. if (this.targetMesh) {
  31601. target.copyFrom(this.targetMesh.getAbsolutePosition());
  31602. }
  31603. if (this.poleTargetBone) {
  31604. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  31605. }
  31606. else if (this.poleTargetMesh) {
  31607. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  31608. }
  31609. var bonePos = this._tmpVec1;
  31610. var zaxis = this._tmpVec2;
  31611. var xaxis = this._tmpVec3;
  31612. var yaxis = this._tmpVec4;
  31613. var upAxis = this._tmpVec5;
  31614. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  31615. poleTarget.subtractToRef(bonePos, upAxis);
  31616. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  31617. upAxis.y = 1;
  31618. }
  31619. else {
  31620. upAxis.normalize();
  31621. }
  31622. target.subtractToRef(bonePos, yaxis);
  31623. yaxis.normalize();
  31624. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  31625. zaxis.normalize();
  31626. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  31627. xaxis.normalize();
  31628. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31629. var a = this._bone1Length;
  31630. var b = this._bone2Length;
  31631. var c = BABYLON.Vector3.Distance(bonePos, target);
  31632. if (this._maxReach > 0) {
  31633. c = Math.min(this._maxReach, c);
  31634. }
  31635. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  31636. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  31637. if (acosa > 1) {
  31638. acosa = 1;
  31639. }
  31640. if (acosb > 1) {
  31641. acosb = 1;
  31642. }
  31643. if (acosa < -1) {
  31644. acosa = -1;
  31645. }
  31646. if (acosb < -1) {
  31647. acosb = -1;
  31648. }
  31649. var angA = Math.acos(acosa);
  31650. var angB = Math.acos(acosb);
  31651. var angC = -angA - angB;
  31652. if (this._rightHandedSystem) {
  31653. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  31654. mat2.multiplyToRef(mat1, mat1);
  31655. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  31656. mat2.multiplyToRef(mat1, mat1);
  31657. }
  31658. else {
  31659. this._tmpVec1.copyFrom(this._bendAxis);
  31660. this._tmpVec1.x *= -1;
  31661. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  31662. mat2.multiplyToRef(mat1, mat1);
  31663. }
  31664. if (this.poleAngle) {
  31665. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  31666. mat1.multiplyToRef(mat2, mat1);
  31667. }
  31668. if (this.slerpAmount < 1) {
  31669. if (!this._slerping) {
  31670. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  31671. }
  31672. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  31673. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  31674. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  31675. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  31676. this._slerping = true;
  31677. }
  31678. else {
  31679. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31680. this._bone1Mat.copyFrom(mat1);
  31681. this._slerping = false;
  31682. }
  31683. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  31684. this._bone2Ang = angC;
  31685. };
  31686. return BoneIKController;
  31687. }());
  31688. BABYLON.BoneIKController = BoneIKController;
  31689. })(BABYLON || (BABYLON = {}));
  31690. //# sourceMappingURL=babylon.boneIKController.js.map
  31691. var BABYLON;
  31692. (function (BABYLON) {
  31693. var BoneLookController = (function () {
  31694. function BoneLookController(mesh, bone, target, options) {
  31695. this.upAxis = BABYLON.Vector3.Up();
  31696. this.adjustYaw = 0;
  31697. this.adjustPitch = 0;
  31698. this.adjustRoll = 0;
  31699. this._tmpVec1 = BABYLON.Vector3.Zero();
  31700. this._tmpVec2 = BABYLON.Vector3.Zero();
  31701. this._tmpVec3 = BABYLON.Vector3.Zero();
  31702. this._tmpVec4 = BABYLON.Vector3.Zero();
  31703. this._tmpMat1 = BABYLON.Matrix.Identity();
  31704. this._tmpMat2 = BABYLON.Matrix.Identity();
  31705. this.mesh = mesh;
  31706. this.bone = bone;
  31707. this.target = target;
  31708. if (options) {
  31709. if (options.adjustYaw) {
  31710. this.adjustYaw = options.adjustYaw;
  31711. }
  31712. if (options.adjustPitch) {
  31713. this.adjustPitch = options.adjustPitch;
  31714. }
  31715. if (options.adjustRoll) {
  31716. this.adjustRoll = options.adjustRoll;
  31717. }
  31718. }
  31719. }
  31720. BoneLookController.prototype.update = function () {
  31721. var bone = this.bone;
  31722. var target = this.target;
  31723. var bonePos = this._tmpVec1;
  31724. var zaxis = this._tmpVec2;
  31725. var xaxis = this._tmpVec3;
  31726. var yaxis = this._tmpVec4;
  31727. var mat1 = this._tmpMat1;
  31728. var mat2 = this._tmpMat2;
  31729. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31730. target.subtractToRef(bonePos, zaxis);
  31731. zaxis.normalize();
  31732. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31733. xaxis.normalize();
  31734. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31735. yaxis.normalize();
  31736. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31737. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31738. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31739. mat2.multiplyToRef(mat1, mat1);
  31740. }
  31741. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31742. };
  31743. return BoneLookController;
  31744. }());
  31745. BABYLON.BoneLookController = BoneLookController;
  31746. })(BABYLON || (BABYLON = {}));
  31747. //# sourceMappingURL=babylon.boneLookController.js.map
  31748. var BABYLON;
  31749. (function (BABYLON) {
  31750. var Skeleton = (function () {
  31751. function Skeleton(name, id, scene) {
  31752. this.name = name;
  31753. this.id = id;
  31754. this.bones = new Array();
  31755. this.needInitialSkinMatrix = false;
  31756. this._isDirty = true;
  31757. this._meshesWithPoseMatrix = new Array();
  31758. this._identity = BABYLON.Matrix.Identity();
  31759. this._ranges = {};
  31760. this._lastAbsoluteTransformsUpdateId = -1;
  31761. this.bones = [];
  31762. this._scene = scene;
  31763. scene.skeletons.push(this);
  31764. //make sure it will recalculate the matrix next time prepare is called.
  31765. this._isDirty = true;
  31766. }
  31767. // Members
  31768. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31769. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31770. return mesh._bonesTransformMatrices;
  31771. }
  31772. if (!this._transformMatrices) {
  31773. this.prepare();
  31774. }
  31775. return this._transformMatrices;
  31776. };
  31777. Skeleton.prototype.getScene = function () {
  31778. return this._scene;
  31779. };
  31780. // Methods
  31781. /**
  31782. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31783. */
  31784. Skeleton.prototype.toString = function (fullDetails) {
  31785. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31786. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31787. if (fullDetails) {
  31788. ret += ", Ranges: {";
  31789. var first = true;
  31790. for (var name_1 in this._ranges) {
  31791. if (first) {
  31792. ret += ", ";
  31793. first = false;
  31794. }
  31795. ret += name_1;
  31796. }
  31797. ret += "}";
  31798. }
  31799. return ret;
  31800. };
  31801. /**
  31802. * Get bone's index searching by name
  31803. * @param {string} name is bone's name to search for
  31804. * @return {number} Indice of the bone. Returns -1 if not found
  31805. */
  31806. Skeleton.prototype.getBoneIndexByName = function (name) {
  31807. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31808. if (this.bones[boneIndex].name === name) {
  31809. return boneIndex;
  31810. }
  31811. }
  31812. return -1;
  31813. };
  31814. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31815. // check name not already in use
  31816. if (!this._ranges[name]) {
  31817. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31818. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31819. if (this.bones[i].animations[0]) {
  31820. this.bones[i].animations[0].createRange(name, from, to);
  31821. }
  31822. }
  31823. }
  31824. };
  31825. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31826. if (deleteFrames === void 0) { deleteFrames = true; }
  31827. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31828. if (this.bones[i].animations[0]) {
  31829. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31830. }
  31831. }
  31832. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31833. };
  31834. Skeleton.prototype.getAnimationRange = function (name) {
  31835. return this._ranges[name];
  31836. };
  31837. /**
  31838. * Returns as an Array, all AnimationRanges defined on this skeleton
  31839. */
  31840. Skeleton.prototype.getAnimationRanges = function () {
  31841. var animationRanges = [];
  31842. var name;
  31843. var i = 0;
  31844. for (name in this._ranges) {
  31845. animationRanges[i] = this._ranges[name];
  31846. i++;
  31847. }
  31848. return animationRanges;
  31849. };
  31850. /**
  31851. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31852. */
  31853. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31854. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31855. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31856. return false;
  31857. }
  31858. var ret = true;
  31859. var frameOffset = this._getHighestAnimationFrame() + 1;
  31860. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31861. var boneDict = {};
  31862. var sourceBones = source.bones;
  31863. var nBones;
  31864. var i;
  31865. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31866. boneDict[sourceBones[i].name] = sourceBones[i];
  31867. }
  31868. if (this.bones.length !== sourceBones.length) {
  31869. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31870. ret = false;
  31871. }
  31872. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31873. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31874. var boneName = this.bones[i].name;
  31875. var sourceBone = boneDict[boneName];
  31876. if (sourceBone) {
  31877. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31878. }
  31879. else {
  31880. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31881. ret = false;
  31882. }
  31883. }
  31884. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31885. var range = source.getAnimationRange(name);
  31886. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31887. return ret;
  31888. };
  31889. Skeleton.prototype.returnToRest = function () {
  31890. for (var index = 0; index < this.bones.length; index++) {
  31891. this.bones[index].returnToRest();
  31892. }
  31893. };
  31894. Skeleton.prototype._getHighestAnimationFrame = function () {
  31895. var ret = 0;
  31896. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31897. if (this.bones[i].animations[0]) {
  31898. var highest = this.bones[i].animations[0].getHighestFrame();
  31899. if (ret < highest) {
  31900. ret = highest;
  31901. }
  31902. }
  31903. }
  31904. return ret;
  31905. };
  31906. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31907. var range = this.getAnimationRange(name);
  31908. if (!range) {
  31909. return null;
  31910. }
  31911. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31912. };
  31913. Skeleton.prototype._markAsDirty = function () {
  31914. this._isDirty = true;
  31915. };
  31916. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31917. this._meshesWithPoseMatrix.push(mesh);
  31918. };
  31919. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31920. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31921. if (index > -1) {
  31922. this._meshesWithPoseMatrix.splice(index, 1);
  31923. }
  31924. };
  31925. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31926. for (var index = 0; index < this.bones.length; index++) {
  31927. var bone = this.bones[index];
  31928. var parentBone = bone.getParent();
  31929. if (parentBone) {
  31930. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31931. }
  31932. else {
  31933. if (initialSkinMatrix) {
  31934. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31935. }
  31936. else {
  31937. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31938. }
  31939. }
  31940. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31941. }
  31942. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31943. };
  31944. Skeleton.prototype.prepare = function () {
  31945. if (!this._isDirty) {
  31946. return;
  31947. }
  31948. if (this.needInitialSkinMatrix) {
  31949. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31950. var mesh = this._meshesWithPoseMatrix[index];
  31951. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31952. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31953. }
  31954. var poseMatrix = mesh.getPoseMatrix();
  31955. // Prepare bones
  31956. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31957. var bone = this.bones[boneIndex];
  31958. if (!bone.getParent()) {
  31959. var matrix = bone.getBaseMatrix();
  31960. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31961. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31962. }
  31963. }
  31964. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31965. }
  31966. }
  31967. else {
  31968. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31969. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31970. }
  31971. this._computeTransformMatrices(this._transformMatrices, null);
  31972. }
  31973. this._isDirty = false;
  31974. this._scene._activeBones.addCount(this.bones.length, false);
  31975. };
  31976. Skeleton.prototype.getAnimatables = function () {
  31977. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31978. this._animatables = [];
  31979. for (var index = 0; index < this.bones.length; index++) {
  31980. this._animatables.push(this.bones[index]);
  31981. }
  31982. }
  31983. return this._animatables;
  31984. };
  31985. Skeleton.prototype.clone = function (name, id) {
  31986. var result = new Skeleton(name, id || name, this._scene);
  31987. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31988. for (var index = 0; index < this.bones.length; index++) {
  31989. var source = this.bones[index];
  31990. var parentBone = null;
  31991. if (source.getParent()) {
  31992. var parentIndex = this.bones.indexOf(source.getParent());
  31993. parentBone = result.bones[parentIndex];
  31994. }
  31995. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31996. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31997. }
  31998. if (this._ranges) {
  31999. result._ranges = {};
  32000. for (var rangeName in this._ranges) {
  32001. result._ranges[rangeName] = this._ranges[rangeName].clone();
  32002. }
  32003. }
  32004. this._isDirty = true;
  32005. return result;
  32006. };
  32007. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  32008. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  32009. this.bones.forEach(function (bone) {
  32010. bone.animations.forEach(function (animation) {
  32011. animation.enableBlending = true;
  32012. animation.blendingSpeed = blendingSpeed;
  32013. });
  32014. });
  32015. };
  32016. Skeleton.prototype.dispose = function () {
  32017. this._meshesWithPoseMatrix = [];
  32018. // Animations
  32019. this.getScene().stopAnimation(this);
  32020. // Remove from scene
  32021. this.getScene().removeSkeleton(this);
  32022. };
  32023. Skeleton.prototype.serialize = function () {
  32024. var serializationObject = {};
  32025. serializationObject.name = this.name;
  32026. serializationObject.id = this.id;
  32027. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  32028. serializationObject.bones = [];
  32029. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32030. for (var index = 0; index < this.bones.length; index++) {
  32031. var bone = this.bones[index];
  32032. var serializedBone = {
  32033. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  32034. name: bone.name,
  32035. matrix: bone.getLocalMatrix().toArray(),
  32036. rest: bone.getRestPose().toArray()
  32037. };
  32038. serializationObject.bones.push(serializedBone);
  32039. if (bone.length) {
  32040. serializedBone.length = bone.length;
  32041. }
  32042. if (bone.animations && bone.animations.length > 0) {
  32043. serializedBone.animation = bone.animations[0].serialize();
  32044. }
  32045. serializationObject.ranges = [];
  32046. for (var name in this._ranges) {
  32047. var range = {};
  32048. range.name = name;
  32049. range.from = this._ranges[name].from;
  32050. range.to = this._ranges[name].to;
  32051. serializationObject.ranges.push(range);
  32052. }
  32053. }
  32054. return serializationObject;
  32055. };
  32056. Skeleton.Parse = function (parsedSkeleton, scene) {
  32057. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  32058. if (parsedSkeleton.dimensionsAtRest) {
  32059. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  32060. }
  32061. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  32062. var index;
  32063. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  32064. var parsedBone = parsedSkeleton.bones[index];
  32065. var parentBone = null;
  32066. if (parsedBone.parentBoneIndex > -1) {
  32067. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  32068. }
  32069. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  32070. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  32071. if (parsedBone.length) {
  32072. bone.length = parsedBone.length;
  32073. }
  32074. if (parsedBone.animation) {
  32075. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  32076. }
  32077. }
  32078. // placed after bones, so createAnimationRange can cascade down
  32079. if (parsedSkeleton.ranges) {
  32080. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  32081. var data = parsedSkeleton.ranges[index];
  32082. skeleton.createAnimationRange(data.name, data.from, data.to);
  32083. }
  32084. }
  32085. return skeleton;
  32086. };
  32087. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  32088. if (forceUpdate === void 0) { forceUpdate = false; }
  32089. var renderId = this._scene.getRenderId();
  32090. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  32091. this.bones[0].computeAbsoluteTransforms();
  32092. this._lastAbsoluteTransformsUpdateId = renderId;
  32093. }
  32094. };
  32095. Skeleton.prototype.getPoseMatrix = function () {
  32096. var poseMatrix;
  32097. if (this._meshesWithPoseMatrix.length > 0) {
  32098. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  32099. }
  32100. return poseMatrix;
  32101. };
  32102. return Skeleton;
  32103. }());
  32104. BABYLON.Skeleton = Skeleton;
  32105. })(BABYLON || (BABYLON = {}));
  32106. //# sourceMappingURL=babylon.skeleton.js.map
  32107. var BABYLON;
  32108. (function (BABYLON) {
  32109. var PostProcess = (function () {
  32110. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  32111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32112. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32113. this.name = name;
  32114. this.width = -1;
  32115. this.height = -1;
  32116. /*
  32117. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32118. Can only be used on a single postprocess or on the last one of a chain.
  32119. */
  32120. this.enablePixelPerfectMode = false;
  32121. this._reusable = false;
  32122. this._textures = new BABYLON.SmartArray(2);
  32123. this._currentRenderTextureInd = 0;
  32124. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32125. // Events
  32126. /**
  32127. * An event triggered when the postprocess is activated.
  32128. * @type {BABYLON.Observable}
  32129. */
  32130. this.onActivateObservable = new BABYLON.Observable();
  32131. /**
  32132. * An event triggered when the postprocess changes its size.
  32133. * @type {BABYLON.Observable}
  32134. */
  32135. this.onSizeChangedObservable = new BABYLON.Observable();
  32136. /**
  32137. * An event triggered when the postprocess applies its effect.
  32138. * @type {BABYLON.Observable}
  32139. */
  32140. this.onApplyObservable = new BABYLON.Observable();
  32141. /**
  32142. * An event triggered before rendering the postprocess
  32143. * @type {BABYLON.Observable}
  32144. */
  32145. this.onBeforeRenderObservable = new BABYLON.Observable();
  32146. /**
  32147. * An event triggered after rendering the postprocess
  32148. * @type {BABYLON.Observable}
  32149. */
  32150. this.onAfterRenderObservable = new BABYLON.Observable();
  32151. if (camera != null) {
  32152. this._camera = camera;
  32153. this._scene = camera.getScene();
  32154. camera.attachPostProcess(this);
  32155. this._engine = this._scene.getEngine();
  32156. }
  32157. else {
  32158. this._engine = engine;
  32159. }
  32160. this._options = options;
  32161. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32162. this._reusable = reusable || false;
  32163. this._textureType = textureType;
  32164. this._samplers = samplers || [];
  32165. this._samplers.push("textureSampler");
  32166. this._fragmentUrl = fragmentUrl;
  32167. this._parameters = parameters || [];
  32168. this._parameters.push("scale");
  32169. this.updateEffect(defines);
  32170. }
  32171. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32172. set: function (callback) {
  32173. if (this._onActivateObserver) {
  32174. this.onActivateObservable.remove(this._onActivateObserver);
  32175. }
  32176. this._onActivateObserver = this.onActivateObservable.add(callback);
  32177. },
  32178. enumerable: true,
  32179. configurable: true
  32180. });
  32181. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32182. set: function (callback) {
  32183. if (this._onSizeChangedObserver) {
  32184. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32185. }
  32186. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32187. },
  32188. enumerable: true,
  32189. configurable: true
  32190. });
  32191. Object.defineProperty(PostProcess.prototype, "onApply", {
  32192. set: function (callback) {
  32193. if (this._onApplyObserver) {
  32194. this.onApplyObservable.remove(this._onApplyObserver);
  32195. }
  32196. this._onApplyObserver = this.onApplyObservable.add(callback);
  32197. },
  32198. enumerable: true,
  32199. configurable: true
  32200. });
  32201. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32202. set: function (callback) {
  32203. if (this._onBeforeRenderObserver) {
  32204. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32205. }
  32206. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32207. },
  32208. enumerable: true,
  32209. configurable: true
  32210. });
  32211. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32212. set: function (callback) {
  32213. if (this._onAfterRenderObserver) {
  32214. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32215. }
  32216. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32217. },
  32218. enumerable: true,
  32219. configurable: true
  32220. });
  32221. PostProcess.prototype.updateEffect = function (defines) {
  32222. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  32223. };
  32224. PostProcess.prototype.isReusable = function () {
  32225. return this._reusable;
  32226. };
  32227. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32228. PostProcess.prototype.markTextureDirty = function () {
  32229. this.width = -1;
  32230. };
  32231. PostProcess.prototype.activate = function (camera, sourceTexture) {
  32232. camera = camera || this._camera;
  32233. var scene = camera.getScene();
  32234. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32235. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32236. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32237. var desiredWidth = this._options.width || requiredWidth;
  32238. var desiredHeight = this._options.height || requiredHeight;
  32239. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32240. if (!this._options.width) {
  32241. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  32242. }
  32243. if (!this._options.height) {
  32244. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  32245. }
  32246. }
  32247. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32248. if (this._textures.length > 0) {
  32249. for (var i = 0; i < this._textures.length; i++) {
  32250. this._engine._releaseTexture(this._textures.data[i]);
  32251. }
  32252. this._textures.reset();
  32253. }
  32254. this.width = desiredWidth;
  32255. this.height = desiredHeight;
  32256. var textureSize = { width: this.width, height: this.height };
  32257. var textureOptions = {
  32258. generateMipMaps: false,
  32259. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  32260. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  32261. samplingMode: this.renderTargetSamplingMode,
  32262. type: this._textureType
  32263. };
  32264. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32265. if (this._reusable) {
  32266. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32267. }
  32268. this.onSizeChangedObservable.notifyObservers(this);
  32269. }
  32270. if (this.enablePixelPerfectMode) {
  32271. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32272. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  32273. }
  32274. else {
  32275. this._scaleRatio.copyFromFloats(1, 1);
  32276. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  32277. }
  32278. this.onActivateObservable.notifyObservers(camera);
  32279. // Clear
  32280. if (this.clearColor) {
  32281. this._engine.clear(this.clearColor, true, true, true);
  32282. }
  32283. else {
  32284. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  32285. }
  32286. if (this._reusable) {
  32287. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32288. }
  32289. };
  32290. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32291. get: function () {
  32292. return this._effect.isSupported;
  32293. },
  32294. enumerable: true,
  32295. configurable: true
  32296. });
  32297. PostProcess.prototype.apply = function () {
  32298. // Check
  32299. if (!this._effect.isReady())
  32300. return null;
  32301. // States
  32302. this._engine.enableEffect(this._effect);
  32303. this._engine.setState(false);
  32304. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32305. this._engine.setDepthBuffer(false);
  32306. this._engine.setDepthWrite(false);
  32307. // Texture
  32308. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  32309. // Parameters
  32310. this._effect.setVector2("scale", this._scaleRatio);
  32311. this.onApplyObservable.notifyObservers(this._effect);
  32312. return this._effect;
  32313. };
  32314. PostProcess.prototype.dispose = function (camera) {
  32315. camera = camera || this._camera;
  32316. if (this._textures.length > 0) {
  32317. for (var i = 0; i < this._textures.length; i++) {
  32318. this._engine._releaseTexture(this._textures.data[i]);
  32319. }
  32320. this._textures.reset();
  32321. }
  32322. if (!camera) {
  32323. return;
  32324. }
  32325. camera.detachPostProcess(this);
  32326. var index = camera._postProcesses.indexOf(this);
  32327. if (index === 0 && camera._postProcesses.length > 0) {
  32328. this._camera._postProcesses[0].markTextureDirty();
  32329. }
  32330. this.onActivateObservable.clear();
  32331. this.onAfterRenderObservable.clear();
  32332. this.onApplyObservable.clear();
  32333. this.onBeforeRenderObservable.clear();
  32334. this.onSizeChangedObservable.clear();
  32335. };
  32336. return PostProcess;
  32337. }());
  32338. BABYLON.PostProcess = PostProcess;
  32339. })(BABYLON || (BABYLON = {}));
  32340. //# sourceMappingURL=babylon.postProcess.js.map
  32341. var BABYLON;
  32342. (function (BABYLON) {
  32343. var PostProcessManager = (function () {
  32344. function PostProcessManager(scene) {
  32345. this._vertexBuffers = {};
  32346. this._scene = scene;
  32347. }
  32348. PostProcessManager.prototype._prepareBuffers = function () {
  32349. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32350. return;
  32351. }
  32352. // VBO
  32353. var vertices = [];
  32354. vertices.push(1, 1);
  32355. vertices.push(-1, 1);
  32356. vertices.push(-1, -1);
  32357. vertices.push(1, -1);
  32358. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32359. // Indices
  32360. var indices = [];
  32361. indices.push(0);
  32362. indices.push(1);
  32363. indices.push(2);
  32364. indices.push(0);
  32365. indices.push(2);
  32366. indices.push(3);
  32367. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32368. };
  32369. // Methods
  32370. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  32371. var postProcesses = this._scene.activeCamera._postProcesses;
  32372. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32373. return false;
  32374. }
  32375. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  32376. return true;
  32377. };
  32378. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  32379. var engine = this._scene.getEngine();
  32380. for (var index = 0; index < postProcesses.length; index++) {
  32381. if (index < postProcesses.length - 1) {
  32382. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32383. }
  32384. else {
  32385. if (targetTexture) {
  32386. engine.bindFramebuffer(targetTexture);
  32387. }
  32388. else {
  32389. engine.restoreDefaultFramebuffer();
  32390. }
  32391. }
  32392. var pp = postProcesses[index];
  32393. var effect = pp.apply();
  32394. if (effect) {
  32395. pp.onBeforeRenderObservable.notifyObservers(effect);
  32396. // VBOs
  32397. this._prepareBuffers();
  32398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32399. // Draw order
  32400. engine.draw(true, 0, 6);
  32401. pp.onAfterRenderObservable.notifyObservers(effect);
  32402. }
  32403. }
  32404. // Restore depth buffer
  32405. engine.setDepthBuffer(true);
  32406. engine.setDepthWrite(true);
  32407. };
  32408. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  32409. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  32410. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32411. return;
  32412. }
  32413. var engine = this._scene.getEngine();
  32414. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32415. if (index < len - 1) {
  32416. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32417. }
  32418. else {
  32419. if (targetTexture) {
  32420. engine.bindFramebuffer(targetTexture, faceIndex);
  32421. }
  32422. else {
  32423. engine.restoreDefaultFramebuffer();
  32424. }
  32425. }
  32426. if (doNotPresent) {
  32427. break;
  32428. }
  32429. var pp = postProcesses[index];
  32430. var effect = pp.apply();
  32431. if (effect) {
  32432. pp.onBeforeRenderObservable.notifyObservers(effect);
  32433. // VBOs
  32434. this._prepareBuffers();
  32435. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32436. // Draw order
  32437. engine.draw(true, 0, 6);
  32438. pp.onAfterRenderObservable.notifyObservers(effect);
  32439. }
  32440. }
  32441. // Restore depth buffer
  32442. engine.setDepthBuffer(true);
  32443. engine.setDepthWrite(true);
  32444. };
  32445. PostProcessManager.prototype.dispose = function () {
  32446. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32447. if (buffer) {
  32448. buffer.dispose();
  32449. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32450. }
  32451. if (this._indexBuffer) {
  32452. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32453. this._indexBuffer = null;
  32454. }
  32455. };
  32456. return PostProcessManager;
  32457. }());
  32458. BABYLON.PostProcessManager = PostProcessManager;
  32459. })(BABYLON || (BABYLON = {}));
  32460. //# sourceMappingURL=babylon.postProcessManager.js.map
  32461. var BABYLON;
  32462. (function (BABYLON) {
  32463. var PassPostProcess = (function (_super) {
  32464. __extends(PassPostProcess, _super);
  32465. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  32466. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  32467. }
  32468. return PassPostProcess;
  32469. }(BABYLON.PostProcess));
  32470. BABYLON.PassPostProcess = PassPostProcess;
  32471. })(BABYLON || (BABYLON = {}));
  32472. //# sourceMappingURL=babylon.passPostProcess.js.map
  32473. var BABYLON;
  32474. (function (BABYLON) {
  32475. /**
  32476. * This is a holder class for the physics joint created by the physics plugin.
  32477. * It holds a set of functions to control the underlying joint.
  32478. */
  32479. var PhysicsJoint = (function () {
  32480. function PhysicsJoint(type, jointData) {
  32481. this.type = type;
  32482. this.jointData = jointData;
  32483. jointData.nativeParams = jointData.nativeParams || {};
  32484. }
  32485. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  32486. get: function () {
  32487. return this._physicsJoint;
  32488. },
  32489. set: function (newJoint) {
  32490. if (this._physicsJoint) {
  32491. }
  32492. this._physicsJoint = newJoint;
  32493. },
  32494. enumerable: true,
  32495. configurable: true
  32496. });
  32497. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  32498. set: function (physicsPlugin) {
  32499. this._physicsPlugin = physicsPlugin;
  32500. },
  32501. enumerable: true,
  32502. configurable: true
  32503. });
  32504. /**
  32505. * Execute a function that is physics-plugin specific.
  32506. * @param {Function} func the function that will be executed.
  32507. * It accepts two parameters: the physics world and the physics joint.
  32508. */
  32509. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  32510. func(this._physicsPlugin.world, this._physicsJoint);
  32511. };
  32512. return PhysicsJoint;
  32513. }());
  32514. //TODO check if the native joints are the same
  32515. //Joint Types
  32516. PhysicsJoint.DistanceJoint = 0;
  32517. PhysicsJoint.HingeJoint = 1;
  32518. PhysicsJoint.BallAndSocketJoint = 2;
  32519. PhysicsJoint.WheelJoint = 3;
  32520. PhysicsJoint.SliderJoint = 4;
  32521. //OIMO
  32522. PhysicsJoint.PrismaticJoint = 5;
  32523. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  32524. PhysicsJoint.UniversalJoint = 6;
  32525. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  32526. //Cannon
  32527. //Similar to a Ball-Joint. Different in params
  32528. PhysicsJoint.PointToPointJoint = 8;
  32529. //Cannon only at the moment
  32530. PhysicsJoint.SpringJoint = 9;
  32531. PhysicsJoint.LockJoint = 10;
  32532. BABYLON.PhysicsJoint = PhysicsJoint;
  32533. /**
  32534. * A class representing a physics distance joint.
  32535. */
  32536. var DistanceJoint = (function (_super) {
  32537. __extends(DistanceJoint, _super);
  32538. function DistanceJoint(jointData) {
  32539. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  32540. }
  32541. /**
  32542. * Update the predefined distance.
  32543. */
  32544. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  32545. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  32546. };
  32547. return DistanceJoint;
  32548. }(PhysicsJoint));
  32549. BABYLON.DistanceJoint = DistanceJoint;
  32550. var MotorEnabledJoint = (function (_super) {
  32551. __extends(MotorEnabledJoint, _super);
  32552. function MotorEnabledJoint(type, jointData) {
  32553. return _super.call(this, type, jointData) || this;
  32554. }
  32555. /**
  32556. * Set the motor values.
  32557. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32558. * @param {number} force the force to apply
  32559. * @param {number} maxForce max force for this motor.
  32560. */
  32561. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  32562. this._physicsPlugin.setMotor(this, force, maxForce);
  32563. };
  32564. /**
  32565. * Set the motor's limits.
  32566. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32567. */
  32568. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32569. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32570. };
  32571. return MotorEnabledJoint;
  32572. }(PhysicsJoint));
  32573. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  32574. /**
  32575. * This class represents a single hinge physics joint
  32576. */
  32577. var HingeJoint = (function (_super) {
  32578. __extends(HingeJoint, _super);
  32579. function HingeJoint(jointData) {
  32580. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  32581. }
  32582. /**
  32583. * Set the motor values.
  32584. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32585. * @param {number} force the force to apply
  32586. * @param {number} maxForce max force for this motor.
  32587. */
  32588. HingeJoint.prototype.setMotor = function (force, maxForce) {
  32589. this._physicsPlugin.setMotor(this, force, maxForce);
  32590. };
  32591. /**
  32592. * Set the motor's limits.
  32593. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32594. */
  32595. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32596. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32597. };
  32598. return HingeJoint;
  32599. }(MotorEnabledJoint));
  32600. BABYLON.HingeJoint = HingeJoint;
  32601. /**
  32602. * This class represents a dual hinge physics joint (same as wheel joint)
  32603. */
  32604. var Hinge2Joint = (function (_super) {
  32605. __extends(Hinge2Joint, _super);
  32606. function Hinge2Joint(jointData) {
  32607. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  32608. }
  32609. /**
  32610. * Set the motor values.
  32611. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32612. * @param {number} force the force to apply
  32613. * @param {number} maxForce max force for this motor.
  32614. * @param {motorIndex} the motor's index, 0 or 1.
  32615. */
  32616. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  32617. if (motorIndex === void 0) { motorIndex = 0; }
  32618. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  32619. };
  32620. /**
  32621. * Set the motor limits.
  32622. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32623. * @param {number} upperLimit the upper limit
  32624. * @param {number} lowerLimit lower limit
  32625. * @param {motorIndex} the motor's index, 0 or 1.
  32626. */
  32627. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  32628. if (motorIndex === void 0) { motorIndex = 0; }
  32629. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  32630. };
  32631. return Hinge2Joint;
  32632. }(MotorEnabledJoint));
  32633. BABYLON.Hinge2Joint = Hinge2Joint;
  32634. })(BABYLON || (BABYLON = {}));
  32635. //# sourceMappingURL=babylon.physicsJoint.js.map
  32636. var BABYLON;
  32637. (function (BABYLON) {
  32638. var PhysicsImpostor = (function () {
  32639. function PhysicsImpostor(object, type, _options, _scene) {
  32640. if (_options === void 0) { _options = { mass: 0 }; }
  32641. var _this = this;
  32642. this.object = object;
  32643. this.type = type;
  32644. this._options = _options;
  32645. this._scene = _scene;
  32646. this._bodyUpdateRequired = false;
  32647. this._onBeforePhysicsStepCallbacks = new Array();
  32648. this._onAfterPhysicsStepCallbacks = new Array();
  32649. this._onPhysicsCollideCallbacks = [];
  32650. this._deltaPosition = BABYLON.Vector3.Zero();
  32651. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  32652. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  32653. /**
  32654. * this function is executed by the physics engine.
  32655. */
  32656. this.beforeStep = function () {
  32657. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  32658. //conjugate deltaRotation
  32659. if (_this._deltaRotationConjugated) {
  32660. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  32661. }
  32662. else {
  32663. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  32664. }
  32665. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  32666. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  32667. func(_this);
  32668. });
  32669. };
  32670. /**
  32671. * this function is executed by the physics engine.
  32672. */
  32673. this.afterStep = function () {
  32674. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  32675. func(_this);
  32676. });
  32677. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  32678. _this.object.position.addInPlace(_this._deltaPosition);
  32679. if (_this._deltaRotation) {
  32680. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  32681. }
  32682. };
  32683. /**
  32684. * Legacy collision detection event support
  32685. */
  32686. this.onCollideEvent = null;
  32687. //event and body object due to cannon's event-based architecture.
  32688. this.onCollide = function (e) {
  32689. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  32690. return;
  32691. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  32692. if (otherImpostor) {
  32693. // Legacy collision detection event support
  32694. if (_this.onCollideEvent) {
  32695. _this.onCollideEvent(_this, otherImpostor);
  32696. }
  32697. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  32698. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  32699. }).forEach(function (obj) {
  32700. obj.callback(_this, otherImpostor);
  32701. });
  32702. }
  32703. };
  32704. //sanity check!
  32705. if (!this.object) {
  32706. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  32707. return;
  32708. }
  32709. //legacy support for old syntax.
  32710. if (!this._scene && object.getScene) {
  32711. this._scene = object.getScene();
  32712. }
  32713. this._physicsEngine = this._scene.getPhysicsEngine();
  32714. if (!this._physicsEngine) {
  32715. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  32716. }
  32717. else {
  32718. //set the object's quaternion, if not set
  32719. if (!this.object.rotationQuaternion) {
  32720. if (this.object.rotation) {
  32721. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  32722. }
  32723. else {
  32724. this.object.rotationQuaternion = new BABYLON.Quaternion();
  32725. }
  32726. }
  32727. //default options params
  32728. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32729. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32730. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32731. this._joints = [];
  32732. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32733. if (!this.object.parent) {
  32734. this._init();
  32735. }
  32736. }
  32737. }
  32738. /**
  32739. * This function will completly initialize this impostor.
  32740. * It will create a new body - but only if this mesh has no parent.
  32741. * If it has, this impostor will not be used other than to define the impostor
  32742. * of the child mesh.
  32743. */
  32744. PhysicsImpostor.prototype._init = function () {
  32745. this._physicsEngine.removeImpostor(this);
  32746. this.physicsBody = null;
  32747. this._parent = this._parent || this._getPhysicsParent();
  32748. if (!this.parent) {
  32749. this._physicsEngine.addImpostor(this);
  32750. }
  32751. };
  32752. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32753. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32754. var parentMesh = this.object.parent;
  32755. return parentMesh.physicsImpostor;
  32756. }
  32757. return;
  32758. };
  32759. /**
  32760. * Should a new body be generated.
  32761. */
  32762. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32763. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32764. };
  32765. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32766. this.forceUpdate();
  32767. };
  32768. /**
  32769. * Force a regeneration of this or the parent's impostor's body.
  32770. * Use under cautious - This will remove all joints already implemented.
  32771. */
  32772. PhysicsImpostor.prototype.forceUpdate = function () {
  32773. this._init();
  32774. if (this.parent) {
  32775. this.parent.forceUpdate();
  32776. }
  32777. };
  32778. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32779. /*public get mesh(): AbstractMesh {
  32780. return this._mesh;
  32781. }*/
  32782. /**
  32783. * Gets the body that holds this impostor. Either its own, or its parent.
  32784. */
  32785. get: function () {
  32786. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32787. },
  32788. /**
  32789. * Set the physics body. Used mainly by the physics engine/plugin
  32790. */
  32791. set: function (physicsBody) {
  32792. if (this._physicsBody) {
  32793. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32794. }
  32795. this._physicsBody = physicsBody;
  32796. this.resetUpdateFlags();
  32797. },
  32798. enumerable: true,
  32799. configurable: true
  32800. });
  32801. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32802. get: function () {
  32803. return this._parent;
  32804. },
  32805. set: function (value) {
  32806. this._parent = value;
  32807. },
  32808. enumerable: true,
  32809. configurable: true
  32810. });
  32811. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32812. this._bodyUpdateRequired = false;
  32813. };
  32814. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32815. if (this.object.getBoundingInfo) {
  32816. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32817. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32818. }
  32819. else {
  32820. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32821. }
  32822. };
  32823. PhysicsImpostor.prototype.getObjectCenter = function () {
  32824. if (this.object.getBoundingInfo) {
  32825. return this.object.getBoundingInfo().boundingBox.center;
  32826. }
  32827. else {
  32828. return this.object.position;
  32829. }
  32830. };
  32831. /**
  32832. * Get a specific parametes from the options parameter.
  32833. */
  32834. PhysicsImpostor.prototype.getParam = function (paramName) {
  32835. return this._options[paramName];
  32836. };
  32837. /**
  32838. * Sets a specific parameter in the options given to the physics plugin
  32839. */
  32840. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32841. this._options[paramName] = value;
  32842. this._bodyUpdateRequired = true;
  32843. };
  32844. /**
  32845. * Specifically change the body's mass option. Won't recreate the physics body object
  32846. */
  32847. PhysicsImpostor.prototype.setMass = function (mass) {
  32848. if (this.getParam("mass") !== mass) {
  32849. this.setParam("mass", mass);
  32850. }
  32851. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32852. };
  32853. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32854. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32855. };
  32856. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32857. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32858. };
  32859. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32860. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32861. };
  32862. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32863. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32864. };
  32865. /**
  32866. * Execute a function with the physics plugin native code.
  32867. * Provide a function the will have two variables - the world object and the physics body object.
  32868. */
  32869. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32870. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32871. };
  32872. /**
  32873. * Register a function that will be executed before the physics world is stepping forward.
  32874. */
  32875. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32876. this._onBeforePhysicsStepCallbacks.push(func);
  32877. };
  32878. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32879. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32880. if (index > -1) {
  32881. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32882. }
  32883. else {
  32884. BABYLON.Tools.Warn("Function to remove was not found");
  32885. }
  32886. };
  32887. /**
  32888. * Register a function that will be executed after the physics step
  32889. */
  32890. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32891. this._onAfterPhysicsStepCallbacks.push(func);
  32892. };
  32893. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32894. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32895. if (index > -1) {
  32896. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32897. }
  32898. else {
  32899. BABYLON.Tools.Warn("Function to remove was not found");
  32900. }
  32901. };
  32902. /**
  32903. * register a function that will be executed when this impostor collides against a different body.
  32904. */
  32905. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32906. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32907. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32908. };
  32909. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32910. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32911. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32912. if (index > -1) {
  32913. this._onPhysicsCollideCallbacks.splice(index, 1);
  32914. }
  32915. else {
  32916. BABYLON.Tools.Warn("Function to remove was not found");
  32917. }
  32918. };
  32919. /**
  32920. * Apply a force
  32921. */
  32922. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32923. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32924. };
  32925. /**
  32926. * Apply an impulse
  32927. */
  32928. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32929. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32930. };
  32931. /**
  32932. * A help function to create a joint.
  32933. */
  32934. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32935. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32936. this.addJoint(otherImpostor, joint);
  32937. };
  32938. /**
  32939. * Add a joint to this impostor with a different impostor.
  32940. */
  32941. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32942. this._joints.push({
  32943. otherImpostor: otherImpostor,
  32944. joint: joint
  32945. });
  32946. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32947. };
  32948. /**
  32949. * Will keep this body still, in a sleep mode.
  32950. */
  32951. PhysicsImpostor.prototype.sleep = function () {
  32952. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32953. };
  32954. /**
  32955. * Wake the body up.
  32956. */
  32957. PhysicsImpostor.prototype.wakeUp = function () {
  32958. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32959. };
  32960. PhysicsImpostor.prototype.clone = function (newObject) {
  32961. if (!newObject)
  32962. return null;
  32963. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32964. };
  32965. PhysicsImpostor.prototype.dispose = function () {
  32966. var _this = this;
  32967. //no dispose if no physics engine is available.
  32968. if (!this._physicsEngine) {
  32969. return;
  32970. }
  32971. this._joints.forEach(function (j) {
  32972. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32973. });
  32974. //dispose the physics body
  32975. this._physicsEngine.removeImpostor(this);
  32976. if (this.parent) {
  32977. this.parent.forceUpdate();
  32978. }
  32979. else {
  32980. }
  32981. };
  32982. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32983. this._deltaPosition.copyFrom(position);
  32984. };
  32985. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32986. if (!this._deltaRotation) {
  32987. this._deltaRotation = new BABYLON.Quaternion();
  32988. }
  32989. this._deltaRotation.copyFrom(rotation);
  32990. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32991. };
  32992. return PhysicsImpostor;
  32993. }());
  32994. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32995. //Impostor types
  32996. PhysicsImpostor.NoImpostor = 0;
  32997. PhysicsImpostor.SphereImpostor = 1;
  32998. PhysicsImpostor.BoxImpostor = 2;
  32999. PhysicsImpostor.PlaneImpostor = 3;
  33000. PhysicsImpostor.MeshImpostor = 4;
  33001. PhysicsImpostor.CylinderImpostor = 7;
  33002. PhysicsImpostor.ParticleImpostor = 8;
  33003. PhysicsImpostor.HeightmapImpostor = 9;
  33004. BABYLON.PhysicsImpostor = PhysicsImpostor;
  33005. })(BABYLON || (BABYLON = {}));
  33006. //# sourceMappingURL=babylon.physicsImpostor.js.map
  33007. var BABYLON;
  33008. (function (BABYLON) {
  33009. var PhysicsEngine = (function () {
  33010. function PhysicsEngine(gravity, _physicsPlugin) {
  33011. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  33012. this._physicsPlugin = _physicsPlugin;
  33013. //new methods and parameters
  33014. this._impostors = [];
  33015. this._joints = [];
  33016. if (!this._physicsPlugin.isSupported()) {
  33017. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  33018. + "Please make sure it is included.");
  33019. }
  33020. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  33021. this.setGravity(gravity);
  33022. this.setTimeStep();
  33023. }
  33024. PhysicsEngine.prototype.setGravity = function (gravity) {
  33025. this.gravity = gravity;
  33026. this._physicsPlugin.setGravity(this.gravity);
  33027. };
  33028. /**
  33029. * Set the time step of the physics engine.
  33030. * default is 1/60.
  33031. * To slow it down, enter 1/600 for example.
  33032. * To speed it up, 1/30
  33033. * @param {number} newTimeStep the new timestep to apply to this world.
  33034. */
  33035. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  33036. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  33037. this._physicsPlugin.setTimeStep(newTimeStep);
  33038. };
  33039. PhysicsEngine.prototype.dispose = function () {
  33040. this._impostors.forEach(function (impostor) {
  33041. impostor.dispose();
  33042. });
  33043. this._physicsPlugin.dispose();
  33044. };
  33045. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  33046. return this._physicsPlugin.name;
  33047. };
  33048. /**
  33049. * Adding a new impostor for the impostor tracking.
  33050. * This will be done by the impostor itself.
  33051. * @param {PhysicsImpostor} impostor the impostor to add
  33052. */
  33053. PhysicsEngine.prototype.addImpostor = function (impostor) {
  33054. impostor.uniqueId = this._impostors.push(impostor);
  33055. //if no parent, generate the body
  33056. if (!impostor.parent) {
  33057. this._physicsPlugin.generatePhysicsBody(impostor);
  33058. }
  33059. };
  33060. /**
  33061. * Remove an impostor from the engine.
  33062. * This impostor and its mesh will not longer be updated by the physics engine.
  33063. * @param {PhysicsImpostor} impostor the impostor to remove
  33064. */
  33065. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  33066. var index = this._impostors.indexOf(impostor);
  33067. if (index > -1) {
  33068. var removed = this._impostors.splice(index, 1);
  33069. //Is it needed?
  33070. if (removed.length) {
  33071. //this will also remove it from the world.
  33072. removed[0].physicsBody = null;
  33073. }
  33074. }
  33075. };
  33076. /**
  33077. * Add a joint to the physics engine
  33078. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  33079. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  33080. * @param {PhysicsJoint} the joint that will connect both impostors.
  33081. */
  33082. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  33083. var impostorJoint = {
  33084. mainImpostor: mainImpostor,
  33085. connectedImpostor: connectedImpostor,
  33086. joint: joint
  33087. };
  33088. joint.physicsPlugin = this._physicsPlugin;
  33089. this._joints.push(impostorJoint);
  33090. this._physicsPlugin.generateJoint(impostorJoint);
  33091. };
  33092. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  33093. var matchingJoints = this._joints.filter(function (impostorJoint) {
  33094. return (impostorJoint.connectedImpostor === connectedImpostor
  33095. && impostorJoint.joint === joint
  33096. && impostorJoint.mainImpostor === mainImpostor);
  33097. });
  33098. if (matchingJoints.length) {
  33099. this._physicsPlugin.removeJoint(matchingJoints[0]);
  33100. }
  33101. };
  33102. /**
  33103. * Called by the scene. no need to call it.
  33104. */
  33105. PhysicsEngine.prototype._step = function (delta) {
  33106. var _this = this;
  33107. //check if any mesh has no body / requires an update
  33108. this._impostors.forEach(function (impostor) {
  33109. if (impostor.isBodyInitRequired()) {
  33110. _this._physicsPlugin.generatePhysicsBody(impostor);
  33111. }
  33112. });
  33113. if (delta > 0.1) {
  33114. delta = 0.1;
  33115. }
  33116. else if (delta <= 0) {
  33117. delta = 1.0 / 60.0;
  33118. }
  33119. this._physicsPlugin.executeStep(delta, this._impostors);
  33120. };
  33121. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  33122. return this._physicsPlugin;
  33123. };
  33124. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  33125. for (var i = 0; i < this._impostors.length; ++i) {
  33126. if (this._impostors[i].object === object) {
  33127. return this._impostors[i];
  33128. }
  33129. }
  33130. };
  33131. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  33132. for (var i = 0; i < this._impostors.length; ++i) {
  33133. if (this._impostors[i].physicsBody === body) {
  33134. return this._impostors[i];
  33135. }
  33136. }
  33137. };
  33138. return PhysicsEngine;
  33139. }());
  33140. // Statics, Legacy support.
  33141. /**
  33142. * @Deprecated
  33143. *
  33144. */
  33145. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  33146. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  33147. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  33148. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  33149. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  33150. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  33151. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  33152. PhysicsEngine.CapsuleImpostor = -1;
  33153. PhysicsEngine.ConeImpostor = -1;
  33154. PhysicsEngine.ConvexHullImpostor = -1;
  33155. PhysicsEngine.Epsilon = 0.001;
  33156. BABYLON.PhysicsEngine = PhysicsEngine;
  33157. })(BABYLON || (BABYLON = {}));
  33158. //# sourceMappingURL=babylon.physicsEngine.js.map
  33159. var BABYLON;
  33160. (function (BABYLON) {
  33161. var VertexData = (function () {
  33162. function VertexData() {
  33163. }
  33164. VertexData.prototype.set = function (data, kind) {
  33165. switch (kind) {
  33166. case BABYLON.VertexBuffer.PositionKind:
  33167. this.positions = data;
  33168. break;
  33169. case BABYLON.VertexBuffer.NormalKind:
  33170. this.normals = data;
  33171. break;
  33172. case BABYLON.VertexBuffer.UVKind:
  33173. this.uvs = data;
  33174. break;
  33175. case BABYLON.VertexBuffer.UV2Kind:
  33176. this.uvs2 = data;
  33177. break;
  33178. case BABYLON.VertexBuffer.UV3Kind:
  33179. this.uvs3 = data;
  33180. break;
  33181. case BABYLON.VertexBuffer.UV4Kind:
  33182. this.uvs4 = data;
  33183. break;
  33184. case BABYLON.VertexBuffer.UV5Kind:
  33185. this.uvs5 = data;
  33186. break;
  33187. case BABYLON.VertexBuffer.UV6Kind:
  33188. this.uvs6 = data;
  33189. break;
  33190. case BABYLON.VertexBuffer.ColorKind:
  33191. this.colors = data;
  33192. break;
  33193. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33194. this.matricesIndices = data;
  33195. break;
  33196. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33197. this.matricesWeights = data;
  33198. break;
  33199. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33200. this.matricesIndicesExtra = data;
  33201. break;
  33202. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33203. this.matricesWeightsExtra = data;
  33204. break;
  33205. }
  33206. };
  33207. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33208. this._applyTo(mesh, updatable);
  33209. };
  33210. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33211. this._applyTo(geometry, updatable);
  33212. };
  33213. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33214. this._update(mesh);
  33215. };
  33216. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33217. this._update(geometry);
  33218. };
  33219. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33220. if (this.positions) {
  33221. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33222. }
  33223. if (this.normals) {
  33224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33225. }
  33226. if (this.uvs) {
  33227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33228. }
  33229. if (this.uvs2) {
  33230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33231. }
  33232. if (this.uvs3) {
  33233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33234. }
  33235. if (this.uvs4) {
  33236. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33237. }
  33238. if (this.uvs5) {
  33239. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33240. }
  33241. if (this.uvs6) {
  33242. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33243. }
  33244. if (this.colors) {
  33245. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33246. }
  33247. if (this.matricesIndices) {
  33248. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33249. }
  33250. if (this.matricesWeights) {
  33251. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33252. }
  33253. if (this.matricesIndicesExtra) {
  33254. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33255. }
  33256. if (this.matricesWeightsExtra) {
  33257. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33258. }
  33259. if (this.indices) {
  33260. meshOrGeometry.setIndices(this.indices);
  33261. }
  33262. };
  33263. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33264. if (this.positions) {
  33265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33266. }
  33267. if (this.normals) {
  33268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33269. }
  33270. if (this.uvs) {
  33271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33272. }
  33273. if (this.uvs2) {
  33274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33275. }
  33276. if (this.uvs3) {
  33277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33278. }
  33279. if (this.uvs4) {
  33280. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33281. }
  33282. if (this.uvs5) {
  33283. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33284. }
  33285. if (this.uvs6) {
  33286. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33287. }
  33288. if (this.colors) {
  33289. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33290. }
  33291. if (this.matricesIndices) {
  33292. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33293. }
  33294. if (this.matricesWeights) {
  33295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33296. }
  33297. if (this.matricesIndicesExtra) {
  33298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33299. }
  33300. if (this.matricesWeightsExtra) {
  33301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33302. }
  33303. if (this.indices) {
  33304. meshOrGeometry.setIndices(this.indices);
  33305. }
  33306. };
  33307. VertexData.prototype.transform = function (matrix) {
  33308. var transformed = BABYLON.Vector3.Zero();
  33309. var index;
  33310. if (this.positions) {
  33311. var position = BABYLON.Vector3.Zero();
  33312. for (index = 0; index < this.positions.length; index += 3) {
  33313. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33314. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33315. this.positions[index] = transformed.x;
  33316. this.positions[index + 1] = transformed.y;
  33317. this.positions[index + 2] = transformed.z;
  33318. }
  33319. }
  33320. if (this.normals) {
  33321. var normal = BABYLON.Vector3.Zero();
  33322. for (index = 0; index < this.normals.length; index += 3) {
  33323. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33324. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33325. this.normals[index] = transformed.x;
  33326. this.normals[index + 1] = transformed.y;
  33327. this.normals[index + 2] = transformed.z;
  33328. }
  33329. }
  33330. };
  33331. VertexData.prototype.merge = function (other) {
  33332. if (other.indices) {
  33333. if (!this.indices) {
  33334. this.indices = [];
  33335. }
  33336. var offset = this.positions ? this.positions.length / 3 : 0;
  33337. for (var index = 0; index < other.indices.length; index++) {
  33338. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33339. this.indices.push(other.indices[index] + offset);
  33340. }
  33341. }
  33342. this.positions = this._mergeElement(this.positions, other.positions);
  33343. this.normals = this._mergeElement(this.normals, other.normals);
  33344. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33345. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33346. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33347. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33348. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33349. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33350. this.colors = this._mergeElement(this.colors, other.colors);
  33351. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33352. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33353. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33354. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33355. };
  33356. VertexData.prototype._mergeElement = function (source, other) {
  33357. if (!other)
  33358. return source;
  33359. if (!source)
  33360. return other;
  33361. var len = other.length + source.length;
  33362. var isSrcTypedArray = source instanceof Float32Array;
  33363. var isOthTypedArray = other instanceof Float32Array;
  33364. // use non-loop method when the source is Float32Array
  33365. if (isSrcTypedArray) {
  33366. var ret32 = new Float32Array(len);
  33367. ret32.set(source);
  33368. ret32.set(other, source.length);
  33369. return ret32;
  33370. }
  33371. else if (!isOthTypedArray) {
  33372. return source.concat(other);
  33373. }
  33374. else {
  33375. var ret = source.slice(0); // copy source to a separate array
  33376. for (var i = 0, len = other.length; i < len; i++) {
  33377. ret.push(other[i]);
  33378. }
  33379. return ret;
  33380. }
  33381. };
  33382. VertexData.prototype.serialize = function () {
  33383. var serializationObject = this.serialize();
  33384. if (this.positions) {
  33385. serializationObject.positions = this.positions;
  33386. }
  33387. if (this.normals) {
  33388. serializationObject.normals = this.normals;
  33389. }
  33390. if (this.uvs) {
  33391. serializationObject.uvs = this.uvs;
  33392. }
  33393. if (this.uvs2) {
  33394. serializationObject.uvs2 = this.uvs2;
  33395. }
  33396. if (this.uvs3) {
  33397. serializationObject.uvs3 = this.uvs3;
  33398. }
  33399. if (this.uvs4) {
  33400. serializationObject.uvs4 = this.uvs4;
  33401. }
  33402. if (this.uvs5) {
  33403. serializationObject.uvs5 = this.uvs5;
  33404. }
  33405. if (this.uvs6) {
  33406. serializationObject.uvs6 = this.uvs6;
  33407. }
  33408. if (this.colors) {
  33409. serializationObject.colors = this.colors;
  33410. }
  33411. if (this.matricesIndices) {
  33412. serializationObject.matricesIndices = this.matricesIndices;
  33413. serializationObject.matricesIndices._isExpanded = true;
  33414. }
  33415. if (this.matricesWeights) {
  33416. serializationObject.matricesWeights = this.matricesWeights;
  33417. }
  33418. if (this.matricesIndicesExtra) {
  33419. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33420. serializationObject.matricesIndicesExtra._isExpanded = true;
  33421. }
  33422. if (this.matricesWeightsExtra) {
  33423. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33424. }
  33425. serializationObject.indices = this.indices;
  33426. return serializationObject;
  33427. };
  33428. // Statics
  33429. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  33430. return VertexData._ExtractFrom(mesh, copyWhenShared);
  33431. };
  33432. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  33433. return VertexData._ExtractFrom(geometry, copyWhenShared);
  33434. };
  33435. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  33436. var result = new VertexData();
  33437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33438. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  33439. }
  33440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33441. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  33442. }
  33443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33444. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  33445. }
  33446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33447. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  33448. }
  33449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33450. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  33451. }
  33452. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33453. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  33454. }
  33455. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33456. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  33457. }
  33458. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33459. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  33460. }
  33461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33462. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  33463. }
  33464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33465. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  33466. }
  33467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33468. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  33469. }
  33470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33471. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  33472. }
  33473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33474. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  33475. }
  33476. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33477. return result;
  33478. };
  33479. VertexData.CreateRibbon = function (options) {
  33480. var pathArray = options.pathArray;
  33481. var closeArray = options.closeArray || false;
  33482. var closePath = options.closePath || false;
  33483. var invertUV = options.invertUV || false;
  33484. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33485. var offset = options.offset || defaultOffset;
  33486. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33487. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33488. var positions = [];
  33489. var indices = [];
  33490. var normals = [];
  33491. var uvs = [];
  33492. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33493. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33494. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33495. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33496. var minlg; // minimal length among all paths from pathArray
  33497. var lg = []; // array of path lengths : nb of vertex per path
  33498. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33499. var p; // path iterator
  33500. var i; // point iterator
  33501. var j; // point iterator
  33502. // if single path in pathArray
  33503. if (pathArray.length < 2) {
  33504. var ar1 = [];
  33505. var ar2 = [];
  33506. for (i = 0; i < pathArray[0].length - offset; i++) {
  33507. ar1.push(pathArray[0][i]);
  33508. ar2.push(pathArray[0][i + offset]);
  33509. }
  33510. pathArray = [ar1, ar2];
  33511. }
  33512. // positions and horizontal distances (u)
  33513. var idc = 0;
  33514. var closePathCorr = (closePath) ? 1 : 0;
  33515. var path;
  33516. var l;
  33517. minlg = pathArray[0].length;
  33518. var vectlg;
  33519. var dist;
  33520. for (p = 0; p < pathArray.length; p++) {
  33521. uTotalDistance[p] = 0;
  33522. us[p] = [0];
  33523. path = pathArray[p];
  33524. l = path.length;
  33525. minlg = (minlg < l) ? minlg : l;
  33526. j = 0;
  33527. while (j < l) {
  33528. positions.push(path[j].x, path[j].y, path[j].z);
  33529. if (j > 0) {
  33530. vectlg = path[j].subtract(path[j - 1]).length();
  33531. dist = vectlg + uTotalDistance[p];
  33532. us[p].push(dist);
  33533. uTotalDistance[p] = dist;
  33534. }
  33535. j++;
  33536. }
  33537. if (closePath) {
  33538. j--;
  33539. positions.push(path[0].x, path[0].y, path[0].z);
  33540. vectlg = path[j].subtract(path[0]).length();
  33541. dist = vectlg + uTotalDistance[p];
  33542. us[p].push(dist);
  33543. uTotalDistance[p] = dist;
  33544. }
  33545. lg[p] = l + closePathCorr;
  33546. idx[p] = idc;
  33547. idc += (l + closePathCorr);
  33548. }
  33549. // vertical distances (v)
  33550. var path1;
  33551. var path2;
  33552. var vertex1;
  33553. var vertex2;
  33554. for (i = 0; i < minlg + closePathCorr; i++) {
  33555. vTotalDistance[i] = 0;
  33556. vs[i] = [0];
  33557. for (p = 0; p < pathArray.length - 1; p++) {
  33558. path1 = pathArray[p];
  33559. path2 = pathArray[p + 1];
  33560. if (i === minlg) {
  33561. vertex1 = path1[0];
  33562. vertex2 = path2[0];
  33563. }
  33564. else {
  33565. vertex1 = path1[i];
  33566. vertex2 = path2[i];
  33567. }
  33568. vectlg = vertex2.subtract(vertex1).length();
  33569. dist = vectlg + vTotalDistance[i];
  33570. vs[i].push(dist);
  33571. vTotalDistance[i] = dist;
  33572. }
  33573. if (closeArray) {
  33574. path1 = pathArray[p];
  33575. path2 = pathArray[0];
  33576. if (i === minlg) {
  33577. vertex2 = path2[0];
  33578. }
  33579. vectlg = vertex2.subtract(vertex1).length();
  33580. dist = vectlg + vTotalDistance[i];
  33581. vTotalDistance[i] = dist;
  33582. }
  33583. }
  33584. // uvs
  33585. var u;
  33586. var v;
  33587. for (p = 0; p < pathArray.length; p++) {
  33588. for (i = 0; i < minlg + closePathCorr; i++) {
  33589. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33590. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33591. if (invertUV) {
  33592. uvs.push(v, u);
  33593. }
  33594. else {
  33595. uvs.push(u, v);
  33596. }
  33597. }
  33598. }
  33599. // indices
  33600. p = 0; // path index
  33601. var pi = 0; // positions array index
  33602. var l1 = lg[p] - 1; // path1 length
  33603. var l2 = lg[p + 1] - 1; // path2 length
  33604. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33605. var shft = idx[1] - idx[0]; // shift
  33606. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33607. while (pi <= min && p < path1nb) {
  33608. // 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
  33609. indices.push(pi, pi + shft, pi + 1);
  33610. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33611. pi += 1;
  33612. if (pi === min) {
  33613. p++;
  33614. if (p === lg.length - 1) {
  33615. shft = idx[0] - idx[p];
  33616. l1 = lg[p] - 1;
  33617. l2 = lg[0] - 1;
  33618. }
  33619. else {
  33620. shft = idx[p + 1] - idx[p];
  33621. l1 = lg[p] - 1;
  33622. l2 = lg[p + 1] - 1;
  33623. }
  33624. pi = idx[p];
  33625. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33626. }
  33627. }
  33628. // normals
  33629. VertexData.ComputeNormals(positions, indices, normals);
  33630. if (closePath) {
  33631. var indexFirst = 0;
  33632. var indexLast = 0;
  33633. for (p = 0; p < pathArray.length; p++) {
  33634. indexFirst = idx[p] * 3;
  33635. if (p + 1 < pathArray.length) {
  33636. indexLast = (idx[p + 1] - 1) * 3;
  33637. }
  33638. else {
  33639. indexLast = normals.length - 3;
  33640. }
  33641. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33642. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33643. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33644. normals[indexLast] = normals[indexFirst];
  33645. normals[indexLast + 1] = normals[indexFirst + 1];
  33646. normals[indexLast + 2] = normals[indexFirst + 2];
  33647. }
  33648. }
  33649. // sides
  33650. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33651. // Result
  33652. var vertexData = new VertexData();
  33653. vertexData.indices = indices;
  33654. vertexData.positions = positions;
  33655. vertexData.normals = normals;
  33656. vertexData.uvs = uvs;
  33657. if (closePath) {
  33658. vertexData._idx = idx;
  33659. }
  33660. return vertexData;
  33661. };
  33662. VertexData.CreateBox = function (options) {
  33663. var normalsSource = [
  33664. new BABYLON.Vector3(0, 0, 1),
  33665. new BABYLON.Vector3(0, 0, -1),
  33666. new BABYLON.Vector3(1, 0, 0),
  33667. new BABYLON.Vector3(-1, 0, 0),
  33668. new BABYLON.Vector3(0, 1, 0),
  33669. new BABYLON.Vector3(0, -1, 0)
  33670. ];
  33671. var indices = [];
  33672. var positions = [];
  33673. var normals = [];
  33674. var uvs = [];
  33675. var width = options.width || options.size || 1;
  33676. var height = options.height || options.size || 1;
  33677. var depth = options.depth || options.size || 1;
  33678. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33679. var faceUV = options.faceUV || new Array(6);
  33680. var faceColors = options.faceColors;
  33681. var colors = [];
  33682. // default face colors and UV if undefined
  33683. for (var f = 0; f < 6; f++) {
  33684. if (faceUV[f] === undefined) {
  33685. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33686. }
  33687. if (faceColors && faceColors[f] === undefined) {
  33688. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33689. }
  33690. }
  33691. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33692. // Create each face in turn.
  33693. for (var index = 0; index < normalsSource.length; index++) {
  33694. var normal = normalsSource[index];
  33695. // Get two vectors perpendicular to the face normal and to each other.
  33696. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33697. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33698. // Six indices (two triangles) per face.
  33699. var verticesLength = positions.length / 3;
  33700. indices.push(verticesLength);
  33701. indices.push(verticesLength + 1);
  33702. indices.push(verticesLength + 2);
  33703. indices.push(verticesLength);
  33704. indices.push(verticesLength + 2);
  33705. indices.push(verticesLength + 3);
  33706. // Four vertices per face.
  33707. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33708. positions.push(vertex.x, vertex.y, vertex.z);
  33709. normals.push(normal.x, normal.y, normal.z);
  33710. uvs.push(faceUV[index].z, faceUV[index].w);
  33711. if (faceColors) {
  33712. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33713. }
  33714. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33715. positions.push(vertex.x, vertex.y, vertex.z);
  33716. normals.push(normal.x, normal.y, normal.z);
  33717. uvs.push(faceUV[index].x, faceUV[index].w);
  33718. if (faceColors) {
  33719. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33720. }
  33721. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33722. positions.push(vertex.x, vertex.y, vertex.z);
  33723. normals.push(normal.x, normal.y, normal.z);
  33724. uvs.push(faceUV[index].x, faceUV[index].y);
  33725. if (faceColors) {
  33726. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33727. }
  33728. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33729. positions.push(vertex.x, vertex.y, vertex.z);
  33730. normals.push(normal.x, normal.y, normal.z);
  33731. uvs.push(faceUV[index].z, faceUV[index].y);
  33732. if (faceColors) {
  33733. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33734. }
  33735. }
  33736. // sides
  33737. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33738. // Result
  33739. var vertexData = new VertexData();
  33740. vertexData.indices = indices;
  33741. vertexData.positions = positions;
  33742. vertexData.normals = normals;
  33743. vertexData.uvs = uvs;
  33744. if (faceColors) {
  33745. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33746. vertexData.colors = totalColors;
  33747. }
  33748. return vertexData;
  33749. };
  33750. VertexData.CreateSphere = function (options) {
  33751. var segments = options.segments || 32;
  33752. var diameterX = options.diameterX || options.diameter || 1;
  33753. var diameterY = options.diameterY || options.diameter || 1;
  33754. var diameterZ = options.diameterZ || options.diameter || 1;
  33755. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33756. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33757. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33758. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33759. var totalZRotationSteps = 2 + segments;
  33760. var totalYRotationSteps = 2 * totalZRotationSteps;
  33761. var indices = [];
  33762. var positions = [];
  33763. var normals = [];
  33764. var uvs = [];
  33765. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33766. var normalizedZ = zRotationStep / totalZRotationSteps;
  33767. var angleZ = normalizedZ * Math.PI * slice;
  33768. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33769. var normalizedY = yRotationStep / totalYRotationSteps;
  33770. var angleY = normalizedY * Math.PI * 2 * arc;
  33771. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33772. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33773. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33774. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33775. var vertex = complete.multiply(radius);
  33776. var normal = complete.divide(radius).normalize();
  33777. positions.push(vertex.x, vertex.y, vertex.z);
  33778. normals.push(normal.x, normal.y, normal.z);
  33779. uvs.push(normalizedY, normalizedZ);
  33780. }
  33781. if (zRotationStep > 0) {
  33782. var verticesCount = positions.length / 3;
  33783. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33784. indices.push((firstIndex));
  33785. indices.push((firstIndex + 1));
  33786. indices.push(firstIndex + totalYRotationSteps + 1);
  33787. indices.push((firstIndex + totalYRotationSteps + 1));
  33788. indices.push((firstIndex + 1));
  33789. indices.push((firstIndex + totalYRotationSteps + 2));
  33790. }
  33791. }
  33792. }
  33793. // Sides
  33794. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33795. // Result
  33796. var vertexData = new VertexData();
  33797. vertexData.indices = indices;
  33798. vertexData.positions = positions;
  33799. vertexData.normals = normals;
  33800. vertexData.uvs = uvs;
  33801. return vertexData;
  33802. };
  33803. // Cylinder and cone
  33804. VertexData.CreateCylinder = function (options) {
  33805. var height = options.height || 2;
  33806. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33807. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33808. var tessellation = options.tessellation || 24;
  33809. var subdivisions = options.subdivisions || 1;
  33810. var hasRings = options.hasRings;
  33811. var enclose = options.enclose;
  33812. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33813. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33814. var faceUV = options.faceUV || new Array(3);
  33815. var faceColors = options.faceColors;
  33816. // default face colors and UV if undefined
  33817. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33818. var ringNb = (hasRings) ? subdivisions : 1;
  33819. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33820. var f;
  33821. for (f = 0; f < surfaceNb; f++) {
  33822. if (faceColors && faceColors[f] === undefined) {
  33823. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33824. }
  33825. }
  33826. for (f = 0; f < surfaceNb; f++) {
  33827. if (faceUV && faceUV[f] === undefined) {
  33828. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33829. }
  33830. }
  33831. var indices = [];
  33832. var positions = [];
  33833. var normals = [];
  33834. var uvs = [];
  33835. var colors = [];
  33836. var angle_step = Math.PI * 2 * arc / tessellation;
  33837. var angle;
  33838. var h;
  33839. var radius;
  33840. var tan = (diameterBottom - diameterTop) / 2 / height;
  33841. var ringVertex = BABYLON.Vector3.Zero();
  33842. var ringNormal = BABYLON.Vector3.Zero();
  33843. var ringFirstVertex = BABYLON.Vector3.Zero();
  33844. var ringFirstNormal = BABYLON.Vector3.Zero();
  33845. var quadNormal = BABYLON.Vector3.Zero();
  33846. var Y = BABYLON.Axis.Y;
  33847. // positions, normals, uvs
  33848. var i;
  33849. var j;
  33850. var r;
  33851. var ringIdx = 1;
  33852. var s = 1; // surface index
  33853. var cs = 0;
  33854. var v = 0;
  33855. for (i = 0; i <= subdivisions; i++) {
  33856. h = i / subdivisions;
  33857. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33858. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33859. for (r = 0; r < ringIdx; r++) {
  33860. if (hasRings) {
  33861. s += r;
  33862. }
  33863. if (enclose) {
  33864. s += 2 * r;
  33865. }
  33866. for (j = 0; j <= tessellation; j++) {
  33867. angle = j * angle_step;
  33868. // position
  33869. ringVertex.x = Math.cos(-angle) * radius;
  33870. ringVertex.y = -height / 2 + h * height;
  33871. ringVertex.z = Math.sin(-angle) * radius;
  33872. // normal
  33873. if (diameterTop === 0 && i === subdivisions) {
  33874. // if no top cap, reuse former normals
  33875. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33876. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33877. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33878. }
  33879. else {
  33880. ringNormal.x = ringVertex.x;
  33881. ringNormal.z = ringVertex.z;
  33882. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33883. ringNormal.normalize();
  33884. }
  33885. // keep first ring vertex values for enclose
  33886. if (j === 0) {
  33887. ringFirstVertex.copyFrom(ringVertex);
  33888. ringFirstNormal.copyFrom(ringNormal);
  33889. }
  33890. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33891. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33892. if (hasRings) {
  33893. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33894. }
  33895. else {
  33896. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33897. }
  33898. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33899. if (faceColors) {
  33900. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33901. }
  33902. }
  33903. // if enclose, add four vertices and their dedicated normals
  33904. if (arc !== 1 && enclose) {
  33905. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33906. positions.push(0, ringVertex.y, 0);
  33907. positions.push(0, ringVertex.y, 0);
  33908. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33909. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33910. quadNormal.normalize();
  33911. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33912. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33913. quadNormal.normalize();
  33914. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33915. if (hasRings) {
  33916. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33917. }
  33918. else {
  33919. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33920. }
  33921. uvs.push(faceUV[s + 1].x, v);
  33922. uvs.push(faceUV[s + 1].z, v);
  33923. if (hasRings) {
  33924. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33925. }
  33926. else {
  33927. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33928. }
  33929. uvs.push(faceUV[s + 2].x, v);
  33930. uvs.push(faceUV[s + 2].z, v);
  33931. if (faceColors) {
  33932. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33933. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33934. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33935. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33936. }
  33937. }
  33938. if (cs !== s) {
  33939. cs = s;
  33940. }
  33941. }
  33942. }
  33943. // indices
  33944. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33945. var s;
  33946. i = 0;
  33947. for (s = 0; s < subdivisions; s++) {
  33948. for (j = 0; j < tessellation; j++) {
  33949. var i0 = i * (e + 1) + j;
  33950. var i1 = (i + 1) * (e + 1) + j;
  33951. var i2 = i * (e + 1) + (j + 1);
  33952. var i3 = (i + 1) * (e + 1) + (j + 1);
  33953. indices.push(i0, i1, i2);
  33954. indices.push(i3, i2, i1);
  33955. }
  33956. if (arc !== 1 && enclose) {
  33957. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33958. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33959. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33960. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33961. }
  33962. i = (hasRings) ? (i + 2) : (i + 1);
  33963. }
  33964. // Caps
  33965. var createCylinderCap = function (isTop) {
  33966. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33967. if (radius === 0) {
  33968. return;
  33969. }
  33970. // Cap positions, normals & uvs
  33971. var angle;
  33972. var circleVector;
  33973. var i;
  33974. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33975. var c;
  33976. if (faceColors) {
  33977. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33978. }
  33979. // cap center
  33980. var vbase = positions.length / 3;
  33981. var offset = isTop ? height / 2 : -height / 2;
  33982. var center = new BABYLON.Vector3(0, offset, 0);
  33983. positions.push(center.x, center.y, center.z);
  33984. normals.push(0, isTop ? 1 : -1, 0);
  33985. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33986. if (faceColors) {
  33987. colors.push(c.r, c.g, c.b, c.a);
  33988. }
  33989. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33990. for (i = 0; i <= tessellation; i++) {
  33991. angle = Math.PI * 2 * i * arc / tessellation;
  33992. var cos = Math.cos(-angle);
  33993. var sin = Math.sin(-angle);
  33994. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33995. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33996. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33997. normals.push(0, isTop ? 1 : -1, 0);
  33998. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33999. if (faceColors) {
  34000. colors.push(c.r, c.g, c.b, c.a);
  34001. }
  34002. }
  34003. // Cap indices
  34004. for (i = 0; i < tessellation; i++) {
  34005. if (!isTop) {
  34006. indices.push(vbase);
  34007. indices.push(vbase + (i + 1));
  34008. indices.push(vbase + (i + 2));
  34009. }
  34010. else {
  34011. indices.push(vbase);
  34012. indices.push(vbase + (i + 2));
  34013. indices.push(vbase + (i + 1));
  34014. }
  34015. }
  34016. };
  34017. // add caps to geometry
  34018. createCylinderCap(false);
  34019. createCylinderCap(true);
  34020. // Sides
  34021. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34022. var vertexData = new VertexData();
  34023. vertexData.indices = indices;
  34024. vertexData.positions = positions;
  34025. vertexData.normals = normals;
  34026. vertexData.uvs = uvs;
  34027. if (faceColors) {
  34028. vertexData.colors = colors;
  34029. }
  34030. return vertexData;
  34031. };
  34032. VertexData.CreateTorus = function (options) {
  34033. var indices = [];
  34034. var positions = [];
  34035. var normals = [];
  34036. var uvs = [];
  34037. var diameter = options.diameter || 1;
  34038. var thickness = options.thickness || 0.5;
  34039. var tessellation = options.tessellation || 16;
  34040. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34041. var stride = tessellation + 1;
  34042. for (var i = 0; i <= tessellation; i++) {
  34043. var u = i / tessellation;
  34044. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34045. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34046. for (var j = 0; j <= tessellation; j++) {
  34047. var v = 1 - j / tessellation;
  34048. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34049. var dx = Math.cos(innerAngle);
  34050. var dy = Math.sin(innerAngle);
  34051. // Create a vertex.
  34052. var normal = new BABYLON.Vector3(dx, dy, 0);
  34053. var position = normal.scale(thickness / 2);
  34054. var textureCoordinate = new BABYLON.Vector2(u, v);
  34055. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34056. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34057. positions.push(position.x, position.y, position.z);
  34058. normals.push(normal.x, normal.y, normal.z);
  34059. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34060. // And create indices for two triangles.
  34061. var nextI = (i + 1) % stride;
  34062. var nextJ = (j + 1) % stride;
  34063. indices.push(i * stride + j);
  34064. indices.push(i * stride + nextJ);
  34065. indices.push(nextI * stride + j);
  34066. indices.push(i * stride + nextJ);
  34067. indices.push(nextI * stride + nextJ);
  34068. indices.push(nextI * stride + j);
  34069. }
  34070. }
  34071. // Sides
  34072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34073. // Result
  34074. var vertexData = new VertexData();
  34075. vertexData.indices = indices;
  34076. vertexData.positions = positions;
  34077. vertexData.normals = normals;
  34078. vertexData.uvs = uvs;
  34079. return vertexData;
  34080. };
  34081. VertexData.CreateLineSystem = function (options) {
  34082. var indices = [];
  34083. var positions = [];
  34084. var lines = options.lines;
  34085. var idx = 0;
  34086. for (var l = 0; l < lines.length; l++) {
  34087. var points = lines[l];
  34088. for (var index = 0; index < points.length; index++) {
  34089. positions.push(points[index].x, points[index].y, points[index].z);
  34090. if (index > 0) {
  34091. indices.push(idx - 1);
  34092. indices.push(idx);
  34093. }
  34094. idx++;
  34095. }
  34096. }
  34097. var vertexData = new VertexData();
  34098. vertexData.indices = indices;
  34099. vertexData.positions = positions;
  34100. return vertexData;
  34101. };
  34102. VertexData.CreateDashedLines = function (options) {
  34103. var dashSize = options.dashSize || 3;
  34104. var gapSize = options.gapSize || 1;
  34105. var dashNb = options.dashNb || 200;
  34106. var points = options.points;
  34107. var positions = new Array();
  34108. var indices = new Array();
  34109. var curvect = BABYLON.Vector3.Zero();
  34110. var lg = 0;
  34111. var nb = 0;
  34112. var shft = 0;
  34113. var dashshft = 0;
  34114. var curshft = 0;
  34115. var idx = 0;
  34116. var i = 0;
  34117. for (i = 0; i < points.length - 1; i++) {
  34118. points[i + 1].subtractToRef(points[i], curvect);
  34119. lg += curvect.length();
  34120. }
  34121. shft = lg / dashNb;
  34122. dashshft = dashSize * shft / (dashSize + gapSize);
  34123. for (i = 0; i < points.length - 1; i++) {
  34124. points[i + 1].subtractToRef(points[i], curvect);
  34125. nb = Math.floor(curvect.length() / shft);
  34126. curvect.normalize();
  34127. for (var j = 0; j < nb; j++) {
  34128. curshft = shft * j;
  34129. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34130. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34131. indices.push(idx, idx + 1);
  34132. idx += 2;
  34133. }
  34134. }
  34135. // Result
  34136. var vertexData = new VertexData();
  34137. vertexData.positions = positions;
  34138. vertexData.indices = indices;
  34139. return vertexData;
  34140. };
  34141. VertexData.CreateGround = function (options) {
  34142. var indices = [];
  34143. var positions = [];
  34144. var normals = [];
  34145. var uvs = [];
  34146. var row, col;
  34147. var width = options.width || 1;
  34148. var height = options.height || 1;
  34149. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34150. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34151. for (row = 0; row <= subdivisionsY; row++) {
  34152. for (col = 0; col <= subdivisionsX; col++) {
  34153. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34154. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34155. positions.push(position.x, position.y, position.z);
  34156. normals.push(normal.x, normal.y, normal.z);
  34157. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34158. }
  34159. }
  34160. for (row = 0; row < subdivisionsY; row++) {
  34161. for (col = 0; col < subdivisionsX; col++) {
  34162. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34163. indices.push(col + 1 + row * (subdivisionsX + 1));
  34164. indices.push(col + row * (subdivisionsX + 1));
  34165. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34166. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34167. indices.push(col + row * (subdivisionsX + 1));
  34168. }
  34169. }
  34170. // Result
  34171. var vertexData = new VertexData();
  34172. vertexData.indices = indices;
  34173. vertexData.positions = positions;
  34174. vertexData.normals = normals;
  34175. vertexData.uvs = uvs;
  34176. return vertexData;
  34177. };
  34178. VertexData.CreateTiledGround = function (options) {
  34179. var xmin = options.xmin || -1.0;
  34180. var zmin = options.zmin || -1.0;
  34181. var xmax = options.xmax || 1.0;
  34182. var zmax = options.zmax || 1.0;
  34183. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34184. var precision = options.precision || { w: 1, h: 1 };
  34185. var indices = [];
  34186. var positions = [];
  34187. var normals = [];
  34188. var uvs = [];
  34189. var row, col, tileRow, tileCol;
  34190. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34191. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34192. precision.w = (precision.w < 1) ? 1 : precision.w;
  34193. precision.h = (precision.h < 1) ? 1 : precision.h;
  34194. var tileSize = {
  34195. 'w': (xmax - xmin) / subdivisions.w,
  34196. 'h': (zmax - zmin) / subdivisions.h
  34197. };
  34198. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34199. // Indices
  34200. var base = positions.length / 3;
  34201. var rowLength = precision.w + 1;
  34202. for (row = 0; row < precision.h; row++) {
  34203. for (col = 0; col < precision.w; col++) {
  34204. var square = [
  34205. base + col + row * rowLength,
  34206. base + (col + 1) + row * rowLength,
  34207. base + (col + 1) + (row + 1) * rowLength,
  34208. base + col + (row + 1) * rowLength
  34209. ];
  34210. indices.push(square[1]);
  34211. indices.push(square[2]);
  34212. indices.push(square[3]);
  34213. indices.push(square[0]);
  34214. indices.push(square[1]);
  34215. indices.push(square[3]);
  34216. }
  34217. }
  34218. // Position, normals and uvs
  34219. var position = BABYLON.Vector3.Zero();
  34220. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34221. for (row = 0; row <= precision.h; row++) {
  34222. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34223. for (col = 0; col <= precision.w; col++) {
  34224. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34225. position.y = 0;
  34226. positions.push(position.x, position.y, position.z);
  34227. normals.push(normal.x, normal.y, normal.z);
  34228. uvs.push(col / precision.w, row / precision.h);
  34229. }
  34230. }
  34231. }
  34232. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34233. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34234. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34235. }
  34236. }
  34237. // Result
  34238. var vertexData = new VertexData();
  34239. vertexData.indices = indices;
  34240. vertexData.positions = positions;
  34241. vertexData.normals = normals;
  34242. vertexData.uvs = uvs;
  34243. return vertexData;
  34244. };
  34245. VertexData.CreateGroundFromHeightMap = function (options) {
  34246. var indices = [];
  34247. var positions = [];
  34248. var normals = [];
  34249. var uvs = [];
  34250. var row, col;
  34251. // Vertices
  34252. for (row = 0; row <= options.subdivisions; row++) {
  34253. for (col = 0; col <= options.subdivisions; col++) {
  34254. 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));
  34255. // Compute height
  34256. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34257. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34258. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34259. var r = options.buffer[pos] / 255.0;
  34260. var g = options.buffer[pos + 1] / 255.0;
  34261. var b = options.buffer[pos + 2] / 255.0;
  34262. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34263. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34264. // Add vertex
  34265. positions.push(position.x, position.y, position.z);
  34266. normals.push(0, 0, 0);
  34267. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34268. }
  34269. }
  34270. // Indices
  34271. for (row = 0; row < options.subdivisions; row++) {
  34272. for (col = 0; col < options.subdivisions; col++) {
  34273. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34274. indices.push(col + 1 + row * (options.subdivisions + 1));
  34275. indices.push(col + row * (options.subdivisions + 1));
  34276. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34277. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34278. indices.push(col + row * (options.subdivisions + 1));
  34279. }
  34280. }
  34281. // Normals
  34282. VertexData.ComputeNormals(positions, indices, normals);
  34283. // Result
  34284. var vertexData = new VertexData();
  34285. vertexData.indices = indices;
  34286. vertexData.positions = positions;
  34287. vertexData.normals = normals;
  34288. vertexData.uvs = uvs;
  34289. return vertexData;
  34290. };
  34291. VertexData.CreatePlane = function (options) {
  34292. var indices = [];
  34293. var positions = [];
  34294. var normals = [];
  34295. var uvs = [];
  34296. var width = options.width || options.size || 1;
  34297. var height = options.height || options.size || 1;
  34298. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34299. // Vertices
  34300. var halfWidth = width / 2.0;
  34301. var halfHeight = height / 2.0;
  34302. positions.push(-halfWidth, -halfHeight, 0);
  34303. normals.push(0, 0, -1.0);
  34304. uvs.push(0.0, 0.0);
  34305. positions.push(halfWidth, -halfHeight, 0);
  34306. normals.push(0, 0, -1.0);
  34307. uvs.push(1.0, 0.0);
  34308. positions.push(halfWidth, halfHeight, 0);
  34309. normals.push(0, 0, -1.0);
  34310. uvs.push(1.0, 1.0);
  34311. positions.push(-halfWidth, halfHeight, 0);
  34312. normals.push(0, 0, -1.0);
  34313. uvs.push(0.0, 1.0);
  34314. // Indices
  34315. indices.push(0);
  34316. indices.push(1);
  34317. indices.push(2);
  34318. indices.push(0);
  34319. indices.push(2);
  34320. indices.push(3);
  34321. // Sides
  34322. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34323. // Result
  34324. var vertexData = new VertexData();
  34325. vertexData.indices = indices;
  34326. vertexData.positions = positions;
  34327. vertexData.normals = normals;
  34328. vertexData.uvs = uvs;
  34329. return vertexData;
  34330. };
  34331. VertexData.CreateDisc = function (options) {
  34332. var positions = [];
  34333. var indices = [];
  34334. var normals = [];
  34335. var uvs = [];
  34336. var radius = options.radius || 0.5;
  34337. var tessellation = options.tessellation || 64;
  34338. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34339. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34340. // positions and uvs
  34341. positions.push(0, 0, 0); // disc center first
  34342. uvs.push(0.5, 0.5);
  34343. var theta = Math.PI * 2 * arc;
  34344. var step = theta / tessellation;
  34345. for (var a = 0; a < theta; a += step) {
  34346. var x = Math.cos(a);
  34347. var y = Math.sin(a);
  34348. var u = (x + 1) / 2;
  34349. var v = (1 - y) / 2;
  34350. positions.push(radius * x, radius * y, 0);
  34351. uvs.push(u, v);
  34352. }
  34353. if (arc === 1) {
  34354. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34355. uvs.push(uvs[2], uvs[3]);
  34356. }
  34357. //indices
  34358. var vertexNb = positions.length / 3;
  34359. for (var i = 1; i < vertexNb - 1; i++) {
  34360. indices.push(i + 1, 0, i);
  34361. }
  34362. // result
  34363. VertexData.ComputeNormals(positions, indices, normals);
  34364. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34365. var vertexData = new VertexData();
  34366. vertexData.indices = indices;
  34367. vertexData.positions = positions;
  34368. vertexData.normals = normals;
  34369. vertexData.uvs = uvs;
  34370. return vertexData;
  34371. };
  34372. VertexData.CreateIcoSphere = function (options) {
  34373. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34374. var radius = options.radius || 1;
  34375. var flat = (options.flat === undefined) ? true : options.flat;
  34376. var subdivisions = options.subdivisions || 4;
  34377. var radiusX = options.radiusX || radius;
  34378. var radiusY = options.radiusY || radius;
  34379. var radiusZ = options.radiusZ || radius;
  34380. var t = (1 + Math.sqrt(5)) / 2;
  34381. // 12 vertex x,y,z
  34382. var ico_vertices = [
  34383. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34384. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34385. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34386. ];
  34387. // index of 3 vertex makes a face of icopshere
  34388. var ico_indices = [
  34389. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34390. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34391. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34392. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34393. ];
  34394. // vertex for uv have aliased position, not for UV
  34395. var vertices_unalias_id = [
  34396. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34397. // vertex alias
  34398. 0,
  34399. 2,
  34400. 3,
  34401. 3,
  34402. 3,
  34403. 4,
  34404. 7,
  34405. 8,
  34406. 9,
  34407. 9,
  34408. 10,
  34409. 11 // 23: B + 12
  34410. ];
  34411. // uv as integer step (not pixels !)
  34412. var ico_vertexuv = [
  34413. 5, 1, 3, 1, 6, 4, 0, 0,
  34414. 5, 3, 4, 2, 2, 2, 4, 0,
  34415. 2, 0, 1, 1, 6, 0, 6, 2,
  34416. // vertex alias (for same vertex on different faces)
  34417. 0, 4,
  34418. 3, 3,
  34419. 4, 4,
  34420. 3, 1,
  34421. 4, 2,
  34422. 4, 4,
  34423. 0, 2,
  34424. 1, 1,
  34425. 2, 2,
  34426. 3, 3,
  34427. 1, 3,
  34428. 2, 4 // 23: B + 12
  34429. ];
  34430. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34431. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34432. // First island of uv mapping
  34433. // v = 4h 3+ 2
  34434. // v = 3h 9+ 4
  34435. // v = 2h 9+ 5 B
  34436. // v = 1h 9 1 0
  34437. // v = 0h 3 8 7 A
  34438. // u = 0 1 2 3 4 5 6 *a
  34439. // Second island of uv mapping
  34440. // v = 4h 0+ B+ 4+
  34441. // v = 3h A+ 2+
  34442. // v = 2h 7+ 6 3+
  34443. // v = 1h 8+ 3+
  34444. // v = 0h
  34445. // u = 0 1 2 3 4 5 6 *a
  34446. // Face layout on texture UV mapping
  34447. // ============
  34448. // \ 4 /\ 16 / ======
  34449. // \ / \ / /\ 11 /
  34450. // \/ 7 \/ / \ /
  34451. // ======= / 10 \/
  34452. // /\ 17 /\ =======
  34453. // / \ / \ \ 15 /\
  34454. // / 8 \/ 12 \ \ / \
  34455. // ============ \/ 6 \
  34456. // \ 18 /\ ============
  34457. // \ / \ \ 5 /\ 0 /
  34458. // \/ 13 \ \ / \ /
  34459. // ======= \/ 1 \/
  34460. // =============
  34461. // /\ 19 /\ 2 /\
  34462. // / \ / \ / \
  34463. // / 14 \/ 9 \/ 3 \
  34464. // ===================
  34465. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34466. var ustep = 138 / 1024;
  34467. var vstep = 239 / 1024;
  34468. var uoffset = 60 / 1024;
  34469. var voffset = 26 / 1024;
  34470. // Second island should have margin, not to touch the first island
  34471. // avoid any borderline artefact in pixel rounding
  34472. var island_u_offset = -40 / 1024;
  34473. var island_v_offset = +20 / 1024;
  34474. // face is either island 0 or 1 :
  34475. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34476. var island = [
  34477. 0, 0, 0, 0, 1,
  34478. 0, 0, 1, 1, 0,
  34479. 0, 0, 1, 1, 0,
  34480. 0, 1, 1, 1, 0 // 15 - 19
  34481. ];
  34482. var indices = [];
  34483. var positions = [];
  34484. var normals = [];
  34485. var uvs = [];
  34486. var current_indice = 0;
  34487. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34488. var face_vertex_pos = new Array(3);
  34489. var face_vertex_uv = new Array(3);
  34490. var v012;
  34491. for (v012 = 0; v012 < 3; v012++) {
  34492. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34493. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34494. }
  34495. // create all with normals
  34496. for (var face = 0; face < 20; face++) {
  34497. // 3 vertex per face
  34498. for (v012 = 0; v012 < 3; v012++) {
  34499. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34500. var v_id = ico_indices[3 * face + v012];
  34501. // vertex have 3D position (x,y,z)
  34502. 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]);
  34503. // Normalize to get normal, then scale to radius
  34504. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34505. // uv Coordinates from vertex ID
  34506. 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);
  34507. }
  34508. // Subdivide the face (interpolate pos, norm, uv)
  34509. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34510. // - norm is linear interpolation of vertex corner normal
  34511. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34512. // - uv is linear interpolation
  34513. //
  34514. // Topology is as below for sub-divide by 2
  34515. // vertex shown as v0,v1,v2
  34516. // interp index is i1 to progress in range [v0,v1[
  34517. // interp index is i2 to progress in range [v0,v2[
  34518. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34519. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34520. //
  34521. //
  34522. // i2 v2
  34523. // ^ ^
  34524. // / / \
  34525. // / / \
  34526. // / / \
  34527. // / / (0,1) \
  34528. // / #---------\
  34529. // / / \ (0,0)'/ \
  34530. // / / \ / \
  34531. // / / \ / \
  34532. // / / (0,0) \ / (1,0) \
  34533. // / #---------#---------\
  34534. // v0 v1
  34535. //
  34536. // --------------------> i1
  34537. //
  34538. // interp of (i1,i2):
  34539. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34540. // along i1 : lerp(x0,x1, i1/(S-i2))
  34541. //
  34542. // centroid of triangle is needed to get help normal computation
  34543. // (c1,c2) are used for centroid location
  34544. var interp_vertex = function (i1, i2, c1, c2) {
  34545. // vertex is interpolated from
  34546. // - face_vertex_pos[0..2]
  34547. // - face_vertex_uv[0..2]
  34548. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34549. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34550. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34551. pos_interp.normalize();
  34552. var vertex_normal;
  34553. if (flat) {
  34554. // in flat mode, recalculate normal as face centroid normal
  34555. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34556. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34557. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34558. }
  34559. else {
  34560. // in smooth mode, recalculate normal from each single vertex position
  34561. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34562. }
  34563. // Vertex normal need correction due to X,Y,Z radius scaling
  34564. vertex_normal.x /= radiusX;
  34565. vertex_normal.y /= radiusY;
  34566. vertex_normal.z /= radiusZ;
  34567. vertex_normal.normalize();
  34568. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34569. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34570. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34571. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34572. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34573. uvs.push(uv_interp.x, uv_interp.y);
  34574. // push each vertex has member of a face
  34575. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34576. indices.push(current_indice);
  34577. current_indice++;
  34578. };
  34579. for (var i2 = 0; i2 < subdivisions; i2++) {
  34580. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34581. // face : (i1,i2) for /\ :
  34582. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34583. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34584. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34585. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34586. if (i1 + i2 + 1 < subdivisions) {
  34587. // face : (i1,i2)' for \/ :
  34588. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34589. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34590. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34591. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34592. }
  34593. }
  34594. }
  34595. }
  34596. // Sides
  34597. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34598. // Result
  34599. var vertexData = new VertexData();
  34600. vertexData.indices = indices;
  34601. vertexData.positions = positions;
  34602. vertexData.normals = normals;
  34603. vertexData.uvs = uvs;
  34604. return vertexData;
  34605. };
  34606. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34607. VertexData.CreatePolyhedron = function (options) {
  34608. // provided polyhedron types :
  34609. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34610. // 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)
  34611. var polyhedra = [];
  34612. 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]] };
  34613. 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]] };
  34614. polyhedra[2] = {
  34615. 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]],
  34616. 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]]
  34617. };
  34618. polyhedra[3] = {
  34619. 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]],
  34620. 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]]
  34621. };
  34622. polyhedra[4] = {
  34623. 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]],
  34624. 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]]
  34625. };
  34626. 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]] };
  34627. 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]] };
  34628. 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]] };
  34629. 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]] };
  34630. 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]] };
  34631. 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]] };
  34632. 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]] };
  34633. 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]] };
  34634. 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]] };
  34635. polyhedra[14] = {
  34636. 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]],
  34637. 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]]
  34638. };
  34639. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34640. var size = options.size;
  34641. var sizeX = options.sizeX || size || 1;
  34642. var sizeY = options.sizeY || size || 1;
  34643. var sizeZ = options.sizeZ || size || 1;
  34644. var data = options.custom || polyhedra[type];
  34645. var nbfaces = data.face.length;
  34646. var faceUV = options.faceUV || new Array(nbfaces);
  34647. var faceColors = options.faceColors;
  34648. var flat = (options.flat === undefined) ? true : options.flat;
  34649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34650. var positions = [];
  34651. var indices = [];
  34652. var normals = [];
  34653. var uvs = [];
  34654. var colors = [];
  34655. var index = 0;
  34656. var faceIdx = 0; // face cursor in the array "indexes"
  34657. var indexes = [];
  34658. var i = 0;
  34659. var f = 0;
  34660. var u, v, ang, x, y, tmp;
  34661. // default face colors and UV if undefined
  34662. if (flat) {
  34663. for (f = 0; f < nbfaces; f++) {
  34664. if (faceColors && faceColors[f] === undefined) {
  34665. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34666. }
  34667. if (faceUV && faceUV[f] === undefined) {
  34668. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34669. }
  34670. }
  34671. }
  34672. if (!flat) {
  34673. for (i = 0; i < data.vertex.length; i++) {
  34674. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34675. uvs.push(0, 0);
  34676. }
  34677. for (f = 0; f < nbfaces; f++) {
  34678. for (i = 0; i < data.face[f].length - 2; i++) {
  34679. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34680. }
  34681. }
  34682. }
  34683. else {
  34684. for (f = 0; f < nbfaces; f++) {
  34685. var fl = data.face[f].length; // number of vertices of the current face
  34686. ang = 2 * Math.PI / fl;
  34687. x = 0.5 * Math.tan(ang / 2);
  34688. y = 0.5;
  34689. // positions, uvs, colors
  34690. for (i = 0; i < fl; i++) {
  34691. // positions
  34692. 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);
  34693. indexes.push(index);
  34694. index++;
  34695. // uvs
  34696. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34697. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34698. uvs.push(u, v);
  34699. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34700. y = x * Math.sin(ang) + y * Math.cos(ang);
  34701. x = tmp;
  34702. // colors
  34703. if (faceColors) {
  34704. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34705. }
  34706. }
  34707. // indices from indexes
  34708. for (i = 0; i < fl - 2; i++) {
  34709. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34710. }
  34711. faceIdx += fl;
  34712. }
  34713. }
  34714. VertexData.ComputeNormals(positions, indices, normals);
  34715. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34716. var vertexData = new VertexData();
  34717. vertexData.positions = positions;
  34718. vertexData.indices = indices;
  34719. vertexData.normals = normals;
  34720. vertexData.uvs = uvs;
  34721. if (faceColors && flat) {
  34722. vertexData.colors = colors;
  34723. }
  34724. return vertexData;
  34725. };
  34726. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34727. VertexData.CreateTorusKnot = function (options) {
  34728. var indices = [];
  34729. var positions = [];
  34730. var normals = [];
  34731. var uvs = [];
  34732. var radius = options.radius || 2;
  34733. var tube = options.tube || 0.5;
  34734. var radialSegments = options.radialSegments || 32;
  34735. var tubularSegments = options.tubularSegments || 32;
  34736. var p = options.p || 2;
  34737. var q = options.q || 3;
  34738. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34739. // Helper
  34740. var getPos = function (angle) {
  34741. var cu = Math.cos(angle);
  34742. var su = Math.sin(angle);
  34743. var quOverP = q / p * angle;
  34744. var cs = Math.cos(quOverP);
  34745. var tx = radius * (2 + cs) * 0.5 * cu;
  34746. var ty = radius * (2 + cs) * su * 0.5;
  34747. var tz = radius * Math.sin(quOverP) * 0.5;
  34748. return new BABYLON.Vector3(tx, ty, tz);
  34749. };
  34750. // Vertices
  34751. var i;
  34752. var j;
  34753. for (i = 0; i <= radialSegments; i++) {
  34754. var modI = i % radialSegments;
  34755. var u = modI / radialSegments * 2 * p * Math.PI;
  34756. var p1 = getPos(u);
  34757. var p2 = getPos(u + 0.01);
  34758. var tang = p2.subtract(p1);
  34759. var n = p2.add(p1);
  34760. var bitan = BABYLON.Vector3.Cross(tang, n);
  34761. n = BABYLON.Vector3.Cross(bitan, tang);
  34762. bitan.normalize();
  34763. n.normalize();
  34764. for (j = 0; j < tubularSegments; j++) {
  34765. var modJ = j % tubularSegments;
  34766. var v = modJ / tubularSegments * 2 * Math.PI;
  34767. var cx = -tube * Math.cos(v);
  34768. var cy = tube * Math.sin(v);
  34769. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34770. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34771. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34772. uvs.push(i / radialSegments);
  34773. uvs.push(j / tubularSegments);
  34774. }
  34775. }
  34776. for (i = 0; i < radialSegments; i++) {
  34777. for (j = 0; j < tubularSegments; j++) {
  34778. var jNext = (j + 1) % tubularSegments;
  34779. var a = i * tubularSegments + j;
  34780. var b = (i + 1) * tubularSegments + j;
  34781. var c = (i + 1) * tubularSegments + jNext;
  34782. var d = i * tubularSegments + jNext;
  34783. indices.push(d);
  34784. indices.push(b);
  34785. indices.push(a);
  34786. indices.push(d);
  34787. indices.push(c);
  34788. indices.push(b);
  34789. }
  34790. }
  34791. // Normals
  34792. VertexData.ComputeNormals(positions, indices, normals);
  34793. // Sides
  34794. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34795. // Result
  34796. var vertexData = new VertexData();
  34797. vertexData.indices = indices;
  34798. vertexData.positions = positions;
  34799. vertexData.normals = normals;
  34800. vertexData.uvs = uvs;
  34801. return vertexData;
  34802. };
  34803. // Tools
  34804. /**
  34805. * @param {any} - positions (number[] or Float32Array)
  34806. * @param {any} - indices (number[] or Uint16Array)
  34807. * @param {any} - normals (number[] or Float32Array)
  34808. * options (optional) :
  34809. * facetPositions : optional array of facet positions (vector3)
  34810. * facetNormals : optional array of facet normals (vector3)
  34811. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34812. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34813. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34814. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34815. * bInfo : optional bounding info, required for facetPartitioning computation
  34816. */
  34817. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34818. // temporary scalar variables
  34819. var index = 0; // facet index
  34820. var p1p2x = 0.0; // p1p2 vector x coordinate
  34821. var p1p2y = 0.0; // p1p2 vector y coordinate
  34822. var p1p2z = 0.0; // p1p2 vector z coordinate
  34823. var p3p2x = 0.0; // p3p2 vector x coordinate
  34824. var p3p2y = 0.0; // p3p2 vector y coordinate
  34825. var p3p2z = 0.0; // p3p2 vector z coordinate
  34826. var faceNormalx = 0.0; // facet normal x coordinate
  34827. var faceNormaly = 0.0; // facet normal y coordinate
  34828. var faceNormalz = 0.0; // facet normal z coordinate
  34829. var length = 0.0; // facet normal length before normalization
  34830. var v1x = 0; // vector1 x index in the positions array
  34831. var v1y = 0; // vector1 y index in the positions array
  34832. var v1z = 0; // vector1 z index in the positions array
  34833. var v2x = 0; // vector2 x index in the positions array
  34834. var v2y = 0; // vector2 y index in the positions array
  34835. var v2z = 0; // vector2 z index in the positions array
  34836. var v3x = 0; // vector3 x index in the positions array
  34837. var v3y = 0; // vector3 y index in the positions array
  34838. var v3z = 0; // vector3 z index in the positions array
  34839. var computeFacetNormals = false;
  34840. var computeFacetPositions = false;
  34841. var computeFacetPartitioning = false;
  34842. if (options) {
  34843. computeFacetNormals = (options.facetNormals) ? true : false;
  34844. computeFacetPositions = (options.facetPositions) ? true : false;
  34845. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34846. }
  34847. // facetPartitioning reinit if needed
  34848. if (computeFacetPartitioning) {
  34849. var ox = 0; // X partitioning index for facet position
  34850. var oy = 0; // Y partinioning index for facet position
  34851. var oz = 0; // Z partinioning index for facet position
  34852. var b1x = 0; // X partitioning index for facet v1 vertex
  34853. var b1y = 0; // Y partitioning index for facet v1 vertex
  34854. var b1z = 0; // z partitioning index for facet v1 vertex
  34855. var b2x = 0; // X partitioning index for facet v2 vertex
  34856. var b2y = 0; // Y partitioning index for facet v2 vertex
  34857. var b2z = 0; // Z partitioning index for facet v2 vertex
  34858. var b3x = 0; // X partitioning index for facet v3 vertex
  34859. var b3y = 0; // Y partitioning index for facet v3 vertex
  34860. var b3z = 0; // Z partitioning index for facet v3 vertex
  34861. var block_idx_o = 0; // facet barycenter block index
  34862. var block_idx_v1 = 0; // v1 vertex block index
  34863. var block_idx_v2 = 0; // v2 vertex block index
  34864. var block_idx_v3 = 0; // v3 vertex block index
  34865. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34866. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34867. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  34868. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  34869. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  34870. var subSq = options.subDiv.max * options.subDiv.max;
  34871. options.facetPartitioning.length = 0;
  34872. }
  34873. // reset the normals
  34874. for (index = 0; index < positions.length; index++) {
  34875. normals[index] = 0.0;
  34876. }
  34877. // Loop : 1 indice triplet = 1 facet
  34878. var nbFaces = indices.length / 3;
  34879. for (index = 0; index < nbFaces; index++) {
  34880. // get the indexes of the coordinates of each vertex of the facet
  34881. v1x = indices[index * 3] * 3;
  34882. v1y = v1x + 1;
  34883. v1z = v1x + 2;
  34884. v2x = indices[index * 3 + 1] * 3;
  34885. v2y = v2x + 1;
  34886. v2z = v2x + 2;
  34887. v3x = indices[index * 3 + 2] * 3;
  34888. v3y = v3x + 1;
  34889. v3z = v3x + 2;
  34890. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34891. p1p2y = positions[v1y] - positions[v2y];
  34892. p1p2z = positions[v1z] - positions[v2z];
  34893. p3p2x = positions[v3x] - positions[v2x];
  34894. p3p2y = positions[v3y] - positions[v2y];
  34895. p3p2z = positions[v3z] - positions[v2z];
  34896. // compute the face normal with the cross product
  34897. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  34898. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34899. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34900. // normalize this normal and store it in the array facetData
  34901. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34902. length = (length === 0) ? 1.0 : length;
  34903. faceNormalx /= length;
  34904. faceNormaly /= length;
  34905. faceNormalz /= length;
  34906. if (computeFacetNormals) {
  34907. options.facetNormals[index].x = faceNormalx;
  34908. options.facetNormals[index].y = faceNormaly;
  34909. options.facetNormals[index].z = faceNormalz;
  34910. }
  34911. if (computeFacetPositions) {
  34912. // compute and the facet barycenter coordinates in the array facetPositions
  34913. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34914. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34915. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34916. }
  34917. if (computeFacetPartitioning) {
  34918. // store the facet indexes in arrays in the main facetPartitioning array :
  34919. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34920. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34921. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34922. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34923. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34924. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34925. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34926. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34927. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34928. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34929. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  34930. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  34931. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  34932. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34933. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34934. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34935. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34936. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34937. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34938. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34939. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34940. // push each facet index in each block containing the vertex
  34941. options.facetPartitioning[block_idx_v1].push(index);
  34942. if (block_idx_v2 != block_idx_v1) {
  34943. options.facetPartitioning[block_idx_v2].push(index);
  34944. }
  34945. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34946. options.facetPartitioning[block_idx_v3].push(index);
  34947. }
  34948. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34949. options.facetPartitioning[block_idx_o].push(index);
  34950. }
  34951. }
  34952. // compute the normals anyway
  34953. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34954. normals[v1y] += faceNormaly;
  34955. normals[v1z] += faceNormalz;
  34956. normals[v2x] += faceNormalx;
  34957. normals[v2y] += faceNormaly;
  34958. normals[v2z] += faceNormalz;
  34959. normals[v3x] += faceNormalx;
  34960. normals[v3y] += faceNormaly;
  34961. normals[v3z] += faceNormalz;
  34962. }
  34963. // last normalization of each normal
  34964. for (index = 0; index < normals.length / 3; index++) {
  34965. faceNormalx = normals[index * 3];
  34966. faceNormaly = normals[index * 3 + 1];
  34967. faceNormalz = normals[index * 3 + 2];
  34968. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34969. length = (length === 0) ? 1.0 : length;
  34970. faceNormalx /= length;
  34971. faceNormaly /= length;
  34972. faceNormalz /= length;
  34973. normals[index * 3] = faceNormalx;
  34974. normals[index * 3 + 1] = faceNormaly;
  34975. normals[index * 3 + 2] = faceNormalz;
  34976. }
  34977. };
  34978. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34979. var li = indices.length;
  34980. var ln = normals.length;
  34981. var i;
  34982. var n;
  34983. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34984. switch (sideOrientation) {
  34985. case BABYLON.Mesh.FRONTSIDE:
  34986. // nothing changed
  34987. break;
  34988. case BABYLON.Mesh.BACKSIDE:
  34989. var tmp;
  34990. // indices
  34991. for (i = 0; i < li; i += 3) {
  34992. tmp = indices[i];
  34993. indices[i] = indices[i + 2];
  34994. indices[i + 2] = tmp;
  34995. }
  34996. // normals
  34997. for (n = 0; n < ln; n++) {
  34998. normals[n] = -normals[n];
  34999. }
  35000. break;
  35001. case BABYLON.Mesh.DOUBLESIDE:
  35002. // positions
  35003. var lp = positions.length;
  35004. var l = lp / 3;
  35005. for (var p = 0; p < lp; p++) {
  35006. positions[lp + p] = positions[p];
  35007. }
  35008. // indices
  35009. for (i = 0; i < li; i += 3) {
  35010. indices[i + li] = indices[i + 2] + l;
  35011. indices[i + 1 + li] = indices[i + 1] + l;
  35012. indices[i + 2 + li] = indices[i] + l;
  35013. }
  35014. // normals
  35015. for (n = 0; n < ln; n++) {
  35016. normals[ln + n] = -normals[n];
  35017. }
  35018. // uvs
  35019. var lu = uvs.length;
  35020. for (var u = 0; u < lu; u++) {
  35021. uvs[u + lu] = uvs[u];
  35022. }
  35023. break;
  35024. }
  35025. };
  35026. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35027. var vertexData = new VertexData();
  35028. // positions
  35029. var positions = parsedVertexData.positions;
  35030. if (positions) {
  35031. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35032. }
  35033. // normals
  35034. var normals = parsedVertexData.normals;
  35035. if (normals) {
  35036. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35037. }
  35038. // uvs
  35039. var uvs = parsedVertexData.uvs;
  35040. if (uvs) {
  35041. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35042. }
  35043. // uv2s
  35044. var uv2s = parsedVertexData.uv2s;
  35045. if (uv2s) {
  35046. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35047. }
  35048. // uv3s
  35049. var uv3s = parsedVertexData.uv3s;
  35050. if (uv3s) {
  35051. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35052. }
  35053. // uv4s
  35054. var uv4s = parsedVertexData.uv4s;
  35055. if (uv4s) {
  35056. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35057. }
  35058. // uv5s
  35059. var uv5s = parsedVertexData.uv5s;
  35060. if (uv5s) {
  35061. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35062. }
  35063. // uv6s
  35064. var uv6s = parsedVertexData.uv6s;
  35065. if (uv6s) {
  35066. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35067. }
  35068. // colors
  35069. var colors = parsedVertexData.colors;
  35070. if (colors) {
  35071. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35072. }
  35073. // matricesIndices
  35074. var matricesIndices = parsedVertexData.matricesIndices;
  35075. if (matricesIndices) {
  35076. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35077. }
  35078. // matricesWeights
  35079. var matricesWeights = parsedVertexData.matricesWeights;
  35080. if (matricesWeights) {
  35081. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35082. }
  35083. // indices
  35084. var indices = parsedVertexData.indices;
  35085. if (indices) {
  35086. vertexData.indices = indices;
  35087. }
  35088. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35089. };
  35090. return VertexData;
  35091. }());
  35092. BABYLON.VertexData = VertexData;
  35093. })(BABYLON || (BABYLON = {}));
  35094. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35095. var BABYLON;
  35096. (function (BABYLON) {
  35097. var Tags = (function () {
  35098. function Tags() {
  35099. }
  35100. Tags.EnableFor = function (obj) {
  35101. obj._tags = obj._tags || {};
  35102. obj.hasTags = function () {
  35103. return Tags.HasTags(obj);
  35104. };
  35105. obj.addTags = function (tagsString) {
  35106. return Tags.AddTagsTo(obj, tagsString);
  35107. };
  35108. obj.removeTags = function (tagsString) {
  35109. return Tags.RemoveTagsFrom(obj, tagsString);
  35110. };
  35111. obj.matchesTagsQuery = function (tagsQuery) {
  35112. return Tags.MatchesQuery(obj, tagsQuery);
  35113. };
  35114. };
  35115. Tags.DisableFor = function (obj) {
  35116. delete obj._tags;
  35117. delete obj.hasTags;
  35118. delete obj.addTags;
  35119. delete obj.removeTags;
  35120. delete obj.matchesTagsQuery;
  35121. };
  35122. Tags.HasTags = function (obj) {
  35123. if (!obj._tags) {
  35124. return false;
  35125. }
  35126. return !BABYLON.Tools.IsEmpty(obj._tags);
  35127. };
  35128. Tags.GetTags = function (obj, asString) {
  35129. if (asString === void 0) { asString = true; }
  35130. if (!obj._tags) {
  35131. return null;
  35132. }
  35133. if (asString) {
  35134. var tagsArray = [];
  35135. for (var tag in obj._tags) {
  35136. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  35137. tagsArray.push(tag);
  35138. }
  35139. }
  35140. return tagsArray.join(" ");
  35141. }
  35142. else {
  35143. return obj._tags;
  35144. }
  35145. };
  35146. // the tags 'true' and 'false' are reserved and cannot be used as tags
  35147. // a tag cannot start with '||', '&&', and '!'
  35148. // it cannot contain whitespaces
  35149. Tags.AddTagsTo = function (obj, tagsString) {
  35150. if (!tagsString) {
  35151. return;
  35152. }
  35153. if (typeof tagsString !== "string") {
  35154. return;
  35155. }
  35156. var tags = tagsString.split(" ");
  35157. tags.forEach(function (tag, index, array) {
  35158. Tags._AddTagTo(obj, tag);
  35159. });
  35160. };
  35161. Tags._AddTagTo = function (obj, tag) {
  35162. tag = tag.trim();
  35163. if (tag === "" || tag === "true" || tag === "false") {
  35164. return;
  35165. }
  35166. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  35167. return;
  35168. }
  35169. Tags.EnableFor(obj);
  35170. obj._tags[tag] = true;
  35171. };
  35172. Tags.RemoveTagsFrom = function (obj, tagsString) {
  35173. if (!Tags.HasTags(obj)) {
  35174. return;
  35175. }
  35176. var tags = tagsString.split(" ");
  35177. for (var t in tags) {
  35178. Tags._RemoveTagFrom(obj, tags[t]);
  35179. }
  35180. };
  35181. Tags._RemoveTagFrom = function (obj, tag) {
  35182. delete obj._tags[tag];
  35183. };
  35184. Tags.MatchesQuery = function (obj, tagsQuery) {
  35185. if (tagsQuery === undefined) {
  35186. return true;
  35187. }
  35188. if (tagsQuery === "") {
  35189. return Tags.HasTags(obj);
  35190. }
  35191. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  35192. };
  35193. return Tags;
  35194. }());
  35195. BABYLON.Tags = Tags;
  35196. })(BABYLON || (BABYLON = {}));
  35197. //# sourceMappingURL=babylon.tags.js.map
  35198. var BABYLON;
  35199. (function (BABYLON) {
  35200. var Internals;
  35201. (function (Internals) {
  35202. var AndOrNotEvaluator = (function () {
  35203. function AndOrNotEvaluator() {
  35204. }
  35205. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  35206. if (!query.match(/\([^\(\)]*\)/g)) {
  35207. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  35208. }
  35209. else {
  35210. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  35211. // remove parenthesis
  35212. r = r.slice(1, r.length - 1);
  35213. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  35214. });
  35215. }
  35216. if (query === "true") {
  35217. return true;
  35218. }
  35219. if (query === "false") {
  35220. return false;
  35221. }
  35222. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  35223. };
  35224. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  35225. evaluateCallback = evaluateCallback || (function (r) {
  35226. return r === "true" ? true : false;
  35227. });
  35228. var result;
  35229. var or = parenthesisContent.split("||");
  35230. for (var i in or) {
  35231. if (or.hasOwnProperty(i)) {
  35232. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  35233. var and = ori.split("&&");
  35234. if (and.length > 1) {
  35235. for (var j = 0; j < and.length; ++j) {
  35236. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  35237. if (andj !== "true" && andj !== "false") {
  35238. if (andj[0] === "!") {
  35239. result = !evaluateCallback(andj.substring(1));
  35240. }
  35241. else {
  35242. result = evaluateCallback(andj);
  35243. }
  35244. }
  35245. else {
  35246. result = andj === "true" ? true : false;
  35247. }
  35248. if (!result) {
  35249. ori = "false";
  35250. break;
  35251. }
  35252. }
  35253. }
  35254. if (result || ori === "true") {
  35255. result = true;
  35256. break;
  35257. }
  35258. // result equals false (or undefined)
  35259. if (ori !== "true" && ori !== "false") {
  35260. if (ori[0] === "!") {
  35261. result = !evaluateCallback(ori.substring(1));
  35262. }
  35263. else {
  35264. result = evaluateCallback(ori);
  35265. }
  35266. }
  35267. else {
  35268. result = ori === "true" ? true : false;
  35269. }
  35270. }
  35271. }
  35272. // the whole parenthesis scope is replaced by 'true' or 'false'
  35273. return result ? "true" : "false";
  35274. };
  35275. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  35276. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  35277. // remove whitespaces
  35278. r = r.replace(/[\s]/g, function () { return ""; });
  35279. return r.length % 2 ? "!" : "";
  35280. });
  35281. booleanString = booleanString.trim();
  35282. if (booleanString === "!true") {
  35283. booleanString = "false";
  35284. }
  35285. else if (booleanString === "!false") {
  35286. booleanString = "true";
  35287. }
  35288. return booleanString;
  35289. };
  35290. return AndOrNotEvaluator;
  35291. }());
  35292. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  35293. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35294. })(BABYLON || (BABYLON = {}));
  35295. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  35296. var BABYLON;
  35297. (function (BABYLON) {
  35298. var PostProcessRenderPass = (function () {
  35299. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  35300. this._enabled = true;
  35301. this._refCount = 0;
  35302. this._name = name;
  35303. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  35304. this.setRenderList(renderList);
  35305. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  35306. this._renderTexture.onAfterRenderObservable.add(afterRender);
  35307. this._scene = scene;
  35308. this._renderList = renderList;
  35309. }
  35310. // private
  35311. PostProcessRenderPass.prototype._incRefCount = function () {
  35312. if (this._refCount === 0) {
  35313. this._scene.customRenderTargets.push(this._renderTexture);
  35314. }
  35315. return ++this._refCount;
  35316. };
  35317. PostProcessRenderPass.prototype._decRefCount = function () {
  35318. this._refCount--;
  35319. if (this._refCount <= 0) {
  35320. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  35321. }
  35322. return this._refCount;
  35323. };
  35324. PostProcessRenderPass.prototype._update = function () {
  35325. this.setRenderList(this._renderList);
  35326. };
  35327. // public
  35328. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  35329. this._renderTexture.renderList = renderList;
  35330. };
  35331. PostProcessRenderPass.prototype.getRenderTexture = function () {
  35332. return this._renderTexture;
  35333. };
  35334. return PostProcessRenderPass;
  35335. }());
  35336. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  35337. })(BABYLON || (BABYLON = {}));
  35338. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  35339. var BABYLON;
  35340. (function (BABYLON) {
  35341. var PostProcessRenderEffect = (function () {
  35342. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  35343. this._engine = engine;
  35344. this._name = name;
  35345. this._singleInstance = singleInstance || true;
  35346. this._getPostProcess = getPostProcess;
  35347. this._cameras = [];
  35348. this._indicesForCamera = [];
  35349. this._postProcesses = {};
  35350. this._renderPasses = {};
  35351. this._renderEffectAsPasses = {};
  35352. }
  35353. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  35354. get: function () {
  35355. for (var index in this._postProcesses) {
  35356. if (!this._postProcesses[index].isSupported) {
  35357. return false;
  35358. }
  35359. }
  35360. return true;
  35361. },
  35362. enumerable: true,
  35363. configurable: true
  35364. });
  35365. PostProcessRenderEffect.prototype._update = function () {
  35366. for (var renderPassName in this._renderPasses) {
  35367. this._renderPasses[renderPassName]._update();
  35368. }
  35369. };
  35370. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  35371. this._renderPasses[renderPass._name] = renderPass;
  35372. this._linkParameters();
  35373. };
  35374. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  35375. delete this._renderPasses[renderPass._name];
  35376. this._linkParameters();
  35377. };
  35378. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  35379. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  35380. this._linkParameters();
  35381. };
  35382. PostProcessRenderEffect.prototype.getPass = function (passName) {
  35383. for (var renderPassName in this._renderPasses) {
  35384. if (renderPassName === passName) {
  35385. return this._renderPasses[passName];
  35386. }
  35387. }
  35388. };
  35389. PostProcessRenderEffect.prototype.emptyPasses = function () {
  35390. this._renderPasses = {};
  35391. this._linkParameters();
  35392. };
  35393. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  35394. var cameraKey;
  35395. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35396. for (var i = 0; i < _cam.length; i++) {
  35397. var camera = _cam[i];
  35398. var cameraName = camera.name;
  35399. if (this._singleInstance) {
  35400. cameraKey = 0;
  35401. }
  35402. else {
  35403. cameraKey = cameraName;
  35404. }
  35405. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  35406. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  35407. if (!this._indicesForCamera[cameraName]) {
  35408. this._indicesForCamera[cameraName] = [];
  35409. }
  35410. this._indicesForCamera[cameraName].push(index);
  35411. if (this._cameras.indexOf(camera) === -1) {
  35412. this._cameras[cameraName] = camera;
  35413. }
  35414. for (var passName in this._renderPasses) {
  35415. this._renderPasses[passName]._incRefCount();
  35416. }
  35417. }
  35418. this._linkParameters();
  35419. };
  35420. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  35421. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35422. for (var i = 0; i < _cam.length; i++) {
  35423. var camera = _cam[i];
  35424. var cameraName = camera.name;
  35425. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35426. var index = this._cameras.indexOf(cameraName);
  35427. this._indicesForCamera.splice(index, 1);
  35428. this._cameras.splice(index, 1);
  35429. for (var passName in this._renderPasses) {
  35430. this._renderPasses[passName]._decRefCount();
  35431. }
  35432. }
  35433. };
  35434. PostProcessRenderEffect.prototype._enable = function (cameras) {
  35435. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35436. for (var i = 0; i < _cam.length; i++) {
  35437. var camera = _cam[i];
  35438. var cameraName = camera.name;
  35439. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  35440. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  35441. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  35442. }
  35443. }
  35444. for (var passName in this._renderPasses) {
  35445. this._renderPasses[passName]._incRefCount();
  35446. }
  35447. }
  35448. };
  35449. PostProcessRenderEffect.prototype._disable = function (cameras) {
  35450. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35451. for (var i = 0; i < _cam.length; i++) {
  35452. var camera = _cam[i];
  35453. var cameraName = camera.Name;
  35454. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35455. for (var passName in this._renderPasses) {
  35456. this._renderPasses[passName]._decRefCount();
  35457. }
  35458. }
  35459. };
  35460. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  35461. if (this._singleInstance) {
  35462. return this._postProcesses[0];
  35463. }
  35464. else {
  35465. return this._postProcesses[camera.name];
  35466. }
  35467. };
  35468. PostProcessRenderEffect.prototype._linkParameters = function () {
  35469. var _this = this;
  35470. for (var index in this._postProcesses) {
  35471. if (this.applyParameters) {
  35472. this.applyParameters(this._postProcesses[index]);
  35473. }
  35474. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  35475. _this._linkTextures(effect);
  35476. });
  35477. }
  35478. };
  35479. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  35480. for (var renderPassName in this._renderPasses) {
  35481. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  35482. }
  35483. for (var renderEffectName in this._renderEffectAsPasses) {
  35484. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  35485. }
  35486. };
  35487. return PostProcessRenderEffect;
  35488. }());
  35489. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  35490. })(BABYLON || (BABYLON = {}));
  35491. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  35492. var BABYLON;
  35493. (function (BABYLON) {
  35494. var PostProcessRenderPipeline = (function () {
  35495. function PostProcessRenderPipeline(engine, name) {
  35496. this._engine = engine;
  35497. this._name = name;
  35498. this._renderEffects = {};
  35499. this._renderEffectsForIsolatedPass = {};
  35500. this._cameras = [];
  35501. }
  35502. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  35503. get: function () {
  35504. for (var renderEffectName in this._renderEffects) {
  35505. if (!this._renderEffects[renderEffectName].isSupported) {
  35506. return false;
  35507. }
  35508. }
  35509. return true;
  35510. },
  35511. enumerable: true,
  35512. configurable: true
  35513. });
  35514. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  35515. this._renderEffects[renderEffect._name] = renderEffect;
  35516. };
  35517. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  35518. var renderEffects = this._renderEffects[renderEffectName];
  35519. if (!renderEffects) {
  35520. return;
  35521. }
  35522. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35523. };
  35524. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  35525. var renderEffects = this._renderEffects[renderEffectName];
  35526. if (!renderEffects) {
  35527. return;
  35528. }
  35529. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35530. };
  35531. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  35532. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35533. var indicesToDelete = [];
  35534. var i;
  35535. for (i = 0; i < _cam.length; i++) {
  35536. var camera = _cam[i];
  35537. var cameraName = camera.name;
  35538. if (this._cameras.indexOf(camera) === -1) {
  35539. this._cameras[cameraName] = camera;
  35540. }
  35541. else if (unique) {
  35542. indicesToDelete.push(i);
  35543. }
  35544. }
  35545. for (i = 0; i < indicesToDelete.length; i++) {
  35546. cameras.splice(indicesToDelete[i], 1);
  35547. }
  35548. for (var renderEffectName in this._renderEffects) {
  35549. this._renderEffects[renderEffectName]._attachCameras(_cam);
  35550. }
  35551. };
  35552. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  35553. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35554. for (var renderEffectName in this._renderEffects) {
  35555. this._renderEffects[renderEffectName]._detachCameras(_cam);
  35556. }
  35557. for (var i = 0; i < _cam.length; i++) {
  35558. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  35559. }
  35560. };
  35561. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  35562. var _this = this;
  35563. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35564. var pass = null;
  35565. var renderEffectName;
  35566. for (renderEffectName in this._renderEffects) {
  35567. pass = this._renderEffects[renderEffectName].getPass(passName);
  35568. if (pass != null) {
  35569. break;
  35570. }
  35571. }
  35572. if (pass === null) {
  35573. return;
  35574. }
  35575. for (renderEffectName in this._renderEffects) {
  35576. this._renderEffects[renderEffectName]._disable(_cam);
  35577. }
  35578. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  35579. for (var i = 0; i < _cam.length; i++) {
  35580. var camera = _cam[i];
  35581. var cameraName = camera.name;
  35582. 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); });
  35583. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  35584. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  35585. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  35586. }
  35587. };
  35588. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  35589. var _this = this;
  35590. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35591. for (var i = 0; i < _cam.length; i++) {
  35592. var camera = _cam[i];
  35593. var cameraName = camera.name;
  35594. 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); });
  35595. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  35596. }
  35597. for (var renderEffectName in this._renderEffects) {
  35598. this._renderEffects[renderEffectName]._enable(_cam);
  35599. }
  35600. };
  35601. PostProcessRenderPipeline.prototype._update = function () {
  35602. for (var renderEffectName in this._renderEffects) {
  35603. this._renderEffects[renderEffectName]._update();
  35604. }
  35605. for (var i = 0; i < this._cameras.length; i++) {
  35606. var cameraName = this._cameras[i].name;
  35607. if (this._renderEffectsForIsolatedPass[cameraName]) {
  35608. this._renderEffectsForIsolatedPass[cameraName]._update();
  35609. }
  35610. }
  35611. };
  35612. PostProcessRenderPipeline.prototype.dispose = function () {
  35613. // Must be implemented by children
  35614. };
  35615. return PostProcessRenderPipeline;
  35616. }());
  35617. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  35618. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  35619. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  35620. })(BABYLON || (BABYLON = {}));
  35621. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  35622. var BABYLON;
  35623. (function (BABYLON) {
  35624. var PostProcessRenderPipelineManager = (function () {
  35625. function PostProcessRenderPipelineManager() {
  35626. this._renderPipelines = {};
  35627. }
  35628. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  35629. this._renderPipelines[renderPipeline._name] = renderPipeline;
  35630. };
  35631. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  35632. var renderPipeline = this._renderPipelines[renderPipelineName];
  35633. if (!renderPipeline) {
  35634. return;
  35635. }
  35636. renderPipeline._attachCameras(cameras, unique);
  35637. };
  35638. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  35639. var renderPipeline = this._renderPipelines[renderPipelineName];
  35640. if (!renderPipeline) {
  35641. return;
  35642. }
  35643. renderPipeline._detachCameras(cameras);
  35644. };
  35645. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35646. var renderPipeline = this._renderPipelines[renderPipelineName];
  35647. if (!renderPipeline) {
  35648. return;
  35649. }
  35650. renderPipeline._enableEffect(renderEffectName, cameras);
  35651. };
  35652. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35653. var renderPipeline = this._renderPipelines[renderPipelineName];
  35654. if (!renderPipeline) {
  35655. return;
  35656. }
  35657. renderPipeline._disableEffect(renderEffectName, cameras);
  35658. };
  35659. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  35660. var renderPipeline = this._renderPipelines[renderPipelineName];
  35661. if (!renderPipeline) {
  35662. return;
  35663. }
  35664. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  35665. };
  35666. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  35667. var renderPipeline = this._renderPipelines[renderPipelineName];
  35668. if (!renderPipeline) {
  35669. return;
  35670. }
  35671. renderPipeline._disableDisplayOnlyPass(cameras);
  35672. };
  35673. PostProcessRenderPipelineManager.prototype.update = function () {
  35674. for (var renderPipelineName in this._renderPipelines) {
  35675. var pipeline = this._renderPipelines[renderPipelineName];
  35676. if (!pipeline.isSupported) {
  35677. pipeline.dispose();
  35678. delete this._renderPipelines[renderPipelineName];
  35679. }
  35680. else {
  35681. pipeline._update();
  35682. }
  35683. }
  35684. };
  35685. return PostProcessRenderPipelineManager;
  35686. }());
  35687. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  35688. })(BABYLON || (BABYLON = {}));
  35689. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  35690. var BABYLON;
  35691. (function (BABYLON) {
  35692. var BoundingBoxRenderer = (function () {
  35693. function BoundingBoxRenderer(scene) {
  35694. this.frontColor = new BABYLON.Color3(1, 1, 1);
  35695. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  35696. this.showBackLines = true;
  35697. this.renderList = new BABYLON.SmartArray(32);
  35698. this._vertexBuffers = {};
  35699. this._scene = scene;
  35700. }
  35701. BoundingBoxRenderer.prototype._prepareRessources = function () {
  35702. if (this._colorShader) {
  35703. return;
  35704. }
  35705. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  35706. attributes: [BABYLON.VertexBuffer.PositionKind],
  35707. uniforms: ["worldViewProjection", "color"]
  35708. });
  35709. var engine = this._scene.getEngine();
  35710. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  35711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  35712. 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]);
  35713. };
  35714. BoundingBoxRenderer.prototype.reset = function () {
  35715. this.renderList.reset();
  35716. };
  35717. BoundingBoxRenderer.prototype.render = function () {
  35718. if (this.renderList.length === 0) {
  35719. return;
  35720. }
  35721. this._prepareRessources();
  35722. if (!this._colorShader.isReady()) {
  35723. return;
  35724. }
  35725. var engine = this._scene.getEngine();
  35726. engine.setDepthWrite(false);
  35727. this._colorShader._preBind();
  35728. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  35729. var boundingBox = this.renderList.data[boundingBoxIndex];
  35730. var min = boundingBox.minimum;
  35731. var max = boundingBox.maximum;
  35732. var diff = max.subtract(min);
  35733. var median = min.add(diff.scale(0.5));
  35734. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  35735. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  35736. .multiply(boundingBox.getWorldMatrix());
  35737. // VBOs
  35738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  35739. if (this.showBackLines) {
  35740. // Back
  35741. engine.setDepthFunctionToGreaterOrEqual();
  35742. this._scene.resetCachedMaterial();
  35743. this._colorShader.setColor4("color", this.backColor.toColor4());
  35744. this._colorShader.bind(worldMatrix);
  35745. // Draw order
  35746. engine.draw(false, 0, 24);
  35747. }
  35748. // Front
  35749. engine.setDepthFunctionToLess();
  35750. this._scene.resetCachedMaterial();
  35751. this._colorShader.setColor4("color", this.frontColor.toColor4());
  35752. this._colorShader.bind(worldMatrix);
  35753. // Draw order
  35754. engine.draw(false, 0, 24);
  35755. }
  35756. this._colorShader.unbind();
  35757. engine.setDepthFunctionToLessOrEqual();
  35758. engine.setDepthWrite(true);
  35759. };
  35760. BoundingBoxRenderer.prototype.dispose = function () {
  35761. if (!this._colorShader) {
  35762. return;
  35763. }
  35764. this._colorShader.dispose();
  35765. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35766. if (buffer) {
  35767. buffer.dispose();
  35768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35769. }
  35770. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35771. };
  35772. return BoundingBoxRenderer;
  35773. }());
  35774. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  35775. })(BABYLON || (BABYLON = {}));
  35776. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  35777. var BABYLON;
  35778. (function (BABYLON) {
  35779. var Condition = (function () {
  35780. function Condition(actionManager) {
  35781. this._actionManager = actionManager;
  35782. }
  35783. Condition.prototype.isValid = function () {
  35784. return true;
  35785. };
  35786. Condition.prototype._getProperty = function (propertyPath) {
  35787. return this._actionManager._getProperty(propertyPath);
  35788. };
  35789. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35790. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35791. };
  35792. Condition.prototype.serialize = function () {
  35793. };
  35794. Condition.prototype._serialize = function (serializedCondition) {
  35795. return {
  35796. type: 2,
  35797. children: [],
  35798. name: serializedCondition.name,
  35799. properties: serializedCondition.properties
  35800. };
  35801. };
  35802. return Condition;
  35803. }());
  35804. BABYLON.Condition = Condition;
  35805. var ValueCondition = (function (_super) {
  35806. __extends(ValueCondition, _super);
  35807. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35808. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35809. var _this = _super.call(this, actionManager) || this;
  35810. _this.propertyPath = propertyPath;
  35811. _this.value = value;
  35812. _this.operator = operator;
  35813. _this._target = target;
  35814. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35815. _this._property = _this._getProperty(_this.propertyPath);
  35816. return _this;
  35817. }
  35818. Object.defineProperty(ValueCondition, "IsEqual", {
  35819. get: function () {
  35820. return ValueCondition._IsEqual;
  35821. },
  35822. enumerable: true,
  35823. configurable: true
  35824. });
  35825. Object.defineProperty(ValueCondition, "IsDifferent", {
  35826. get: function () {
  35827. return ValueCondition._IsDifferent;
  35828. },
  35829. enumerable: true,
  35830. configurable: true
  35831. });
  35832. Object.defineProperty(ValueCondition, "IsGreater", {
  35833. get: function () {
  35834. return ValueCondition._IsGreater;
  35835. },
  35836. enumerable: true,
  35837. configurable: true
  35838. });
  35839. Object.defineProperty(ValueCondition, "IsLesser", {
  35840. get: function () {
  35841. return ValueCondition._IsLesser;
  35842. },
  35843. enumerable: true,
  35844. configurable: true
  35845. });
  35846. // Methods
  35847. ValueCondition.prototype.isValid = function () {
  35848. switch (this.operator) {
  35849. case ValueCondition.IsGreater:
  35850. return this._effectiveTarget[this._property] > this.value;
  35851. case ValueCondition.IsLesser:
  35852. return this._effectiveTarget[this._property] < this.value;
  35853. case ValueCondition.IsEqual:
  35854. case ValueCondition.IsDifferent:
  35855. var check;
  35856. if (this.value.equals) {
  35857. check = this.value.equals(this._effectiveTarget[this._property]);
  35858. }
  35859. else {
  35860. check = this.value === this._effectiveTarget[this._property];
  35861. }
  35862. return this.operator === ValueCondition.IsEqual ? check : !check;
  35863. }
  35864. return false;
  35865. };
  35866. ValueCondition.prototype.serialize = function () {
  35867. return this._serialize({
  35868. name: "ValueCondition",
  35869. properties: [
  35870. BABYLON.Action._GetTargetProperty(this._target),
  35871. { name: "propertyPath", value: this.propertyPath },
  35872. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35873. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35874. ]
  35875. });
  35876. };
  35877. ValueCondition.GetOperatorName = function (operator) {
  35878. switch (operator) {
  35879. case ValueCondition._IsEqual: return "IsEqual";
  35880. case ValueCondition._IsDifferent: return "IsDifferent";
  35881. case ValueCondition._IsGreater: return "IsGreater";
  35882. case ValueCondition._IsLesser: return "IsLesser";
  35883. default: return "";
  35884. }
  35885. };
  35886. return ValueCondition;
  35887. }(Condition));
  35888. // Statics
  35889. ValueCondition._IsEqual = 0;
  35890. ValueCondition._IsDifferent = 1;
  35891. ValueCondition._IsGreater = 2;
  35892. ValueCondition._IsLesser = 3;
  35893. BABYLON.ValueCondition = ValueCondition;
  35894. var PredicateCondition = (function (_super) {
  35895. __extends(PredicateCondition, _super);
  35896. function PredicateCondition(actionManager, predicate) {
  35897. var _this = _super.call(this, actionManager) || this;
  35898. _this.predicate = predicate;
  35899. return _this;
  35900. }
  35901. PredicateCondition.prototype.isValid = function () {
  35902. return this.predicate();
  35903. };
  35904. return PredicateCondition;
  35905. }(Condition));
  35906. BABYLON.PredicateCondition = PredicateCondition;
  35907. var StateCondition = (function (_super) {
  35908. __extends(StateCondition, _super);
  35909. function StateCondition(actionManager, target, value) {
  35910. var _this = _super.call(this, actionManager) || this;
  35911. _this.value = value;
  35912. _this._target = target;
  35913. return _this;
  35914. }
  35915. // Methods
  35916. StateCondition.prototype.isValid = function () {
  35917. return this._target.state === this.value;
  35918. };
  35919. StateCondition.prototype.serialize = function () {
  35920. return this._serialize({
  35921. name: "StateCondition",
  35922. properties: [
  35923. BABYLON.Action._GetTargetProperty(this._target),
  35924. { name: "value", value: this.value }
  35925. ]
  35926. });
  35927. };
  35928. return StateCondition;
  35929. }(Condition));
  35930. BABYLON.StateCondition = StateCondition;
  35931. })(BABYLON || (BABYLON = {}));
  35932. //# sourceMappingURL=babylon.condition.js.map
  35933. var BABYLON;
  35934. (function (BABYLON) {
  35935. var Action = (function () {
  35936. function Action(triggerOptions, condition) {
  35937. this.triggerOptions = triggerOptions;
  35938. if (triggerOptions.parameter) {
  35939. this.trigger = triggerOptions.trigger;
  35940. this._triggerParameter = triggerOptions.parameter;
  35941. }
  35942. else {
  35943. this.trigger = triggerOptions;
  35944. }
  35945. this._nextActiveAction = this;
  35946. this._condition = condition;
  35947. }
  35948. // Methods
  35949. Action.prototype._prepare = function () {
  35950. };
  35951. Action.prototype.getTriggerParameter = function () {
  35952. return this._triggerParameter;
  35953. };
  35954. Action.prototype._executeCurrent = function (evt) {
  35955. if (this._nextActiveAction._condition) {
  35956. var condition = this._nextActiveAction._condition;
  35957. var currentRenderId = this._actionManager.getScene().getRenderId();
  35958. // We cache the current evaluation for the current frame
  35959. if (condition._evaluationId === currentRenderId) {
  35960. if (!condition._currentResult) {
  35961. return;
  35962. }
  35963. }
  35964. else {
  35965. condition._evaluationId = currentRenderId;
  35966. if (!condition.isValid()) {
  35967. condition._currentResult = false;
  35968. return;
  35969. }
  35970. condition._currentResult = true;
  35971. }
  35972. }
  35973. this._nextActiveAction.execute(evt);
  35974. this.skipToNextActiveAction();
  35975. };
  35976. Action.prototype.execute = function (evt) {
  35977. };
  35978. Action.prototype.skipToNextActiveAction = function () {
  35979. if (this._nextActiveAction._child) {
  35980. if (!this._nextActiveAction._child._actionManager) {
  35981. this._nextActiveAction._child._actionManager = this._actionManager;
  35982. }
  35983. this._nextActiveAction = this._nextActiveAction._child;
  35984. }
  35985. else {
  35986. this._nextActiveAction = this;
  35987. }
  35988. };
  35989. Action.prototype.then = function (action) {
  35990. this._child = action;
  35991. action._actionManager = this._actionManager;
  35992. action._prepare();
  35993. return action;
  35994. };
  35995. Action.prototype._getProperty = function (propertyPath) {
  35996. return this._actionManager._getProperty(propertyPath);
  35997. };
  35998. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35999. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36000. };
  36001. Action.prototype.serialize = function (parent) {
  36002. };
  36003. // Called by BABYLON.Action objects in serialize(...). Internal use
  36004. Action.prototype._serialize = function (serializedAction, parent) {
  36005. var serializationObject = {
  36006. type: 1,
  36007. children: [],
  36008. name: serializedAction.name,
  36009. properties: serializedAction.properties || []
  36010. };
  36011. // Serialize child
  36012. if (this._child) {
  36013. this._child.serialize(serializationObject);
  36014. }
  36015. // Check if "this" has a condition
  36016. if (this._condition) {
  36017. var serializedCondition = this._condition.serialize();
  36018. serializedCondition.children.push(serializationObject);
  36019. if (parent) {
  36020. parent.children.push(serializedCondition);
  36021. }
  36022. return serializedCondition;
  36023. }
  36024. if (parent) {
  36025. parent.children.push(serializationObject);
  36026. }
  36027. return serializationObject;
  36028. };
  36029. return Action;
  36030. }());
  36031. Action._SerializeValueAsString = function (value) {
  36032. if (typeof value === "number") {
  36033. return value.toString();
  36034. }
  36035. if (typeof value === "boolean") {
  36036. return value ? "true" : "false";
  36037. }
  36038. if (value instanceof BABYLON.Vector2) {
  36039. return value.x + ", " + value.y;
  36040. }
  36041. if (value instanceof BABYLON.Vector3) {
  36042. return value.x + ", " + value.y + ", " + value.z;
  36043. }
  36044. if (value instanceof BABYLON.Color3) {
  36045. return value.r + ", " + value.g + ", " + value.b;
  36046. }
  36047. if (value instanceof BABYLON.Color4) {
  36048. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36049. }
  36050. return value; // string
  36051. };
  36052. Action._GetTargetProperty = function (target) {
  36053. return {
  36054. name: "target",
  36055. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36056. : target instanceof BABYLON.Light ? "LightProperties"
  36057. : target instanceof BABYLON.Camera ? "CameraProperties"
  36058. : "SceneProperties",
  36059. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36060. };
  36061. };
  36062. BABYLON.Action = Action;
  36063. })(BABYLON || (BABYLON = {}));
  36064. //# sourceMappingURL=babylon.action.js.map
  36065. var BABYLON;
  36066. (function (BABYLON) {
  36067. /**
  36068. * ActionEvent is the event beint sent when an action is triggered.
  36069. */
  36070. var ActionEvent = (function () {
  36071. /**
  36072. * @constructor
  36073. * @param source The mesh or sprite that triggered the action.
  36074. * @param pointerX The X mouse cursor position at the time of the event
  36075. * @param pointerY The Y mouse cursor position at the time of the event
  36076. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36077. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36078. */
  36079. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36080. this.source = source;
  36081. this.pointerX = pointerX;
  36082. this.pointerY = pointerY;
  36083. this.meshUnderPointer = meshUnderPointer;
  36084. this.sourceEvent = sourceEvent;
  36085. this.additionalData = additionalData;
  36086. }
  36087. /**
  36088. * Helper function to auto-create an ActionEvent from a source mesh.
  36089. * @param source The source mesh that triggered the event
  36090. * @param evt {Event} The original (browser) event
  36091. */
  36092. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36093. var scene = source.getScene();
  36094. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36095. };
  36096. /**
  36097. * Helper function to auto-create an ActionEvent from a source mesh.
  36098. * @param source The source sprite that triggered the event
  36099. * @param scene Scene associated with the sprite
  36100. * @param evt {Event} The original (browser) event
  36101. */
  36102. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36103. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36104. };
  36105. /**
  36106. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36107. * @param scene the scene where the event occurred
  36108. * @param evt {Event} The original (browser) event
  36109. */
  36110. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36111. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36112. };
  36113. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36114. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36115. };
  36116. return ActionEvent;
  36117. }());
  36118. BABYLON.ActionEvent = ActionEvent;
  36119. /**
  36120. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36121. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36122. */
  36123. var ActionManager = (function () {
  36124. function ActionManager(scene) {
  36125. // Members
  36126. this.actions = new Array();
  36127. this.hoverCursor = '';
  36128. this._scene = scene;
  36129. scene._actionManagers.push(this);
  36130. }
  36131. Object.defineProperty(ActionManager, "NothingTrigger", {
  36132. get: function () {
  36133. return ActionManager._NothingTrigger;
  36134. },
  36135. enumerable: true,
  36136. configurable: true
  36137. });
  36138. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36139. get: function () {
  36140. return ActionManager._OnPickTrigger;
  36141. },
  36142. enumerable: true,
  36143. configurable: true
  36144. });
  36145. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36146. get: function () {
  36147. return ActionManager._OnLeftPickTrigger;
  36148. },
  36149. enumerable: true,
  36150. configurable: true
  36151. });
  36152. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36153. get: function () {
  36154. return ActionManager._OnRightPickTrigger;
  36155. },
  36156. enumerable: true,
  36157. configurable: true
  36158. });
  36159. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36160. get: function () {
  36161. return ActionManager._OnCenterPickTrigger;
  36162. },
  36163. enumerable: true,
  36164. configurable: true
  36165. });
  36166. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36167. get: function () {
  36168. return ActionManager._OnPickDownTrigger;
  36169. },
  36170. enumerable: true,
  36171. configurable: true
  36172. });
  36173. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36174. get: function () {
  36175. return ActionManager._OnPickUpTrigger;
  36176. },
  36177. enumerable: true,
  36178. configurable: true
  36179. });
  36180. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36181. /// This trigger will only be raised if you also declared a OnPickDown
  36182. get: function () {
  36183. return ActionManager._OnPickOutTrigger;
  36184. },
  36185. enumerable: true,
  36186. configurable: true
  36187. });
  36188. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36189. get: function () {
  36190. return ActionManager._OnLongPressTrigger;
  36191. },
  36192. enumerable: true,
  36193. configurable: true
  36194. });
  36195. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36196. get: function () {
  36197. return ActionManager._OnPointerOverTrigger;
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36203. get: function () {
  36204. return ActionManager._OnPointerOutTrigger;
  36205. },
  36206. enumerable: true,
  36207. configurable: true
  36208. });
  36209. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36210. get: function () {
  36211. return ActionManager._OnEveryFrameTrigger;
  36212. },
  36213. enumerable: true,
  36214. configurable: true
  36215. });
  36216. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36217. get: function () {
  36218. return ActionManager._OnIntersectionEnterTrigger;
  36219. },
  36220. enumerable: true,
  36221. configurable: true
  36222. });
  36223. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36224. get: function () {
  36225. return ActionManager._OnIntersectionExitTrigger;
  36226. },
  36227. enumerable: true,
  36228. configurable: true
  36229. });
  36230. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36231. get: function () {
  36232. return ActionManager._OnKeyDownTrigger;
  36233. },
  36234. enumerable: true,
  36235. configurable: true
  36236. });
  36237. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36238. get: function () {
  36239. return ActionManager._OnKeyUpTrigger;
  36240. },
  36241. enumerable: true,
  36242. configurable: true
  36243. });
  36244. // Methods
  36245. ActionManager.prototype.dispose = function () {
  36246. var index = this._scene._actionManagers.indexOf(this);
  36247. if (index > -1) {
  36248. this._scene._actionManagers.splice(index, 1);
  36249. }
  36250. };
  36251. ActionManager.prototype.getScene = function () {
  36252. return this._scene;
  36253. };
  36254. /**
  36255. * Does this action manager handles actions of any of the given triggers
  36256. * @param {number[]} triggers - the triggers to be tested
  36257. * @return {boolean} whether one (or more) of the triggers is handeled
  36258. */
  36259. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36260. for (var index = 0; index < this.actions.length; index++) {
  36261. var action = this.actions[index];
  36262. if (triggers.indexOf(action.trigger) > -1) {
  36263. return true;
  36264. }
  36265. }
  36266. return false;
  36267. };
  36268. /**
  36269. * Does this action manager handles actions of a given trigger
  36270. * @param {number} trigger - the trigger to be tested
  36271. * @return {boolean} whether the trigger is handeled
  36272. */
  36273. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36274. for (var index = 0; index < this.actions.length; index++) {
  36275. var action = this.actions[index];
  36276. if (action.trigger === trigger) {
  36277. return true;
  36278. }
  36279. }
  36280. return false;
  36281. };
  36282. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36283. /**
  36284. * Does this action manager has pointer triggers
  36285. * @return {boolean} whether or not it has pointer triggers
  36286. */
  36287. get: function () {
  36288. for (var index = 0; index < this.actions.length; index++) {
  36289. var action = this.actions[index];
  36290. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36291. return true;
  36292. }
  36293. }
  36294. return false;
  36295. },
  36296. enumerable: true,
  36297. configurable: true
  36298. });
  36299. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36300. /**
  36301. * Does this action manager has pick triggers
  36302. * @return {boolean} whether or not it has pick triggers
  36303. */
  36304. get: function () {
  36305. for (var index = 0; index < this.actions.length; index++) {
  36306. var action = this.actions[index];
  36307. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36308. return true;
  36309. }
  36310. }
  36311. return false;
  36312. },
  36313. enumerable: true,
  36314. configurable: true
  36315. });
  36316. /**
  36317. * Registers an action to this action manager
  36318. * @param {BABYLON.Action} action - the action to be registered
  36319. * @return {BABYLON.Action} the action amended (prepared) after registration
  36320. */
  36321. ActionManager.prototype.registerAction = function (action) {
  36322. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36323. if (this.getScene().actionManager !== this) {
  36324. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36325. return null;
  36326. }
  36327. }
  36328. this.actions.push(action);
  36329. action._actionManager = this;
  36330. action._prepare();
  36331. return action;
  36332. };
  36333. /**
  36334. * Process a specific trigger
  36335. * @param {number} trigger - the trigger to process
  36336. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36337. */
  36338. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36339. for (var index = 0; index < this.actions.length; index++) {
  36340. var action = this.actions[index];
  36341. if (action.trigger === trigger) {
  36342. if (trigger === ActionManager.OnKeyUpTrigger
  36343. || trigger === ActionManager.OnKeyDownTrigger) {
  36344. var parameter = action.getTriggerParameter();
  36345. if (parameter) {
  36346. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36347. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36348. if (actualkey !== parameter.toLowerCase()) {
  36349. continue;
  36350. }
  36351. }
  36352. }
  36353. action._executeCurrent(evt);
  36354. }
  36355. }
  36356. };
  36357. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36358. var properties = propertyPath.split(".");
  36359. for (var index = 0; index < properties.length - 1; index++) {
  36360. target = target[properties[index]];
  36361. }
  36362. return target;
  36363. };
  36364. ActionManager.prototype._getProperty = function (propertyPath) {
  36365. var properties = propertyPath.split(".");
  36366. return properties[properties.length - 1];
  36367. };
  36368. ActionManager.prototype.serialize = function (name) {
  36369. var root = {
  36370. children: [],
  36371. name: name,
  36372. type: 3,
  36373. properties: [] // Empty for root but required
  36374. };
  36375. for (var i = 0; i < this.actions.length; i++) {
  36376. var triggerObject = {
  36377. type: 0,
  36378. children: [],
  36379. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36380. properties: []
  36381. };
  36382. var triggerOptions = this.actions[i].triggerOptions;
  36383. if (triggerOptions && typeof triggerOptions !== "number") {
  36384. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36385. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36386. }
  36387. else {
  36388. var parameter = {};
  36389. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36390. if (triggerOptions.parameter.mesh) {
  36391. parameter._meshId = triggerOptions.parameter.mesh.id;
  36392. }
  36393. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36394. }
  36395. }
  36396. // Serialize child action, recursively
  36397. this.actions[i].serialize(triggerObject);
  36398. // Add serialized trigger
  36399. root.children.push(triggerObject);
  36400. }
  36401. return root;
  36402. };
  36403. ActionManager.Parse = function (parsedActions, object, scene) {
  36404. var actionManager = new BABYLON.ActionManager(scene);
  36405. if (object === null)
  36406. scene.actionManager = actionManager;
  36407. else
  36408. object.actionManager = actionManager;
  36409. // instanciate a new object
  36410. var instanciate = function (name, params) {
  36411. var newInstance = Object.create(BABYLON[name].prototype);
  36412. newInstance.constructor.apply(newInstance, params);
  36413. return newInstance;
  36414. };
  36415. var parseParameter = function (name, value, target, propertyPath) {
  36416. if (propertyPath === null) {
  36417. // String, boolean or float
  36418. var floatValue = parseFloat(value);
  36419. if (value === "true" || value === "false")
  36420. return value === "true";
  36421. else
  36422. return isNaN(floatValue) ? value : floatValue;
  36423. }
  36424. var effectiveTarget = propertyPath.split(".");
  36425. var values = value.split(",");
  36426. // Get effective Target
  36427. for (var i = 0; i < effectiveTarget.length; i++) {
  36428. target = target[effectiveTarget[i]];
  36429. }
  36430. // Return appropriate value with its type
  36431. if (typeof (target) === "boolean")
  36432. return values[0] === "true";
  36433. if (typeof (target) === "string")
  36434. return values[0];
  36435. // Parameters with multiple values such as Vector3 etc.
  36436. var split = new Array();
  36437. for (var i = 0; i < values.length; i++)
  36438. split.push(parseFloat(values[i]));
  36439. if (target instanceof BABYLON.Vector3)
  36440. return BABYLON.Vector3.FromArray(split);
  36441. if (target instanceof BABYLON.Vector4)
  36442. return BABYLON.Vector4.FromArray(split);
  36443. if (target instanceof BABYLON.Color3)
  36444. return BABYLON.Color3.FromArray(split);
  36445. if (target instanceof BABYLON.Color4)
  36446. return BABYLON.Color4.FromArray(split);
  36447. return parseFloat(values[0]);
  36448. };
  36449. // traverse graph per trigger
  36450. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36451. if (combineArray === void 0) { combineArray = null; }
  36452. if (parsedAction.detached)
  36453. return;
  36454. var parameters = new Array();
  36455. var target = null;
  36456. var propertyPath = null;
  36457. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36458. // Parameters
  36459. if (parsedAction.type === 2)
  36460. parameters.push(actionManager);
  36461. else
  36462. parameters.push(trigger);
  36463. if (combine) {
  36464. var actions = new Array();
  36465. for (var j = 0; j < parsedAction.combine.length; j++) {
  36466. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36467. }
  36468. parameters.push(actions);
  36469. }
  36470. else {
  36471. for (var i = 0; i < parsedAction.properties.length; i++) {
  36472. var value = parsedAction.properties[i].value;
  36473. var name = parsedAction.properties[i].name;
  36474. var targetType = parsedAction.properties[i].targetType;
  36475. if (name === "target")
  36476. if (targetType !== null && targetType === "SceneProperties")
  36477. value = target = scene;
  36478. else
  36479. value = target = scene.getNodeByName(value);
  36480. else if (name === "parent")
  36481. value = scene.getNodeByName(value);
  36482. else if (name === "sound")
  36483. value = scene.getSoundByName(value);
  36484. else if (name !== "propertyPath") {
  36485. if (parsedAction.type === 2 && name === "operator")
  36486. value = BABYLON.ValueCondition[value];
  36487. else
  36488. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36489. }
  36490. else {
  36491. propertyPath = value;
  36492. }
  36493. parameters.push(value);
  36494. }
  36495. }
  36496. if (combineArray === null) {
  36497. parameters.push(condition);
  36498. }
  36499. else {
  36500. parameters.push(null);
  36501. }
  36502. // If interpolate value action
  36503. if (parsedAction.name === "InterpolateValueAction") {
  36504. var param = parameters[parameters.length - 2];
  36505. parameters[parameters.length - 1] = param;
  36506. parameters[parameters.length - 2] = condition;
  36507. }
  36508. // Action or condition(s) and not CombineAction
  36509. var newAction = instanciate(parsedAction.name, parameters);
  36510. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36511. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36512. if (action)
  36513. action.then(nothing);
  36514. else
  36515. actionManager.registerAction(nothing);
  36516. action = nothing;
  36517. }
  36518. if (combineArray === null) {
  36519. if (newAction instanceof BABYLON.Condition) {
  36520. condition = newAction;
  36521. newAction = action;
  36522. }
  36523. else {
  36524. condition = null;
  36525. if (action)
  36526. action.then(newAction);
  36527. else
  36528. actionManager.registerAction(newAction);
  36529. }
  36530. }
  36531. else {
  36532. combineArray.push(newAction);
  36533. }
  36534. for (var i = 0; i < parsedAction.children.length; i++)
  36535. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36536. };
  36537. // triggers
  36538. for (var i = 0; i < parsedActions.children.length; i++) {
  36539. var triggerParams;
  36540. var trigger = parsedActions.children[i];
  36541. if (trigger.properties.length > 0) {
  36542. var param = trigger.properties[0].value;
  36543. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36544. if (value._meshId) {
  36545. value.mesh = scene.getMeshByID(value._meshId);
  36546. }
  36547. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36548. }
  36549. else
  36550. triggerParams = BABYLON.ActionManager[trigger.name];
  36551. for (var j = 0; j < trigger.children.length; j++) {
  36552. if (!trigger.detached)
  36553. traverse(trigger.children[j], triggerParams, null, null);
  36554. }
  36555. }
  36556. };
  36557. ActionManager.GetTriggerName = function (trigger) {
  36558. switch (trigger) {
  36559. case 0: return "NothingTrigger";
  36560. case 1: return "OnPickTrigger";
  36561. case 2: return "OnLeftPickTrigger";
  36562. case 3: return "OnRightPickTrigger";
  36563. case 4: return "OnCenterPickTrigger";
  36564. case 5: return "OnPickDownTrigger";
  36565. case 6: return "OnPickUpTrigger";
  36566. case 7: return "OnLongPressTrigger";
  36567. case 8: return "OnPointerOverTrigger";
  36568. case 9: return "OnPointerOutTrigger";
  36569. case 10: return "OnEveryFrameTrigger";
  36570. case 11: return "OnIntersectionEnterTrigger";
  36571. case 12: return "OnIntersectionExitTrigger";
  36572. case 13: return "OnKeyDownTrigger";
  36573. case 14: return "OnKeyUpTrigger";
  36574. case 15: return "OnPickOutTrigger";
  36575. default: return "";
  36576. }
  36577. };
  36578. return ActionManager;
  36579. }());
  36580. // Statics
  36581. ActionManager._NothingTrigger = 0;
  36582. ActionManager._OnPickTrigger = 1;
  36583. ActionManager._OnLeftPickTrigger = 2;
  36584. ActionManager._OnRightPickTrigger = 3;
  36585. ActionManager._OnCenterPickTrigger = 4;
  36586. ActionManager._OnPickDownTrigger = 5;
  36587. ActionManager._OnPickUpTrigger = 6;
  36588. ActionManager._OnLongPressTrigger = 7;
  36589. ActionManager._OnPointerOverTrigger = 8;
  36590. ActionManager._OnPointerOutTrigger = 9;
  36591. ActionManager._OnEveryFrameTrigger = 10;
  36592. ActionManager._OnIntersectionEnterTrigger = 11;
  36593. ActionManager._OnIntersectionExitTrigger = 12;
  36594. ActionManager._OnKeyDownTrigger = 13;
  36595. ActionManager._OnKeyUpTrigger = 14;
  36596. ActionManager._OnPickOutTrigger = 15;
  36597. ActionManager.DragMovementThreshold = 10; // in pixels
  36598. ActionManager.LongPressDelay = 500; // in milliseconds
  36599. BABYLON.ActionManager = ActionManager;
  36600. })(BABYLON || (BABYLON = {}));
  36601. //# sourceMappingURL=babylon.actionManager.js.map
  36602. var BABYLON;
  36603. (function (BABYLON) {
  36604. var InterpolateValueAction = (function (_super) {
  36605. __extends(InterpolateValueAction, _super);
  36606. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36607. if (duration === void 0) { duration = 1000; }
  36608. var _this = _super.call(this, triggerOptions, condition) || this;
  36609. _this.propertyPath = propertyPath;
  36610. _this.value = value;
  36611. _this.duration = duration;
  36612. _this.stopOtherAnimations = stopOtherAnimations;
  36613. _this.onInterpolationDone = onInterpolationDone;
  36614. _this._target = _this._effectiveTarget = target;
  36615. return _this;
  36616. }
  36617. InterpolateValueAction.prototype._prepare = function () {
  36618. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36619. this._property = this._getProperty(this.propertyPath);
  36620. };
  36621. InterpolateValueAction.prototype.execute = function () {
  36622. var scene = this._actionManager.getScene();
  36623. var keys = [
  36624. {
  36625. frame: 0,
  36626. value: this._effectiveTarget[this._property]
  36627. }, {
  36628. frame: 100,
  36629. value: this.value
  36630. }
  36631. ];
  36632. var dataType;
  36633. if (typeof this.value === "number") {
  36634. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36635. }
  36636. else if (this.value instanceof BABYLON.Color3) {
  36637. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36638. }
  36639. else if (this.value instanceof BABYLON.Vector3) {
  36640. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36641. }
  36642. else if (this.value instanceof BABYLON.Matrix) {
  36643. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36644. }
  36645. else if (this.value instanceof BABYLON.Quaternion) {
  36646. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36647. }
  36648. else {
  36649. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36650. return;
  36651. }
  36652. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36653. animation.setKeys(keys);
  36654. if (this.stopOtherAnimations) {
  36655. scene.stopAnimation(this._effectiveTarget);
  36656. }
  36657. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36658. };
  36659. InterpolateValueAction.prototype.serialize = function (parent) {
  36660. return _super.prototype._serialize.call(this, {
  36661. name: "InterpolateValueAction",
  36662. properties: [
  36663. BABYLON.Action._GetTargetProperty(this._target),
  36664. { name: "propertyPath", value: this.propertyPath },
  36665. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36666. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36667. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36668. ]
  36669. }, parent);
  36670. };
  36671. return InterpolateValueAction;
  36672. }(BABYLON.Action));
  36673. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36674. })(BABYLON || (BABYLON = {}));
  36675. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36676. var BABYLON;
  36677. (function (BABYLON) {
  36678. var SwitchBooleanAction = (function (_super) {
  36679. __extends(SwitchBooleanAction, _super);
  36680. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36681. var _this = _super.call(this, triggerOptions, condition) || this;
  36682. _this.propertyPath = propertyPath;
  36683. _this._target = _this._effectiveTarget = target;
  36684. return _this;
  36685. }
  36686. SwitchBooleanAction.prototype._prepare = function () {
  36687. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36688. this._property = this._getProperty(this.propertyPath);
  36689. };
  36690. SwitchBooleanAction.prototype.execute = function () {
  36691. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36692. };
  36693. SwitchBooleanAction.prototype.serialize = function (parent) {
  36694. return _super.prototype._serialize.call(this, {
  36695. name: "SwitchBooleanAction",
  36696. properties: [
  36697. BABYLON.Action._GetTargetProperty(this._target),
  36698. { name: "propertyPath", value: this.propertyPath }
  36699. ]
  36700. }, parent);
  36701. };
  36702. return SwitchBooleanAction;
  36703. }(BABYLON.Action));
  36704. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36705. var SetStateAction = (function (_super) {
  36706. __extends(SetStateAction, _super);
  36707. function SetStateAction(triggerOptions, target, value, condition) {
  36708. var _this = _super.call(this, triggerOptions, condition) || this;
  36709. _this.value = value;
  36710. _this._target = target;
  36711. return _this;
  36712. }
  36713. SetStateAction.prototype.execute = function () {
  36714. this._target.state = this.value;
  36715. };
  36716. SetStateAction.prototype.serialize = function (parent) {
  36717. return _super.prototype._serialize.call(this, {
  36718. name: "SetStateAction",
  36719. properties: [
  36720. BABYLON.Action._GetTargetProperty(this._target),
  36721. { name: "value", value: this.value }
  36722. ]
  36723. }, parent);
  36724. };
  36725. return SetStateAction;
  36726. }(BABYLON.Action));
  36727. BABYLON.SetStateAction = SetStateAction;
  36728. var SetValueAction = (function (_super) {
  36729. __extends(SetValueAction, _super);
  36730. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36731. var _this = _super.call(this, triggerOptions, condition) || this;
  36732. _this.propertyPath = propertyPath;
  36733. _this.value = value;
  36734. _this._target = _this._effectiveTarget = target;
  36735. return _this;
  36736. }
  36737. SetValueAction.prototype._prepare = function () {
  36738. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36739. this._property = this._getProperty(this.propertyPath);
  36740. };
  36741. SetValueAction.prototype.execute = function () {
  36742. this._effectiveTarget[this._property] = this.value;
  36743. if (this._target.markAsDirty) {
  36744. this._target.markAsDirty(this._property);
  36745. }
  36746. };
  36747. SetValueAction.prototype.serialize = function (parent) {
  36748. return _super.prototype._serialize.call(this, {
  36749. name: "SetValueAction",
  36750. properties: [
  36751. BABYLON.Action._GetTargetProperty(this._target),
  36752. { name: "propertyPath", value: this.propertyPath },
  36753. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36754. ]
  36755. }, parent);
  36756. };
  36757. return SetValueAction;
  36758. }(BABYLON.Action));
  36759. BABYLON.SetValueAction = SetValueAction;
  36760. var IncrementValueAction = (function (_super) {
  36761. __extends(IncrementValueAction, _super);
  36762. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36763. var _this = _super.call(this, triggerOptions, condition) || this;
  36764. _this.propertyPath = propertyPath;
  36765. _this.value = value;
  36766. _this._target = _this._effectiveTarget = target;
  36767. return _this;
  36768. }
  36769. IncrementValueAction.prototype._prepare = function () {
  36770. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36771. this._property = this._getProperty(this.propertyPath);
  36772. if (typeof this._effectiveTarget[this._property] !== "number") {
  36773. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36774. }
  36775. };
  36776. IncrementValueAction.prototype.execute = function () {
  36777. this._effectiveTarget[this._property] += this.value;
  36778. if (this._target.markAsDirty) {
  36779. this._target.markAsDirty(this._property);
  36780. }
  36781. };
  36782. IncrementValueAction.prototype.serialize = function (parent) {
  36783. return _super.prototype._serialize.call(this, {
  36784. name: "IncrementValueAction",
  36785. properties: [
  36786. BABYLON.Action._GetTargetProperty(this._target),
  36787. { name: "propertyPath", value: this.propertyPath },
  36788. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36789. ]
  36790. }, parent);
  36791. };
  36792. return IncrementValueAction;
  36793. }(BABYLON.Action));
  36794. BABYLON.IncrementValueAction = IncrementValueAction;
  36795. var PlayAnimationAction = (function (_super) {
  36796. __extends(PlayAnimationAction, _super);
  36797. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36798. var _this = _super.call(this, triggerOptions, condition) || this;
  36799. _this.from = from;
  36800. _this.to = to;
  36801. _this.loop = loop;
  36802. _this._target = target;
  36803. return _this;
  36804. }
  36805. PlayAnimationAction.prototype._prepare = function () {
  36806. };
  36807. PlayAnimationAction.prototype.execute = function () {
  36808. var scene = this._actionManager.getScene();
  36809. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36810. };
  36811. PlayAnimationAction.prototype.serialize = function (parent) {
  36812. return _super.prototype._serialize.call(this, {
  36813. name: "PlayAnimationAction",
  36814. properties: [
  36815. BABYLON.Action._GetTargetProperty(this._target),
  36816. { name: "from", value: String(this.from) },
  36817. { name: "to", value: String(this.to) },
  36818. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36819. ]
  36820. }, parent);
  36821. };
  36822. return PlayAnimationAction;
  36823. }(BABYLON.Action));
  36824. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36825. var StopAnimationAction = (function (_super) {
  36826. __extends(StopAnimationAction, _super);
  36827. function StopAnimationAction(triggerOptions, target, condition) {
  36828. var _this = _super.call(this, triggerOptions, condition) || this;
  36829. _this._target = target;
  36830. return _this;
  36831. }
  36832. StopAnimationAction.prototype._prepare = function () {
  36833. };
  36834. StopAnimationAction.prototype.execute = function () {
  36835. var scene = this._actionManager.getScene();
  36836. scene.stopAnimation(this._target);
  36837. };
  36838. StopAnimationAction.prototype.serialize = function (parent) {
  36839. return _super.prototype._serialize.call(this, {
  36840. name: "StopAnimationAction",
  36841. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36842. }, parent);
  36843. };
  36844. return StopAnimationAction;
  36845. }(BABYLON.Action));
  36846. BABYLON.StopAnimationAction = StopAnimationAction;
  36847. var DoNothingAction = (function (_super) {
  36848. __extends(DoNothingAction, _super);
  36849. function DoNothingAction(triggerOptions, condition) {
  36850. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36851. return _super.call(this, triggerOptions, condition) || this;
  36852. }
  36853. DoNothingAction.prototype.execute = function () {
  36854. };
  36855. DoNothingAction.prototype.serialize = function (parent) {
  36856. return _super.prototype._serialize.call(this, {
  36857. name: "DoNothingAction",
  36858. properties: []
  36859. }, parent);
  36860. };
  36861. return DoNothingAction;
  36862. }(BABYLON.Action));
  36863. BABYLON.DoNothingAction = DoNothingAction;
  36864. var CombineAction = (function (_super) {
  36865. __extends(CombineAction, _super);
  36866. function CombineAction(triggerOptions, children, condition) {
  36867. var _this = _super.call(this, triggerOptions, condition) || this;
  36868. _this.children = children;
  36869. return _this;
  36870. }
  36871. CombineAction.prototype._prepare = function () {
  36872. for (var index = 0; index < this.children.length; index++) {
  36873. this.children[index]._actionManager = this._actionManager;
  36874. this.children[index]._prepare();
  36875. }
  36876. };
  36877. CombineAction.prototype.execute = function (evt) {
  36878. for (var index = 0; index < this.children.length; index++) {
  36879. this.children[index].execute(evt);
  36880. }
  36881. };
  36882. CombineAction.prototype.serialize = function (parent) {
  36883. var serializationObject = _super.prototype._serialize.call(this, {
  36884. name: "CombineAction",
  36885. properties: [],
  36886. combine: []
  36887. }, parent);
  36888. for (var i = 0; i < this.children.length; i++) {
  36889. serializationObject.combine.push(this.children[i].serialize(null));
  36890. }
  36891. return serializationObject;
  36892. };
  36893. return CombineAction;
  36894. }(BABYLON.Action));
  36895. BABYLON.CombineAction = CombineAction;
  36896. var ExecuteCodeAction = (function (_super) {
  36897. __extends(ExecuteCodeAction, _super);
  36898. function ExecuteCodeAction(triggerOptions, func, condition) {
  36899. var _this = _super.call(this, triggerOptions, condition) || this;
  36900. _this.func = func;
  36901. return _this;
  36902. }
  36903. ExecuteCodeAction.prototype.execute = function (evt) {
  36904. this.func(evt);
  36905. };
  36906. return ExecuteCodeAction;
  36907. }(BABYLON.Action));
  36908. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36909. var SetParentAction = (function (_super) {
  36910. __extends(SetParentAction, _super);
  36911. function SetParentAction(triggerOptions, target, parent, condition) {
  36912. var _this = _super.call(this, triggerOptions, condition) || this;
  36913. _this._target = target;
  36914. _this._parent = parent;
  36915. return _this;
  36916. }
  36917. SetParentAction.prototype._prepare = function () {
  36918. };
  36919. SetParentAction.prototype.execute = function () {
  36920. if (this._target.parent === this._parent) {
  36921. return;
  36922. }
  36923. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36924. invertParentWorldMatrix.invert();
  36925. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36926. this._target.parent = this._parent;
  36927. };
  36928. SetParentAction.prototype.serialize = function (parent) {
  36929. return _super.prototype._serialize.call(this, {
  36930. name: "SetParentAction",
  36931. properties: [
  36932. BABYLON.Action._GetTargetProperty(this._target),
  36933. BABYLON.Action._GetTargetProperty(this._parent),
  36934. ]
  36935. }, parent);
  36936. };
  36937. return SetParentAction;
  36938. }(BABYLON.Action));
  36939. BABYLON.SetParentAction = SetParentAction;
  36940. var PlaySoundAction = (function (_super) {
  36941. __extends(PlaySoundAction, _super);
  36942. function PlaySoundAction(triggerOptions, sound, condition) {
  36943. var _this = _super.call(this, triggerOptions, condition) || this;
  36944. _this._sound = sound;
  36945. return _this;
  36946. }
  36947. PlaySoundAction.prototype._prepare = function () {
  36948. };
  36949. PlaySoundAction.prototype.execute = function () {
  36950. if (this._sound !== undefined)
  36951. this._sound.play();
  36952. };
  36953. PlaySoundAction.prototype.serialize = function (parent) {
  36954. return _super.prototype._serialize.call(this, {
  36955. name: "PlaySoundAction",
  36956. properties: [{ name: "sound", value: this._sound.name }]
  36957. }, parent);
  36958. };
  36959. return PlaySoundAction;
  36960. }(BABYLON.Action));
  36961. BABYLON.PlaySoundAction = PlaySoundAction;
  36962. var StopSoundAction = (function (_super) {
  36963. __extends(StopSoundAction, _super);
  36964. function StopSoundAction(triggerOptions, sound, condition) {
  36965. var _this = _super.call(this, triggerOptions, condition) || this;
  36966. _this._sound = sound;
  36967. return _this;
  36968. }
  36969. StopSoundAction.prototype._prepare = function () {
  36970. };
  36971. StopSoundAction.prototype.execute = function () {
  36972. if (this._sound !== undefined)
  36973. this._sound.stop();
  36974. };
  36975. StopSoundAction.prototype.serialize = function (parent) {
  36976. return _super.prototype._serialize.call(this, {
  36977. name: "StopSoundAction",
  36978. properties: [{ name: "sound", value: this._sound.name }]
  36979. }, parent);
  36980. };
  36981. return StopSoundAction;
  36982. }(BABYLON.Action));
  36983. BABYLON.StopSoundAction = StopSoundAction;
  36984. })(BABYLON || (BABYLON = {}));
  36985. //# sourceMappingURL=babylon.directActions.js.map
  36986. var BABYLON;
  36987. (function (BABYLON) {
  36988. var Geometry = (function () {
  36989. function Geometry(id, scene, vertexData, updatable, mesh) {
  36990. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36991. this._totalVertices = 0;
  36992. this._isDisposed = false;
  36993. this.id = id;
  36994. this._engine = scene.getEngine();
  36995. this._meshes = [];
  36996. this._scene = scene;
  36997. //Init vertex buffer cache
  36998. this._vertexBuffers = {};
  36999. this._indices = [];
  37000. // vertexData
  37001. if (vertexData) {
  37002. this.setAllVerticesData(vertexData, updatable);
  37003. }
  37004. else {
  37005. this._totalVertices = 0;
  37006. this._indices = [];
  37007. }
  37008. if (this._engine.getCaps().vertexArrayObject) {
  37009. this._vertexArrayObjects = {};
  37010. }
  37011. // applyToMesh
  37012. if (mesh) {
  37013. if (mesh instanceof BABYLON.LinesMesh) {
  37014. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37015. this.updateExtend();
  37016. }
  37017. this.applyToMesh(mesh);
  37018. mesh.computeWorldMatrix(true);
  37019. }
  37020. }
  37021. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37022. /**
  37023. * 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
  37024. * @returns The Bias Vector
  37025. */
  37026. get: function () {
  37027. return this._boundingBias;
  37028. },
  37029. set: function (value) {
  37030. if (this._boundingBias && this._boundingBias.equals(value)) {
  37031. return;
  37032. }
  37033. this._boundingBias = value.clone();
  37034. this.updateBoundingInfo(true, null);
  37035. },
  37036. enumerable: true,
  37037. configurable: true
  37038. });
  37039. Object.defineProperty(Geometry.prototype, "extend", {
  37040. get: function () {
  37041. return this._extend;
  37042. },
  37043. enumerable: true,
  37044. configurable: true
  37045. });
  37046. Geometry.prototype.getScene = function () {
  37047. return this._scene;
  37048. };
  37049. Geometry.prototype.getEngine = function () {
  37050. return this._engine;
  37051. };
  37052. Geometry.prototype.isReady = function () {
  37053. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37054. };
  37055. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37056. get: function () {
  37057. for (var index = 0; index < this._meshes.length; index++) {
  37058. if (!this._meshes[index].doNotSerialize) {
  37059. return false;
  37060. }
  37061. }
  37062. return true;
  37063. },
  37064. enumerable: true,
  37065. configurable: true
  37066. });
  37067. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37068. vertexData.applyToGeometry(this, updatable);
  37069. this.notifyUpdate();
  37070. };
  37071. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37072. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37073. this.setVerticesBuffer(buffer);
  37074. };
  37075. Geometry.prototype.setVerticesBuffer = function (buffer) {
  37076. var kind = buffer.getKind();
  37077. if (this._vertexBuffers[kind]) {
  37078. this._vertexBuffers[kind].dispose();
  37079. }
  37080. this._vertexBuffers[kind] = buffer;
  37081. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37082. var data = buffer.getData();
  37083. var stride = buffer.getStrideSize();
  37084. this._totalVertices = data.length / stride;
  37085. this.updateExtend(data, stride);
  37086. var meshes = this._meshes;
  37087. var numOfMeshes = meshes.length;
  37088. for (var index = 0; index < numOfMeshes; index++) {
  37089. var mesh = meshes[index];
  37090. mesh._resetPointsArrayCache();
  37091. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37092. mesh._createGlobalSubMesh();
  37093. mesh.computeWorldMatrix(true);
  37094. }
  37095. }
  37096. this.notifyUpdate(kind);
  37097. if (this._vertexArrayObjects) {
  37098. this._disposeVertexArrayObjects();
  37099. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37100. }
  37101. };
  37102. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37103. var vertexBuffer = this.getVertexBuffer(kind);
  37104. if (!vertexBuffer) {
  37105. return;
  37106. }
  37107. vertexBuffer.updateDirectly(data, offset);
  37108. this.notifyUpdate(kind);
  37109. };
  37110. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37111. var vertexBuffer = this.getVertexBuffer(kind);
  37112. if (!vertexBuffer) {
  37113. return;
  37114. }
  37115. vertexBuffer.update(data);
  37116. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37117. var stride = vertexBuffer.getStrideSize();
  37118. this._totalVertices = data.length / stride;
  37119. this.updateBoundingInfo(updateExtends, data);
  37120. }
  37121. this.notifyUpdate(kind);
  37122. };
  37123. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  37124. if (updateExtends) {
  37125. this.updateExtend(data);
  37126. }
  37127. var meshes = this._meshes;
  37128. var numOfMeshes = meshes.length;
  37129. for (var index = 0; index < numOfMeshes; index++) {
  37130. var mesh = meshes[index];
  37131. mesh._resetPointsArrayCache();
  37132. if (updateExtends) {
  37133. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37134. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37135. var subMesh = mesh.subMeshes[subIndex];
  37136. subMesh.refreshBoundingInfo();
  37137. }
  37138. }
  37139. }
  37140. };
  37141. Geometry.prototype._bind = function (effect, indexToBind) {
  37142. if (indexToBind === void 0) { indexToBind = undefined; }
  37143. if (indexToBind === undefined) {
  37144. indexToBind = this._indexBuffer;
  37145. }
  37146. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37147. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  37148. return;
  37149. }
  37150. // Using VAO
  37151. if (!this._vertexArrayObjects[effect.key]) {
  37152. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  37153. }
  37154. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37155. };
  37156. Geometry.prototype.getTotalVertices = function () {
  37157. if (!this.isReady()) {
  37158. return 0;
  37159. }
  37160. return this._totalVertices;
  37161. };
  37162. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  37163. var vertexBuffer = this.getVertexBuffer(kind);
  37164. if (!vertexBuffer) {
  37165. return null;
  37166. }
  37167. var orig = vertexBuffer.getData();
  37168. if (!copyWhenShared || this._meshes.length === 1) {
  37169. return orig;
  37170. }
  37171. else {
  37172. var len = orig.length;
  37173. var copy = [];
  37174. for (var i = 0; i < len; i++) {
  37175. copy.push(orig[i]);
  37176. }
  37177. return copy;
  37178. }
  37179. };
  37180. Geometry.prototype.getVertexBuffer = function (kind) {
  37181. if (!this.isReady()) {
  37182. return null;
  37183. }
  37184. return this._vertexBuffers[kind];
  37185. };
  37186. Geometry.prototype.getVertexBuffers = function () {
  37187. if (!this.isReady()) {
  37188. return null;
  37189. }
  37190. return this._vertexBuffers;
  37191. };
  37192. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37193. if (!this._vertexBuffers) {
  37194. if (this._delayInfo) {
  37195. return this._delayInfo.indexOf(kind) !== -1;
  37196. }
  37197. return false;
  37198. }
  37199. return this._vertexBuffers[kind] !== undefined;
  37200. };
  37201. Geometry.prototype.getVerticesDataKinds = function () {
  37202. var result = [];
  37203. var kind;
  37204. if (!this._vertexBuffers && this._delayInfo) {
  37205. for (kind in this._delayInfo) {
  37206. result.push(kind);
  37207. }
  37208. }
  37209. else {
  37210. for (kind in this._vertexBuffers) {
  37211. result.push(kind);
  37212. }
  37213. }
  37214. return result;
  37215. };
  37216. Geometry.prototype.setIndices = function (indices, totalVertices) {
  37217. if (this._indexBuffer) {
  37218. this._engine._releaseBuffer(this._indexBuffer);
  37219. }
  37220. this._disposeVertexArrayObjects();
  37221. this._indices = indices;
  37222. if (this._meshes.length !== 0 && this._indices) {
  37223. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37224. }
  37225. if (totalVertices !== undefined) {
  37226. this._totalVertices = totalVertices;
  37227. }
  37228. var meshes = this._meshes;
  37229. var numOfMeshes = meshes.length;
  37230. for (var index = 0; index < numOfMeshes; index++) {
  37231. meshes[index]._createGlobalSubMesh();
  37232. }
  37233. this.notifyUpdate();
  37234. };
  37235. Geometry.prototype.getTotalIndices = function () {
  37236. if (!this.isReady()) {
  37237. return 0;
  37238. }
  37239. return this._indices.length;
  37240. };
  37241. Geometry.prototype.getIndices = function (copyWhenShared) {
  37242. if (!this.isReady()) {
  37243. return null;
  37244. }
  37245. var orig = this._indices;
  37246. if (!copyWhenShared || this._meshes.length === 1) {
  37247. return orig;
  37248. }
  37249. else {
  37250. var len = orig.length;
  37251. var copy = [];
  37252. for (var i = 0; i < len; i++) {
  37253. copy.push(orig[i]);
  37254. }
  37255. return copy;
  37256. }
  37257. };
  37258. Geometry.prototype.getIndexBuffer = function () {
  37259. if (!this.isReady()) {
  37260. return null;
  37261. }
  37262. return this._indexBuffer;
  37263. };
  37264. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37265. var meshes = this._meshes;
  37266. var index = meshes.indexOf(mesh);
  37267. if (index === -1) {
  37268. return;
  37269. }
  37270. meshes.splice(index, 1);
  37271. mesh._geometry = null;
  37272. if (meshes.length === 0 && shouldDispose) {
  37273. this.dispose();
  37274. }
  37275. };
  37276. Geometry.prototype.applyToMesh = function (mesh) {
  37277. if (mesh._geometry === this) {
  37278. return;
  37279. }
  37280. var previousGeometry = mesh._geometry;
  37281. if (previousGeometry) {
  37282. previousGeometry.releaseForMesh(mesh);
  37283. }
  37284. var meshes = this._meshes;
  37285. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37286. mesh._geometry = this;
  37287. this._scene.pushGeometry(this);
  37288. meshes.push(mesh);
  37289. if (this.isReady()) {
  37290. this._applyToMesh(mesh);
  37291. }
  37292. else {
  37293. mesh._boundingInfo = this._boundingInfo;
  37294. }
  37295. };
  37296. Geometry.prototype.updateExtend = function (data, stride) {
  37297. if (data === void 0) { data = null; }
  37298. if (!data) {
  37299. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  37300. }
  37301. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  37302. };
  37303. Geometry.prototype._applyToMesh = function (mesh) {
  37304. var numOfMeshes = this._meshes.length;
  37305. // vertexBuffers
  37306. for (var kind in this._vertexBuffers) {
  37307. if (numOfMeshes === 1) {
  37308. this._vertexBuffers[kind].create();
  37309. }
  37310. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  37311. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37312. mesh._resetPointsArrayCache();
  37313. if (!this._extend) {
  37314. this.updateExtend(this._vertexBuffers[kind].getData());
  37315. }
  37316. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37317. mesh._createGlobalSubMesh();
  37318. //bounding info was just created again, world matrix should be applied again.
  37319. mesh._updateBoundingInfo();
  37320. }
  37321. }
  37322. // indexBuffer
  37323. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37324. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37325. }
  37326. if (this._indexBuffer) {
  37327. this._indexBuffer.references = numOfMeshes;
  37328. }
  37329. };
  37330. Geometry.prototype.notifyUpdate = function (kind) {
  37331. if (this.onGeometryUpdated) {
  37332. this.onGeometryUpdated(this, kind);
  37333. }
  37334. };
  37335. Geometry.prototype.load = function (scene, onLoaded) {
  37336. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37337. return;
  37338. }
  37339. if (this.isReady()) {
  37340. if (onLoaded) {
  37341. onLoaded();
  37342. }
  37343. return;
  37344. }
  37345. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37346. this._queueLoad(scene, onLoaded);
  37347. };
  37348. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37349. var _this = this;
  37350. scene._addPendingData(this);
  37351. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  37352. _this._delayLoadingFunction(JSON.parse(data), _this);
  37353. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37354. _this._delayInfo = [];
  37355. scene._removePendingData(_this);
  37356. var meshes = _this._meshes;
  37357. var numOfMeshes = meshes.length;
  37358. for (var index = 0; index < numOfMeshes; index++) {
  37359. _this._applyToMesh(meshes[index]);
  37360. }
  37361. if (onLoaded) {
  37362. onLoaded();
  37363. }
  37364. }, function () { }, scene.database);
  37365. };
  37366. /**
  37367. * Invert the geometry to move from a right handed system to a left handed one.
  37368. */
  37369. Geometry.prototype.toLeftHanded = function () {
  37370. // Flip faces
  37371. var tIndices = this.getIndices(false);
  37372. if (tIndices != null && tIndices.length > 0) {
  37373. for (var i = 0; i < tIndices.length; i += 3) {
  37374. var tTemp = tIndices[i + 0];
  37375. tIndices[i + 0] = tIndices[i + 2];
  37376. tIndices[i + 2] = tTemp;
  37377. }
  37378. this.setIndices(tIndices);
  37379. }
  37380. // Negate position.z
  37381. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37382. if (tPositions != null && tPositions.length > 0) {
  37383. for (var i = 0; i < tPositions.length; i += 3) {
  37384. tPositions[i + 2] = -tPositions[i + 2];
  37385. }
  37386. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37387. }
  37388. // Negate normal.z
  37389. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37390. if (tNormals != null && tNormals.length > 0) {
  37391. for (var i = 0; i < tNormals.length; i += 3) {
  37392. tNormals[i + 2] = -tNormals[i + 2];
  37393. }
  37394. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37395. }
  37396. };
  37397. Geometry.prototype.isDisposed = function () {
  37398. return this._isDisposed;
  37399. };
  37400. Geometry.prototype._disposeVertexArrayObjects = function () {
  37401. if (this._vertexArrayObjects) {
  37402. for (var kind in this._vertexArrayObjects) {
  37403. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37404. }
  37405. this._vertexArrayObjects = {};
  37406. }
  37407. };
  37408. Geometry.prototype.dispose = function () {
  37409. var meshes = this._meshes;
  37410. var numOfMeshes = meshes.length;
  37411. var index;
  37412. for (index = 0; index < numOfMeshes; index++) {
  37413. this.releaseForMesh(meshes[index]);
  37414. }
  37415. this._meshes = [];
  37416. this._disposeVertexArrayObjects();
  37417. for (var kind in this._vertexBuffers) {
  37418. this._vertexBuffers[kind].dispose();
  37419. }
  37420. this._vertexBuffers = {};
  37421. this._totalVertices = 0;
  37422. if (this._indexBuffer) {
  37423. this._engine._releaseBuffer(this._indexBuffer);
  37424. }
  37425. this._indexBuffer = null;
  37426. this._indices = [];
  37427. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37428. this.delayLoadingFile = null;
  37429. this._delayLoadingFunction = null;
  37430. this._delayInfo = [];
  37431. this._boundingInfo = null;
  37432. this._scene.removeGeometry(this);
  37433. this._isDisposed = true;
  37434. };
  37435. Geometry.prototype.copy = function (id) {
  37436. var vertexData = new BABYLON.VertexData();
  37437. vertexData.indices = [];
  37438. var indices = this.getIndices();
  37439. for (var index = 0; index < indices.length; index++) {
  37440. vertexData.indices.push(indices[index]);
  37441. }
  37442. var updatable = false;
  37443. var stopChecking = false;
  37444. var kind;
  37445. for (kind in this._vertexBuffers) {
  37446. // using slice() to make a copy of the array and not just reference it
  37447. var data = this.getVerticesData(kind);
  37448. if (data instanceof Float32Array) {
  37449. vertexData.set(new Float32Array(data), kind);
  37450. }
  37451. else {
  37452. vertexData.set(data.slice(0), kind);
  37453. }
  37454. if (!stopChecking) {
  37455. updatable = this.getVertexBuffer(kind).isUpdatable();
  37456. stopChecking = !updatable;
  37457. }
  37458. }
  37459. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  37460. geometry.delayLoadState = this.delayLoadState;
  37461. geometry.delayLoadingFile = this.delayLoadingFile;
  37462. geometry._delayLoadingFunction = this._delayLoadingFunction;
  37463. for (kind in this._delayInfo) {
  37464. geometry._delayInfo = geometry._delayInfo || [];
  37465. geometry._delayInfo.push(kind);
  37466. }
  37467. // Bounding info
  37468. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37469. return geometry;
  37470. };
  37471. Geometry.prototype.serialize = function () {
  37472. var serializationObject = {};
  37473. serializationObject.id = this.id;
  37474. if (BABYLON.Tags.HasTags(this)) {
  37475. serializationObject.tags = BABYLON.Tags.GetTags(this);
  37476. }
  37477. return serializationObject;
  37478. };
  37479. Geometry.prototype.serializeVerticeData = function () {
  37480. var serializationObject = this.serialize();
  37481. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37482. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37483. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  37484. serializationObject.positions._updatable = true;
  37485. }
  37486. }
  37487. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37488. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37489. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  37490. serializationObject.normals._updatable = true;
  37491. }
  37492. }
  37493. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37494. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37495. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  37496. serializationObject.uvs._updatable = true;
  37497. }
  37498. }
  37499. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37500. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  37501. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  37502. serializationObject.uv2s._updatable = true;
  37503. }
  37504. }
  37505. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37506. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  37507. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  37508. serializationObject.uv3s._updatable = true;
  37509. }
  37510. }
  37511. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37512. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  37513. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  37514. serializationObject.uv4s._updatable = true;
  37515. }
  37516. }
  37517. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37518. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  37519. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  37520. serializationObject.uv5s._updatable = true;
  37521. }
  37522. }
  37523. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37524. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  37525. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  37526. serializationObject.uv6s._updatable = true;
  37527. }
  37528. }
  37529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37530. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37531. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  37532. serializationObject.colors._updatable = true;
  37533. }
  37534. }
  37535. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37536. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37537. serializationObject.matricesIndices._isExpanded = true;
  37538. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  37539. serializationObject.matricesIndices._updatable = true;
  37540. }
  37541. }
  37542. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37543. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  37544. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  37545. serializationObject.matricesWeights._updatable = true;
  37546. }
  37547. }
  37548. serializationObject.indices = this.getIndices();
  37549. return serializationObject;
  37550. };
  37551. // Statics
  37552. Geometry.ExtractFromMesh = function (mesh, id) {
  37553. var geometry = mesh._geometry;
  37554. if (!geometry) {
  37555. return null;
  37556. }
  37557. return geometry.copy(id);
  37558. };
  37559. /**
  37560. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  37561. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  37562. * Be aware Math.random() could cause collisions, but:
  37563. * "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"
  37564. */
  37565. Geometry.RandomId = function () {
  37566. return BABYLON.Tools.RandomId();
  37567. };
  37568. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  37569. var scene = mesh.getScene();
  37570. // Geometry
  37571. var geometryId = parsedGeometry.geometryId;
  37572. if (geometryId) {
  37573. var geometry = scene.getGeometryByID(geometryId);
  37574. if (geometry) {
  37575. geometry.applyToMesh(mesh);
  37576. }
  37577. }
  37578. else if (parsedGeometry instanceof ArrayBuffer) {
  37579. var binaryInfo = mesh._binaryInfo;
  37580. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  37581. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  37582. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  37583. }
  37584. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  37585. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  37586. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  37587. }
  37588. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  37589. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  37590. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  37591. }
  37592. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  37593. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  37594. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  37595. }
  37596. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  37597. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  37598. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  37599. }
  37600. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  37601. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  37602. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  37603. }
  37604. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  37605. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  37606. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  37607. }
  37608. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  37609. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  37610. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  37611. }
  37612. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  37613. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  37614. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  37615. }
  37616. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  37617. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  37618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  37619. }
  37620. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  37621. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  37622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  37623. }
  37624. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  37625. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  37626. mesh.setIndices(indicesData);
  37627. }
  37628. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  37629. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  37630. mesh.subMeshes = [];
  37631. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  37632. var materialIndex = subMeshesData[(i * 5) + 0];
  37633. var verticesStart = subMeshesData[(i * 5) + 1];
  37634. var verticesCount = subMeshesData[(i * 5) + 2];
  37635. var indexStart = subMeshesData[(i * 5) + 3];
  37636. var indexCount = subMeshesData[(i * 5) + 4];
  37637. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  37638. }
  37639. }
  37640. }
  37641. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  37642. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  37643. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  37644. if (parsedGeometry.uvs) {
  37645. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  37646. }
  37647. if (parsedGeometry.uvs2) {
  37648. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  37649. }
  37650. if (parsedGeometry.uvs3) {
  37651. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  37652. }
  37653. if (parsedGeometry.uvs4) {
  37654. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  37655. }
  37656. if (parsedGeometry.uvs5) {
  37657. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  37658. }
  37659. if (parsedGeometry.uvs6) {
  37660. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  37661. }
  37662. if (parsedGeometry.colors) {
  37663. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  37664. }
  37665. if (parsedGeometry.matricesIndices) {
  37666. if (!parsedGeometry.matricesIndices._isExpanded) {
  37667. var floatIndices = [];
  37668. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  37669. var matricesIndex = parsedGeometry.matricesIndices[i];
  37670. floatIndices.push(matricesIndex & 0x000000FF);
  37671. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37672. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37673. floatIndices.push(matricesIndex >> 24);
  37674. }
  37675. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  37676. }
  37677. else {
  37678. delete parsedGeometry.matricesIndices._isExpanded;
  37679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  37680. }
  37681. }
  37682. if (parsedGeometry.matricesIndicesExtra) {
  37683. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  37684. var floatIndices = [];
  37685. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  37686. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  37687. floatIndices.push(matricesIndex & 0x000000FF);
  37688. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37689. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37690. floatIndices.push(matricesIndex >> 24);
  37691. }
  37692. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  37693. }
  37694. else {
  37695. delete parsedGeometry.matricesIndices._isExpanded;
  37696. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  37697. }
  37698. }
  37699. if (parsedGeometry.matricesWeights) {
  37700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  37701. }
  37702. if (parsedGeometry.matricesWeightsExtra) {
  37703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  37704. }
  37705. mesh.setIndices(parsedGeometry.indices);
  37706. }
  37707. // SubMeshes
  37708. if (parsedGeometry.subMeshes) {
  37709. mesh.subMeshes = [];
  37710. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  37711. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  37712. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  37713. }
  37714. }
  37715. // Flat shading
  37716. if (mesh._shouldGenerateFlatShading) {
  37717. mesh.convertToFlatShadedMesh();
  37718. delete mesh._shouldGenerateFlatShading;
  37719. }
  37720. // Update
  37721. mesh.computeWorldMatrix(true);
  37722. // Octree
  37723. if (scene['_selectionOctree']) {
  37724. scene['_selectionOctree'].addMesh(mesh);
  37725. }
  37726. };
  37727. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37728. if (scene.getGeometryByID(parsedVertexData.id)) {
  37729. return null; // null since geometry could be something else than a box...
  37730. }
  37731. var geometry = new Geometry(parsedVertexData.id, scene);
  37732. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37733. if (parsedVertexData.delayLoadingFile) {
  37734. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37735. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37736. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37737. geometry._delayInfo = [];
  37738. if (parsedVertexData.hasUVs) {
  37739. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37740. }
  37741. if (parsedVertexData.hasUVs2) {
  37742. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37743. }
  37744. if (parsedVertexData.hasUVs3) {
  37745. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37746. }
  37747. if (parsedVertexData.hasUVs4) {
  37748. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  37749. }
  37750. if (parsedVertexData.hasUVs5) {
  37751. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  37752. }
  37753. if (parsedVertexData.hasUVs6) {
  37754. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  37755. }
  37756. if (parsedVertexData.hasColors) {
  37757. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  37758. }
  37759. if (parsedVertexData.hasMatricesIndices) {
  37760. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37761. }
  37762. if (parsedVertexData.hasMatricesWeights) {
  37763. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37764. }
  37765. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  37766. }
  37767. else {
  37768. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  37769. }
  37770. scene.pushGeometry(geometry, true);
  37771. return geometry;
  37772. };
  37773. return Geometry;
  37774. }());
  37775. BABYLON.Geometry = Geometry;
  37776. /////// Primitives //////////////////////////////////////////////
  37777. (function (Geometry) {
  37778. var Primitives;
  37779. (function (Primitives) {
  37780. /// Abstract class
  37781. var _Primitive = (function (_super) {
  37782. __extends(_Primitive, _super);
  37783. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  37784. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  37785. _this._canBeRegenerated = _canBeRegenerated;
  37786. _this._beingRegenerated = true;
  37787. _this.regenerate();
  37788. _this._beingRegenerated = false;
  37789. return _this;
  37790. }
  37791. _Primitive.prototype.canBeRegenerated = function () {
  37792. return this._canBeRegenerated;
  37793. };
  37794. _Primitive.prototype.regenerate = function () {
  37795. if (!this._canBeRegenerated) {
  37796. return;
  37797. }
  37798. this._beingRegenerated = true;
  37799. this.setAllVerticesData(this._regenerateVertexData(), false);
  37800. this._beingRegenerated = false;
  37801. };
  37802. _Primitive.prototype.asNewGeometry = function (id) {
  37803. return _super.prototype.copy.call(this, id);
  37804. };
  37805. // overrides
  37806. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  37807. if (!this._beingRegenerated) {
  37808. return;
  37809. }
  37810. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37811. };
  37812. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  37813. if (!this._beingRegenerated) {
  37814. return;
  37815. }
  37816. _super.prototype.setVerticesData.call(this, kind, data, false);
  37817. };
  37818. // to override
  37819. // protected
  37820. _Primitive.prototype._regenerateVertexData = function () {
  37821. throw new Error("Abstract method");
  37822. };
  37823. _Primitive.prototype.copy = function (id) {
  37824. throw new Error("Must be overriden in sub-classes.");
  37825. };
  37826. _Primitive.prototype.serialize = function () {
  37827. var serializationObject = _super.prototype.serialize.call(this);
  37828. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37829. return serializationObject;
  37830. };
  37831. return _Primitive;
  37832. }(Geometry));
  37833. Primitives._Primitive = _Primitive;
  37834. var Ribbon = (function (_super) {
  37835. __extends(Ribbon, _super);
  37836. // Members
  37837. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  37838. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37839. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37840. _this.pathArray = pathArray;
  37841. _this.closeArray = closeArray;
  37842. _this.closePath = closePath;
  37843. _this.offset = offset;
  37844. _this.side = side;
  37845. return _this;
  37846. }
  37847. Ribbon.prototype._regenerateVertexData = function () {
  37848. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37849. };
  37850. Ribbon.prototype.copy = function (id) {
  37851. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  37852. };
  37853. return Ribbon;
  37854. }(_Primitive));
  37855. Primitives.Ribbon = Ribbon;
  37856. var Box = (function (_super) {
  37857. __extends(Box, _super);
  37858. // Members
  37859. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  37860. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37861. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37862. _this.size = size;
  37863. _this.side = side;
  37864. return _this;
  37865. }
  37866. Box.prototype._regenerateVertexData = function () {
  37867. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  37868. };
  37869. Box.prototype.copy = function (id) {
  37870. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37871. };
  37872. Box.prototype.serialize = function () {
  37873. var serializationObject = _super.prototype.serialize.call(this);
  37874. serializationObject.size = this.size;
  37875. return serializationObject;
  37876. };
  37877. Box.Parse = function (parsedBox, scene) {
  37878. if (scene.getGeometryByID(parsedBox.id)) {
  37879. return null; // null since geometry could be something else than a box...
  37880. }
  37881. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  37882. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  37883. scene.pushGeometry(box, true);
  37884. return box;
  37885. };
  37886. return Box;
  37887. }(_Primitive));
  37888. Primitives.Box = Box;
  37889. var Sphere = (function (_super) {
  37890. __extends(Sphere, _super);
  37891. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  37892. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37893. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37894. _this.segments = segments;
  37895. _this.diameter = diameter;
  37896. _this.side = side;
  37897. return _this;
  37898. }
  37899. Sphere.prototype._regenerateVertexData = function () {
  37900. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37901. };
  37902. Sphere.prototype.copy = function (id) {
  37903. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37904. };
  37905. Sphere.prototype.serialize = function () {
  37906. var serializationObject = _super.prototype.serialize.call(this);
  37907. serializationObject.segments = this.segments;
  37908. serializationObject.diameter = this.diameter;
  37909. return serializationObject;
  37910. };
  37911. Sphere.Parse = function (parsedSphere, scene) {
  37912. if (scene.getGeometryByID(parsedSphere.id)) {
  37913. return null; // null since geometry could be something else than a sphere...
  37914. }
  37915. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37916. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37917. scene.pushGeometry(sphere, true);
  37918. return sphere;
  37919. };
  37920. return Sphere;
  37921. }(_Primitive));
  37922. Primitives.Sphere = Sphere;
  37923. var Disc = (function (_super) {
  37924. __extends(Disc, _super);
  37925. // Members
  37926. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37928. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37929. _this.radius = radius;
  37930. _this.tessellation = tessellation;
  37931. _this.side = side;
  37932. return _this;
  37933. }
  37934. Disc.prototype._regenerateVertexData = function () {
  37935. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37936. };
  37937. Disc.prototype.copy = function (id) {
  37938. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37939. };
  37940. return Disc;
  37941. }(_Primitive));
  37942. Primitives.Disc = Disc;
  37943. var Cylinder = (function (_super) {
  37944. __extends(Cylinder, _super);
  37945. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37946. if (subdivisions === void 0) { subdivisions = 1; }
  37947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37948. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37949. _this.height = height;
  37950. _this.diameterTop = diameterTop;
  37951. _this.diameterBottom = diameterBottom;
  37952. _this.tessellation = tessellation;
  37953. _this.subdivisions = subdivisions;
  37954. _this.side = side;
  37955. return _this;
  37956. }
  37957. Cylinder.prototype._regenerateVertexData = function () {
  37958. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37959. };
  37960. Cylinder.prototype.copy = function (id) {
  37961. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37962. };
  37963. Cylinder.prototype.serialize = function () {
  37964. var serializationObject = _super.prototype.serialize.call(this);
  37965. serializationObject.height = this.height;
  37966. serializationObject.diameterTop = this.diameterTop;
  37967. serializationObject.diameterBottom = this.diameterBottom;
  37968. serializationObject.tessellation = this.tessellation;
  37969. return serializationObject;
  37970. };
  37971. Cylinder.Parse = function (parsedCylinder, scene) {
  37972. if (scene.getGeometryByID(parsedCylinder.id)) {
  37973. return null; // null since geometry could be something else than a cylinder...
  37974. }
  37975. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37976. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37977. scene.pushGeometry(cylinder, true);
  37978. return cylinder;
  37979. };
  37980. return Cylinder;
  37981. }(_Primitive));
  37982. Primitives.Cylinder = Cylinder;
  37983. var Torus = (function (_super) {
  37984. __extends(Torus, _super);
  37985. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37986. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37987. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37988. _this.diameter = diameter;
  37989. _this.thickness = thickness;
  37990. _this.tessellation = tessellation;
  37991. _this.side = side;
  37992. return _this;
  37993. }
  37994. Torus.prototype._regenerateVertexData = function () {
  37995. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37996. };
  37997. Torus.prototype.copy = function (id) {
  37998. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37999. };
  38000. Torus.prototype.serialize = function () {
  38001. var serializationObject = _super.prototype.serialize.call(this);
  38002. serializationObject.diameter = this.diameter;
  38003. serializationObject.thickness = this.thickness;
  38004. serializationObject.tessellation = this.tessellation;
  38005. return serializationObject;
  38006. };
  38007. Torus.Parse = function (parsedTorus, scene) {
  38008. if (scene.getGeometryByID(parsedTorus.id)) {
  38009. return null; // null since geometry could be something else than a torus...
  38010. }
  38011. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  38012. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  38013. scene.pushGeometry(torus, true);
  38014. return torus;
  38015. };
  38016. return Torus;
  38017. }(_Primitive));
  38018. Primitives.Torus = Torus;
  38019. var Ground = (function (_super) {
  38020. __extends(Ground, _super);
  38021. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  38022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38023. _this.width = width;
  38024. _this.height = height;
  38025. _this.subdivisions = subdivisions;
  38026. return _this;
  38027. }
  38028. Ground.prototype._regenerateVertexData = function () {
  38029. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38030. };
  38031. Ground.prototype.copy = function (id) {
  38032. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38033. };
  38034. Ground.prototype.serialize = function () {
  38035. var serializationObject = _super.prototype.serialize.call(this);
  38036. serializationObject.width = this.width;
  38037. serializationObject.height = this.height;
  38038. serializationObject.subdivisions = this.subdivisions;
  38039. return serializationObject;
  38040. };
  38041. Ground.Parse = function (parsedGround, scene) {
  38042. if (scene.getGeometryByID(parsedGround.id)) {
  38043. return null; // null since geometry could be something else than a ground...
  38044. }
  38045. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  38046. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  38047. scene.pushGeometry(ground, true);
  38048. return ground;
  38049. };
  38050. return Ground;
  38051. }(_Primitive));
  38052. Primitives.Ground = Ground;
  38053. var TiledGround = (function (_super) {
  38054. __extends(TiledGround, _super);
  38055. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  38056. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38057. _this.xmin = xmin;
  38058. _this.zmin = zmin;
  38059. _this.xmax = xmax;
  38060. _this.zmax = zmax;
  38061. _this.subdivisions = subdivisions;
  38062. _this.precision = precision;
  38063. return _this;
  38064. }
  38065. TiledGround.prototype._regenerateVertexData = function () {
  38066. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  38067. };
  38068. TiledGround.prototype.copy = function (id) {
  38069. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  38070. };
  38071. return TiledGround;
  38072. }(_Primitive));
  38073. Primitives.TiledGround = TiledGround;
  38074. var Plane = (function (_super) {
  38075. __extends(Plane, _super);
  38076. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  38077. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38078. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38079. _this.size = size;
  38080. _this.side = side;
  38081. return _this;
  38082. }
  38083. Plane.prototype._regenerateVertexData = function () {
  38084. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  38085. };
  38086. Plane.prototype.copy = function (id) {
  38087. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38088. };
  38089. Plane.prototype.serialize = function () {
  38090. var serializationObject = _super.prototype.serialize.call(this);
  38091. serializationObject.size = this.size;
  38092. return serializationObject;
  38093. };
  38094. Plane.Parse = function (parsedPlane, scene) {
  38095. if (scene.getGeometryByID(parsedPlane.id)) {
  38096. return null; // null since geometry could be something else than a ground...
  38097. }
  38098. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  38099. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  38100. scene.pushGeometry(plane, true);
  38101. return plane;
  38102. };
  38103. return Plane;
  38104. }(_Primitive));
  38105. Primitives.Plane = Plane;
  38106. var TorusKnot = (function (_super) {
  38107. __extends(TorusKnot, _super);
  38108. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  38109. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38110. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38111. _this.radius = radius;
  38112. _this.tube = tube;
  38113. _this.radialSegments = radialSegments;
  38114. _this.tubularSegments = tubularSegments;
  38115. _this.p = p;
  38116. _this.q = q;
  38117. _this.side = side;
  38118. return _this;
  38119. }
  38120. TorusKnot.prototype._regenerateVertexData = function () {
  38121. 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 });
  38122. };
  38123. TorusKnot.prototype.copy = function (id) {
  38124. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  38125. };
  38126. TorusKnot.prototype.serialize = function () {
  38127. var serializationObject = _super.prototype.serialize.call(this);
  38128. serializationObject.radius = this.radius;
  38129. serializationObject.tube = this.tube;
  38130. serializationObject.radialSegments = this.radialSegments;
  38131. serializationObject.tubularSegments = this.tubularSegments;
  38132. serializationObject.p = this.p;
  38133. serializationObject.q = this.q;
  38134. return serializationObject;
  38135. };
  38136. ;
  38137. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  38138. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  38139. return null; // null since geometry could be something else than a ground...
  38140. }
  38141. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  38142. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  38143. scene.pushGeometry(torusKnot, true);
  38144. return torusKnot;
  38145. };
  38146. return TorusKnot;
  38147. }(_Primitive));
  38148. Primitives.TorusKnot = TorusKnot;
  38149. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  38150. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  38151. })(BABYLON || (BABYLON = {}));
  38152. //# sourceMappingURL=babylon.geometry.js.map
  38153. var BABYLON;
  38154. (function (BABYLON) {
  38155. var GroundMesh = (function (_super) {
  38156. __extends(GroundMesh, _super);
  38157. function GroundMesh(name, scene) {
  38158. var _this = _super.call(this, name, scene) || this;
  38159. _this.generateOctree = false;
  38160. _this._worldInverse = new BABYLON.Matrix();
  38161. return _this;
  38162. }
  38163. GroundMesh.prototype.getClassName = function () {
  38164. return "GroundMesh";
  38165. };
  38166. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  38167. get: function () {
  38168. return Math.min(this._subdivisionsX, this._subdivisionsY);
  38169. },
  38170. enumerable: true,
  38171. configurable: true
  38172. });
  38173. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  38174. get: function () {
  38175. return this._subdivisionsX;
  38176. },
  38177. enumerable: true,
  38178. configurable: true
  38179. });
  38180. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  38181. get: function () {
  38182. return this._subdivisionsY;
  38183. },
  38184. enumerable: true,
  38185. configurable: true
  38186. });
  38187. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  38188. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  38189. this._subdivisionsX = chunksCount;
  38190. this._subdivisionsY = chunksCount;
  38191. this.subdivide(chunksCount);
  38192. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  38193. };
  38194. /**
  38195. * Returns a height (y) value in the Worl system :
  38196. * the ground altitude at the coordinates (x, z) expressed in the World system.
  38197. * Returns the ground y position if (x, z) are outside the ground surface.
  38198. */
  38199. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  38200. var world = this.getWorldMatrix();
  38201. var invMat = BABYLON.Tmp.Matrix[5];
  38202. world.invertToRef(invMat);
  38203. var tmpVect = BABYLON.Tmp.Vector3[8];
  38204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  38205. x = tmpVect.x;
  38206. z = tmpVect.z;
  38207. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38208. return this.position.y;
  38209. }
  38210. if (!this._heightQuads || this._heightQuads.length == 0) {
  38211. this._initHeightQuads();
  38212. this._computeHeightQuads();
  38213. }
  38214. var facet = this._getFacetAt(x, z);
  38215. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  38216. // return y in the World system
  38217. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  38218. return tmpVect.y;
  38219. };
  38220. /**
  38221. * Returns a normalized vector (Vector3) orthogonal to the ground
  38222. * at the ground coordinates (x, z) expressed in the World system.
  38223. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  38224. */
  38225. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  38226. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  38227. this.getNormalAtCoordinatesToRef(x, z, normal);
  38228. return normal;
  38229. };
  38230. /**
  38231. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  38232. * at the ground coordinates (x, z) expressed in the World system.
  38233. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  38234. * Returns the GroundMesh.
  38235. */
  38236. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  38237. var world = this.getWorldMatrix();
  38238. var tmpMat = BABYLON.Tmp.Matrix[5];
  38239. world.invertToRef(tmpMat);
  38240. var tmpVect = BABYLON.Tmp.Vector3[8];
  38241. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  38242. x = tmpVect.x;
  38243. z = tmpVect.z;
  38244. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38245. return this;
  38246. }
  38247. if (!this._heightQuads || this._heightQuads.length == 0) {
  38248. this._initHeightQuads();
  38249. this._computeHeightQuads();
  38250. }
  38251. var facet = this._getFacetAt(x, z);
  38252. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  38253. return this;
  38254. };
  38255. /**
  38256. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  38257. * if the ground has been updated.
  38258. * This can be used in the render loop
  38259. */
  38260. GroundMesh.prototype.updateCoordinateHeights = function () {
  38261. if (!this._heightQuads || this._heightQuads.length == 0) {
  38262. this._initHeightQuads();
  38263. }
  38264. this._computeHeightQuads();
  38265. };
  38266. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  38267. GroundMesh.prototype._getFacetAt = function (x, z) {
  38268. // retrieve col and row from x, z coordinates in the ground local system
  38269. var subdivisionsX = this._subdivisionsX;
  38270. var subdivisionsY = this._subdivisionsY;
  38271. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  38272. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  38273. var quad = this._heightQuads[row * this._subdivisionsX + col];
  38274. var facet;
  38275. if (z < quad.slope.x * x + quad.slope.y) {
  38276. facet = quad.facet1;
  38277. }
  38278. else {
  38279. facet = quad.facet2;
  38280. }
  38281. return facet;
  38282. };
  38283. // Creates and populates the heightMap array with "facet" elements :
  38284. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  38285. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38286. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38287. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38288. GroundMesh.prototype._initHeightQuads = function () {
  38289. var subdivisionsX = this._subdivisionsX;
  38290. var subdivisionsY = this._subdivisionsY;
  38291. this._heightQuads = new Array();
  38292. for (var row = 0; row < subdivisionsY; row++) {
  38293. for (var col = 0; col < subdivisionsX; col++) {
  38294. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  38295. this._heightQuads[row * subdivisionsX + col] = quad;
  38296. }
  38297. }
  38298. };
  38299. // Compute each quad element values and update the the heightMap array :
  38300. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38301. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38302. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38303. GroundMesh.prototype._computeHeightQuads = function () {
  38304. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38305. var v1 = BABYLON.Tmp.Vector3[3];
  38306. var v2 = BABYLON.Tmp.Vector3[2];
  38307. var v3 = BABYLON.Tmp.Vector3[1];
  38308. var v4 = BABYLON.Tmp.Vector3[0];
  38309. var v1v2 = BABYLON.Tmp.Vector3[4];
  38310. var v1v3 = BABYLON.Tmp.Vector3[5];
  38311. var v1v4 = BABYLON.Tmp.Vector3[6];
  38312. var norm1 = BABYLON.Tmp.Vector3[7];
  38313. var norm2 = BABYLON.Tmp.Vector3[8];
  38314. var i = 0;
  38315. var j = 0;
  38316. var k = 0;
  38317. var cd = 0; // 2D slope coefficient : z = cd * x + h
  38318. var h = 0;
  38319. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  38320. var d2 = 0;
  38321. var subdivisionsX = this._subdivisionsX;
  38322. var subdivisionsY = this._subdivisionsY;
  38323. for (var row = 0; row < subdivisionsY; row++) {
  38324. for (var col = 0; col < subdivisionsX; col++) {
  38325. i = col * 3;
  38326. j = row * (subdivisionsX + 1) * 3;
  38327. k = (row + 1) * (subdivisionsX + 1) * 3;
  38328. v1.x = positions[j + i];
  38329. v1.y = positions[j + i + 1];
  38330. v1.z = positions[j + i + 2];
  38331. v2.x = positions[j + i + 3];
  38332. v2.y = positions[j + i + 4];
  38333. v2.z = positions[j + i + 5];
  38334. v3.x = positions[k + i];
  38335. v3.y = positions[k + i + 1];
  38336. v3.z = positions[k + i + 2];
  38337. v4.x = positions[k + i + 3];
  38338. v4.y = positions[k + i + 4];
  38339. v4.z = positions[k + i + 5];
  38340. // 2D slope V1V4
  38341. cd = (v4.z - v1.z) / (v4.x - v1.x);
  38342. h = v1.z - cd * v1.x; // v1 belongs to the slope
  38343. // facet equations :
  38344. // we compute each facet normal vector
  38345. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  38346. // we compute the value d by applying the equation to v1 which belongs to the plane
  38347. // then we store the facet equation in a Vector4
  38348. v2.subtractToRef(v1, v1v2);
  38349. v3.subtractToRef(v1, v1v3);
  38350. v4.subtractToRef(v1, v1v4);
  38351. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  38352. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  38353. norm1.normalize();
  38354. norm2.normalize();
  38355. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  38356. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  38357. var quad = this._heightQuads[row * subdivisionsX + col];
  38358. quad.slope.copyFromFloats(cd, h);
  38359. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  38360. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  38361. }
  38362. }
  38363. };
  38364. return GroundMesh;
  38365. }(BABYLON.Mesh));
  38366. BABYLON.GroundMesh = GroundMesh;
  38367. })(BABYLON || (BABYLON = {}));
  38368. //# sourceMappingURL=babylon.groundMesh.js.map
  38369. var BABYLON;
  38370. (function (BABYLON) {
  38371. var LinesMesh = (function (_super) {
  38372. __extends(LinesMesh, _super);
  38373. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  38374. if (parent === void 0) { parent = null; }
  38375. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38376. _this.color = new BABYLON.Color3(1, 1, 1);
  38377. _this.alpha = 1;
  38378. _this._positionBuffer = {};
  38379. if (source) {
  38380. _this.color = source.color.clone();
  38381. _this.alpha = source.alpha;
  38382. }
  38383. _this._intersectionThreshold = 0.1;
  38384. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  38385. attributes: [BABYLON.VertexBuffer.PositionKind],
  38386. uniforms: ["worldViewProjection", "color"],
  38387. needAlphaBlending: true
  38388. });
  38389. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  38390. return _this;
  38391. }
  38392. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38393. /**
  38394. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38395. * This margin is expressed in world space coordinates, so its value may vary.
  38396. * Default value is 0.1
  38397. * @returns the intersection Threshold value.
  38398. */
  38399. get: function () {
  38400. return this._intersectionThreshold;
  38401. },
  38402. /**
  38403. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38404. * This margin is expressed in world space coordinates, so its value may vary.
  38405. * @param value the new threshold to apply
  38406. */
  38407. set: function (value) {
  38408. if (this._intersectionThreshold === value) {
  38409. return;
  38410. }
  38411. this._intersectionThreshold = value;
  38412. if (this.geometry) {
  38413. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38414. }
  38415. },
  38416. enumerable: true,
  38417. configurable: true
  38418. });
  38419. LinesMesh.prototype.getClassName = function () {
  38420. return "LinesMesh";
  38421. };
  38422. Object.defineProperty(LinesMesh.prototype, "material", {
  38423. get: function () {
  38424. return this._colorShader;
  38425. },
  38426. enumerable: true,
  38427. configurable: true
  38428. });
  38429. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38430. get: function () {
  38431. return false;
  38432. },
  38433. enumerable: true,
  38434. configurable: true
  38435. });
  38436. LinesMesh.prototype.createInstance = function (name) {
  38437. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38438. return null;
  38439. };
  38440. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38441. var engine = this.getScene().getEngine();
  38442. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  38443. // VBOs
  38444. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  38445. // Color
  38446. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38447. };
  38448. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38449. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38450. return;
  38451. }
  38452. var engine = this.getScene().getEngine();
  38453. // Draw order
  38454. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38455. };
  38456. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38457. this._colorShader.dispose();
  38458. _super.prototype.dispose.call(this, doNotRecurse);
  38459. };
  38460. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38461. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38462. };
  38463. return LinesMesh;
  38464. }(BABYLON.Mesh));
  38465. BABYLON.LinesMesh = LinesMesh;
  38466. })(BABYLON || (BABYLON = {}));
  38467. //# sourceMappingURL=babylon.linesMesh.js.map
  38468. var BABYLON;
  38469. (function (BABYLON) {
  38470. var DefaultLoadingScreen = (function () {
  38471. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  38472. if (_loadingText === void 0) { _loadingText = ""; }
  38473. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  38474. var _this = this;
  38475. this._renderingCanvas = _renderingCanvas;
  38476. this._loadingText = _loadingText;
  38477. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  38478. // Resize
  38479. this._resizeLoadingUI = function () {
  38480. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  38481. _this._loadingDiv.style.position = "absolute";
  38482. _this._loadingDiv.style.left = canvasRect.left + "px";
  38483. _this._loadingDiv.style.top = canvasRect.top + "px";
  38484. _this._loadingDiv.style.width = canvasRect.width + "px";
  38485. _this._loadingDiv.style.height = canvasRect.height + "px";
  38486. };
  38487. }
  38488. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  38489. var _this = this;
  38490. if (this._loadingDiv) {
  38491. // Do not add a loading screen if there is already one
  38492. return;
  38493. }
  38494. this._loadingDiv = document.createElement("div");
  38495. this._loadingDiv.id = "babylonjsLoadingDiv";
  38496. this._loadingDiv.style.opacity = "0";
  38497. this._loadingDiv.style.transition = "opacity 1.5s ease";
  38498. // Loading text
  38499. this._loadingTextDiv = document.createElement("div");
  38500. this._loadingTextDiv.style.position = "absolute";
  38501. this._loadingTextDiv.style.left = "0";
  38502. this._loadingTextDiv.style.top = "50%";
  38503. this._loadingTextDiv.style.marginTop = "80px";
  38504. this._loadingTextDiv.style.width = "100%";
  38505. this._loadingTextDiv.style.height = "20px";
  38506. this._loadingTextDiv.style.fontFamily = "Arial";
  38507. this._loadingTextDiv.style.fontSize = "14px";
  38508. this._loadingTextDiv.style.color = "white";
  38509. this._loadingTextDiv.style.textAlign = "center";
  38510. this._loadingTextDiv.innerHTML = "Loading";
  38511. this._loadingDiv.appendChild(this._loadingTextDiv);
  38512. //set the predefined text
  38513. this._loadingTextDiv.innerHTML = this._loadingText;
  38514. // Loading img
  38515. var imgBack = new Image();
  38516. 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==";
  38517. imgBack.style.position = "absolute";
  38518. imgBack.style.left = "50%";
  38519. imgBack.style.top = "50%";
  38520. imgBack.style.marginLeft = "-50px";
  38521. imgBack.style.marginTop = "-50px";
  38522. imgBack.style.transition = "transform 1.0s ease";
  38523. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  38524. var deg = 360;
  38525. var onTransitionEnd = function () {
  38526. deg += 360;
  38527. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  38528. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  38529. };
  38530. imgBack.addEventListener("transitionend", onTransitionEnd);
  38531. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  38532. this._loadingDiv.appendChild(imgBack);
  38533. // front image
  38534. var imgFront = new Image();
  38535. 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=";
  38536. imgFront.style.position = "absolute";
  38537. imgFront.style.left = "50%";
  38538. imgFront.style.top = "50%";
  38539. imgFront.style.marginLeft = "-50px";
  38540. imgFront.style.marginTop = "-50px";
  38541. this._loadingDiv.appendChild(imgFront);
  38542. this._resizeLoadingUI();
  38543. window.addEventListener("resize", this._resizeLoadingUI);
  38544. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38545. document.body.appendChild(this._loadingDiv);
  38546. setTimeout(function () {
  38547. _this._loadingDiv.style.opacity = "1";
  38548. imgBack.style.transform = "rotateZ(360deg)";
  38549. imgBack.style.webkitTransform = "rotateZ(360deg)";
  38550. }, 0);
  38551. };
  38552. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  38553. var _this = this;
  38554. if (!this._loadingDiv) {
  38555. return;
  38556. }
  38557. var onTransitionEnd = function () {
  38558. if (!_this._loadingDiv) {
  38559. return;
  38560. }
  38561. document.body.removeChild(_this._loadingDiv);
  38562. window.removeEventListener("resize", _this._resizeLoadingUI);
  38563. _this._loadingDiv = null;
  38564. };
  38565. this._loadingDiv.style.opacity = "0";
  38566. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  38567. };
  38568. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  38569. set: function (text) {
  38570. this._loadingText = text;
  38571. if (this._loadingTextDiv) {
  38572. this._loadingTextDiv.innerHTML = this._loadingText;
  38573. }
  38574. },
  38575. enumerable: true,
  38576. configurable: true
  38577. });
  38578. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  38579. get: function () {
  38580. return this._loadingDivBackgroundColor;
  38581. },
  38582. set: function (color) {
  38583. this._loadingDivBackgroundColor = color;
  38584. if (!this._loadingDiv) {
  38585. return;
  38586. }
  38587. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. return DefaultLoadingScreen;
  38593. }());
  38594. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  38595. })(BABYLON || (BABYLON = {}));
  38596. //# sourceMappingURL=babylon.loadingScreen.js.map
  38597. var BABYLON;
  38598. (function (BABYLON) {
  38599. var AudioEngine = (function () {
  38600. function AudioEngine() {
  38601. this._audioContext = null;
  38602. this._audioContextInitialized = false;
  38603. this.canUseWebAudio = false;
  38604. this.WarnedWebAudioUnsupported = false;
  38605. this.unlocked = false;
  38606. this.isMP3supported = false;
  38607. this.isOGGsupported = false;
  38608. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38609. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38610. this.canUseWebAudio = true;
  38611. }
  38612. var audioElem = document.createElement('audio');
  38613. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38614. this.isMP3supported = true;
  38615. }
  38616. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38617. this.isOGGsupported = true;
  38618. }
  38619. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38620. this._unlockiOSaudio();
  38621. }
  38622. else {
  38623. this.unlocked = true;
  38624. }
  38625. }
  38626. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38627. get: function () {
  38628. if (!this._audioContextInitialized) {
  38629. this._initializeAudioContext();
  38630. }
  38631. return this._audioContext;
  38632. },
  38633. enumerable: true,
  38634. configurable: true
  38635. });
  38636. AudioEngine.prototype._unlockiOSaudio = function () {
  38637. var _this = this;
  38638. var unlockaudio = function () {
  38639. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38640. var source = _this.audioContext.createBufferSource();
  38641. source.buffer = buffer;
  38642. source.connect(_this.audioContext.destination);
  38643. source.start(0);
  38644. setTimeout(function () {
  38645. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38646. _this.unlocked = true;
  38647. window.removeEventListener('touchend', unlockaudio, false);
  38648. if (_this.onAudioUnlocked) {
  38649. _this.onAudioUnlocked();
  38650. }
  38651. }
  38652. }, 0);
  38653. };
  38654. window.addEventListener('touchend', unlockaudio, false);
  38655. };
  38656. AudioEngine.prototype._initializeAudioContext = function () {
  38657. try {
  38658. if (this.canUseWebAudio) {
  38659. this._audioContext = new AudioContext();
  38660. // create a global volume gain node
  38661. this.masterGain = this._audioContext.createGain();
  38662. this.masterGain.gain.value = 1;
  38663. this.masterGain.connect(this._audioContext.destination);
  38664. this._audioContextInitialized = true;
  38665. }
  38666. }
  38667. catch (e) {
  38668. this.canUseWebAudio = false;
  38669. BABYLON.Tools.Error("Web Audio: " + e.message);
  38670. }
  38671. };
  38672. AudioEngine.prototype.dispose = function () {
  38673. if (this.canUseWebAudio && this._audioContextInitialized) {
  38674. if (this._connectedAnalyser) {
  38675. this._connectedAnalyser.stopDebugCanvas();
  38676. this._connectedAnalyser.dispose();
  38677. this.masterGain.disconnect();
  38678. this.masterGain.connect(this._audioContext.destination);
  38679. this._connectedAnalyser = null;
  38680. }
  38681. this.masterGain.gain.value = 1;
  38682. }
  38683. this.WarnedWebAudioUnsupported = false;
  38684. };
  38685. AudioEngine.prototype.getGlobalVolume = function () {
  38686. if (this.canUseWebAudio && this._audioContextInitialized) {
  38687. return this.masterGain.gain.value;
  38688. }
  38689. else {
  38690. return -1;
  38691. }
  38692. };
  38693. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38694. if (this.canUseWebAudio && this._audioContextInitialized) {
  38695. this.masterGain.gain.value = newVolume;
  38696. }
  38697. };
  38698. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38699. if (this._connectedAnalyser) {
  38700. this._connectedAnalyser.stopDebugCanvas();
  38701. }
  38702. if (this.canUseWebAudio && this._audioContextInitialized) {
  38703. this._connectedAnalyser = analyser;
  38704. this.masterGain.disconnect();
  38705. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38706. }
  38707. };
  38708. return AudioEngine;
  38709. }());
  38710. BABYLON.AudioEngine = AudioEngine;
  38711. })(BABYLON || (BABYLON = {}));
  38712. //# sourceMappingURL=babylon.audioEngine.js.map
  38713. var BABYLON;
  38714. (function (BABYLON) {
  38715. var Sound = (function () {
  38716. /**
  38717. * Create a sound and attach it to a scene
  38718. * @param name Name of your sound
  38719. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38720. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38721. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38722. */
  38723. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38724. var _this = this;
  38725. this.autoplay = false;
  38726. this.loop = false;
  38727. this.useCustomAttenuation = false;
  38728. this.spatialSound = false;
  38729. this.refDistance = 1;
  38730. this.rolloffFactor = 1;
  38731. this.maxDistance = 100;
  38732. this.distanceModel = "linear";
  38733. this._panningModel = "equalpower";
  38734. this._playbackRate = 1;
  38735. this._streaming = false;
  38736. this._startTime = 0;
  38737. this._startOffset = 0;
  38738. this._position = BABYLON.Vector3.Zero();
  38739. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38740. this._volume = 1;
  38741. this._isLoaded = false;
  38742. this._isReadyToPlay = false;
  38743. this.isPlaying = false;
  38744. this.isPaused = false;
  38745. this._isDirectional = false;
  38746. // Used if you'd like to create a directional sound.
  38747. // If not set, the sound will be omnidirectional
  38748. this._coneInnerAngle = 360;
  38749. this._coneOuterAngle = 360;
  38750. this._coneOuterGain = 0;
  38751. this._isOutputConnected = false;
  38752. this._urlType = "Unknown";
  38753. this.name = name;
  38754. this._scene = scene;
  38755. this._readyToPlayCallback = readyToPlayCallback;
  38756. // Default custom attenuation function is a linear attenuation
  38757. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  38758. if (currentDistance < maxDistance) {
  38759. return currentVolume * (1 - currentDistance / maxDistance);
  38760. }
  38761. else {
  38762. return 0;
  38763. }
  38764. };
  38765. if (options) {
  38766. this.autoplay = options.autoplay || false;
  38767. this.loop = options.loop || false;
  38768. // if volume === 0, we need another way to check this option
  38769. if (options.volume !== undefined) {
  38770. this._volume = options.volume;
  38771. }
  38772. this.spatialSound = options.spatialSound || false;
  38773. this.maxDistance = options.maxDistance || 100;
  38774. this.useCustomAttenuation = options.useCustomAttenuation || false;
  38775. this.rolloffFactor = options.rolloffFactor || 1;
  38776. this.refDistance = options.refDistance || 1;
  38777. this.distanceModel = options.distanceModel || "linear";
  38778. this._playbackRate = options.playbackRate || 1;
  38779. this._streaming = options.streaming || false;
  38780. }
  38781. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38782. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  38783. this._soundGain.gain.value = this._volume;
  38784. this._inputAudioNode = this._soundGain;
  38785. this._ouputAudioNode = this._soundGain;
  38786. if (this.spatialSound) {
  38787. this._createSpatialParameters();
  38788. }
  38789. this._scene.mainSoundTrack.AddSound(this);
  38790. var validParameter = true;
  38791. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  38792. if (urlOrArrayBuffer) {
  38793. if (typeof (urlOrArrayBuffer) === "string")
  38794. this._urlType = "String";
  38795. if (Array.isArray(urlOrArrayBuffer))
  38796. this._urlType = "Array";
  38797. if (urlOrArrayBuffer instanceof ArrayBuffer)
  38798. this._urlType = "ArrayBuffer";
  38799. var urls = [];
  38800. var codecSupportedFound = false;
  38801. switch (this._urlType) {
  38802. case "ArrayBuffer":
  38803. if (urlOrArrayBuffer.byteLength > 0) {
  38804. codecSupportedFound = true;
  38805. this._soundLoaded(urlOrArrayBuffer);
  38806. }
  38807. break;
  38808. case "String":
  38809. urls.push(urlOrArrayBuffer);
  38810. case "Array":
  38811. if (urls.length === 0)
  38812. urls = urlOrArrayBuffer;
  38813. // If we found a supported format, we load it immediately and stop the loop
  38814. for (var i = 0; i < urls.length; i++) {
  38815. var url = urls[i];
  38816. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  38817. codecSupportedFound = true;
  38818. }
  38819. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  38820. codecSupportedFound = true;
  38821. }
  38822. if (url.indexOf(".wav", url.length - 4) !== -1) {
  38823. codecSupportedFound = true;
  38824. }
  38825. if (codecSupportedFound) {
  38826. // Loading sound using XHR2
  38827. if (!this._streaming) {
  38828. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  38829. }
  38830. else {
  38831. this._htmlAudioElement = new Audio(url);
  38832. this._htmlAudioElement.controls = false;
  38833. this._htmlAudioElement.loop = this.loop;
  38834. this._htmlAudioElement.crossOrigin = "anonymous";
  38835. this._htmlAudioElement.preload = "auto";
  38836. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  38837. _this._isReadyToPlay = true;
  38838. if (_this.autoplay) {
  38839. _this.play();
  38840. }
  38841. if (_this._readyToPlayCallback) {
  38842. _this._readyToPlayCallback();
  38843. }
  38844. });
  38845. document.body.appendChild(this._htmlAudioElement);
  38846. }
  38847. break;
  38848. }
  38849. }
  38850. break;
  38851. default:
  38852. validParameter = false;
  38853. break;
  38854. }
  38855. if (!validParameter) {
  38856. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  38857. }
  38858. else {
  38859. if (!codecSupportedFound) {
  38860. this._isReadyToPlay = true;
  38861. // Simulating a ready to play event to avoid breaking code path
  38862. if (this._readyToPlayCallback) {
  38863. window.setTimeout(function () {
  38864. _this._readyToPlayCallback();
  38865. }, 1000);
  38866. }
  38867. }
  38868. }
  38869. }
  38870. }
  38871. else {
  38872. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  38873. this._scene.mainSoundTrack.AddSound(this);
  38874. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  38875. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  38876. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  38877. }
  38878. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  38879. if (this._readyToPlayCallback) {
  38880. window.setTimeout(function () {
  38881. _this._readyToPlayCallback();
  38882. }, 1000);
  38883. }
  38884. }
  38885. }
  38886. Sound.prototype.dispose = function () {
  38887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  38888. if (this.isPlaying) {
  38889. this.stop();
  38890. }
  38891. this._isReadyToPlay = false;
  38892. if (this.soundTrackId === -1) {
  38893. this._scene.mainSoundTrack.RemoveSound(this);
  38894. }
  38895. else {
  38896. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  38897. }
  38898. if (this._soundGain) {
  38899. this._soundGain.disconnect();
  38900. this._soundGain = null;
  38901. }
  38902. if (this._soundPanner) {
  38903. this._soundPanner.disconnect();
  38904. this._soundPanner = null;
  38905. }
  38906. if (this._soundSource) {
  38907. this._soundSource.disconnect();
  38908. this._soundSource = null;
  38909. }
  38910. this._audioBuffer = null;
  38911. if (this._htmlAudioElement) {
  38912. this._htmlAudioElement.pause();
  38913. this._htmlAudioElement.src = "";
  38914. document.body.removeChild(this._htmlAudioElement);
  38915. }
  38916. if (this._connectedMesh) {
  38917. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38918. this._connectedMesh = null;
  38919. }
  38920. }
  38921. };
  38922. Sound.prototype.isReady = function () {
  38923. return this._isReadyToPlay;
  38924. };
  38925. Sound.prototype._soundLoaded = function (audioData) {
  38926. var _this = this;
  38927. this._isLoaded = true;
  38928. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38929. _this._audioBuffer = buffer;
  38930. _this._isReadyToPlay = true;
  38931. if (_this.autoplay) {
  38932. _this.play();
  38933. }
  38934. if (_this._readyToPlayCallback) {
  38935. _this._readyToPlayCallback();
  38936. }
  38937. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38938. };
  38939. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38940. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38941. this._audioBuffer = audioBuffer;
  38942. this._isReadyToPlay = true;
  38943. }
  38944. };
  38945. Sound.prototype.updateOptions = function (options) {
  38946. if (options) {
  38947. this.loop = options.loop || this.loop;
  38948. this.maxDistance = options.maxDistance || this.maxDistance;
  38949. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38950. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38951. this.refDistance = options.refDistance || this.refDistance;
  38952. this.distanceModel = options.distanceModel || this.distanceModel;
  38953. this._playbackRate = options.playbackRate || this._playbackRate;
  38954. this._updateSpatialParameters();
  38955. if (this.isPlaying) {
  38956. if (this._streaming) {
  38957. this._htmlAudioElement.playbackRate = this._playbackRate;
  38958. }
  38959. else {
  38960. this._soundSource.playbackRate.value = this._playbackRate;
  38961. }
  38962. }
  38963. }
  38964. };
  38965. Sound.prototype._createSpatialParameters = function () {
  38966. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38967. if (this._scene.headphone) {
  38968. this._panningModel = "HRTF";
  38969. }
  38970. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38971. this._updateSpatialParameters();
  38972. this._soundPanner.connect(this._ouputAudioNode);
  38973. this._inputAudioNode = this._soundPanner;
  38974. }
  38975. };
  38976. Sound.prototype._updateSpatialParameters = function () {
  38977. if (this.spatialSound) {
  38978. if (this.useCustomAttenuation) {
  38979. // Tricks to disable in a way embedded Web Audio attenuation
  38980. this._soundPanner.distanceModel = "linear";
  38981. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38982. this._soundPanner.refDistance = 1;
  38983. this._soundPanner.rolloffFactor = 1;
  38984. this._soundPanner.panningModel = this._panningModel;
  38985. }
  38986. else {
  38987. this._soundPanner.distanceModel = this.distanceModel;
  38988. this._soundPanner.maxDistance = this.maxDistance;
  38989. this._soundPanner.refDistance = this.refDistance;
  38990. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38991. this._soundPanner.panningModel = this._panningModel;
  38992. }
  38993. }
  38994. };
  38995. Sound.prototype.switchPanningModelToHRTF = function () {
  38996. this._panningModel = "HRTF";
  38997. this._switchPanningModel();
  38998. };
  38999. Sound.prototype.switchPanningModelToEqualPower = function () {
  39000. this._panningModel = "equalpower";
  39001. this._switchPanningModel();
  39002. };
  39003. Sound.prototype._switchPanningModel = function () {
  39004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39005. this._soundPanner.panningModel = this._panningModel;
  39006. }
  39007. };
  39008. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  39009. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39010. if (this._isOutputConnected) {
  39011. this._ouputAudioNode.disconnect();
  39012. }
  39013. this._ouputAudioNode.connect(soundTrackAudioNode);
  39014. this._isOutputConnected = true;
  39015. }
  39016. };
  39017. /**
  39018. * Transform this sound into a directional source
  39019. * @param coneInnerAngle Size of the inner cone in degree
  39020. * @param coneOuterAngle Size of the outer cone in degree
  39021. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39022. */
  39023. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39024. if (coneOuterAngle < coneInnerAngle) {
  39025. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39026. return;
  39027. }
  39028. this._coneInnerAngle = coneInnerAngle;
  39029. this._coneOuterAngle = coneOuterAngle;
  39030. this._coneOuterGain = coneOuterGain;
  39031. this._isDirectional = true;
  39032. if (this.isPlaying && this.loop) {
  39033. this.stop();
  39034. this.play();
  39035. }
  39036. };
  39037. Sound.prototype.setPosition = function (newPosition) {
  39038. this._position = newPosition;
  39039. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39040. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39041. }
  39042. };
  39043. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39044. this._localDirection = newLocalDirection;
  39045. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39046. this._updateDirection();
  39047. }
  39048. };
  39049. Sound.prototype._updateDirection = function () {
  39050. var mat = this._connectedMesh.getWorldMatrix();
  39051. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39052. direction.normalize();
  39053. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39054. };
  39055. Sound.prototype.updateDistanceFromListener = function () {
  39056. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39057. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39058. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39059. }
  39060. };
  39061. Sound.prototype.setAttenuationFunction = function (callback) {
  39062. this._customAttenuationFunction = callback;
  39063. };
  39064. /**
  39065. * Play the sound
  39066. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39067. * @param offset (optional) Start the sound setting it at a specific time
  39068. */
  39069. Sound.prototype.play = function (time, offset) {
  39070. var _this = this;
  39071. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39072. try {
  39073. if (this._startOffset < 0) {
  39074. time = -this._startOffset;
  39075. this._startOffset = 0;
  39076. }
  39077. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39078. if (!this._soundSource || !this._streamingSource) {
  39079. if (this.spatialSound) {
  39080. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39081. if (this._isDirectional) {
  39082. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39083. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39084. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39085. if (this._connectedMesh) {
  39086. this._updateDirection();
  39087. }
  39088. else {
  39089. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39090. }
  39091. }
  39092. }
  39093. }
  39094. if (this._streaming) {
  39095. if (!this._streamingSource) {
  39096. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39097. this._htmlAudioElement.onended = function () { _this._onended(); };
  39098. this._htmlAudioElement.playbackRate = this._playbackRate;
  39099. }
  39100. this._streamingSource.disconnect();
  39101. this._streamingSource.connect(this._inputAudioNode);
  39102. this._htmlAudioElement.play();
  39103. }
  39104. else {
  39105. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39106. this._soundSource.buffer = this._audioBuffer;
  39107. this._soundSource.connect(this._inputAudioNode);
  39108. this._soundSource.loop = this.loop;
  39109. this._soundSource.playbackRate.value = this._playbackRate;
  39110. this._soundSource.onended = function () { _this._onended(); };
  39111. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39112. }
  39113. this._startTime = startTime;
  39114. this.isPlaying = true;
  39115. this.isPaused = false;
  39116. }
  39117. catch (ex) {
  39118. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39119. }
  39120. }
  39121. };
  39122. Sound.prototype._onended = function () {
  39123. this.isPlaying = false;
  39124. if (this.onended) {
  39125. this.onended();
  39126. }
  39127. };
  39128. /**
  39129. * Stop the sound
  39130. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39131. */
  39132. Sound.prototype.stop = function (time) {
  39133. if (this.isPlaying) {
  39134. if (this._streaming) {
  39135. this._htmlAudioElement.pause();
  39136. // Test needed for Firefox or it will generate an Invalid State Error
  39137. if (this._htmlAudioElement.currentTime > 0) {
  39138. this._htmlAudioElement.currentTime = 0;
  39139. }
  39140. }
  39141. else {
  39142. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39143. this._soundSource.stop(stopTime);
  39144. this._soundSource.onended = null;
  39145. if (!this.isPaused) {
  39146. this._startOffset = 0;
  39147. }
  39148. }
  39149. this.isPlaying = false;
  39150. }
  39151. };
  39152. Sound.prototype.pause = function () {
  39153. if (this.isPlaying) {
  39154. this.isPaused = true;
  39155. if (this._streaming) {
  39156. this._htmlAudioElement.pause();
  39157. }
  39158. else {
  39159. this.stop(0);
  39160. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39161. }
  39162. }
  39163. };
  39164. Sound.prototype.setVolume = function (newVolume, time) {
  39165. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39166. if (time) {
  39167. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39168. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39169. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39170. }
  39171. else {
  39172. this._soundGain.gain.value = newVolume;
  39173. }
  39174. }
  39175. this._volume = newVolume;
  39176. };
  39177. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39178. this._playbackRate = newPlaybackRate;
  39179. if (this.isPlaying) {
  39180. if (this._streaming) {
  39181. this._htmlAudioElement.playbackRate = this._playbackRate;
  39182. }
  39183. else {
  39184. this._soundSource.playbackRate.value = this._playbackRate;
  39185. }
  39186. }
  39187. };
  39188. Sound.prototype.getVolume = function () {
  39189. return this._volume;
  39190. };
  39191. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39192. var _this = this;
  39193. if (this._connectedMesh) {
  39194. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39195. this._registerFunc = null;
  39196. }
  39197. this._connectedMesh = meshToConnectTo;
  39198. if (!this.spatialSound) {
  39199. this.spatialSound = true;
  39200. this._createSpatialParameters();
  39201. if (this.isPlaying && this.loop) {
  39202. this.stop();
  39203. this.play();
  39204. }
  39205. }
  39206. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39207. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39208. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39209. };
  39210. Sound.prototype.detachFromMesh = function () {
  39211. if (this._connectedMesh) {
  39212. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39213. this._registerFunc = null;
  39214. this._connectedMesh = null;
  39215. }
  39216. };
  39217. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39218. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39219. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39220. this._updateDirection();
  39221. }
  39222. };
  39223. Sound.prototype.clone = function () {
  39224. var _this = this;
  39225. if (!this._streaming) {
  39226. var setBufferAndRun = function () {
  39227. if (_this._isReadyToPlay) {
  39228. clonedSound._audioBuffer = _this.getAudioBuffer();
  39229. clonedSound._isReadyToPlay = true;
  39230. if (clonedSound.autoplay) {
  39231. clonedSound.play();
  39232. }
  39233. }
  39234. else {
  39235. window.setTimeout(setBufferAndRun, 300);
  39236. }
  39237. };
  39238. var currentOptions = {
  39239. autoplay: this.autoplay, loop: this.loop,
  39240. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39241. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39242. refDistance: this.refDistance, distanceModel: this.distanceModel
  39243. };
  39244. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39245. if (this.useCustomAttenuation) {
  39246. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39247. }
  39248. clonedSound.setPosition(this._position);
  39249. clonedSound.setPlaybackRate(this._playbackRate);
  39250. setBufferAndRun();
  39251. return clonedSound;
  39252. }
  39253. else {
  39254. return null;
  39255. }
  39256. };
  39257. Sound.prototype.getAudioBuffer = function () {
  39258. return this._audioBuffer;
  39259. };
  39260. Sound.prototype.serialize = function () {
  39261. var serializationObject = {
  39262. name: this.name,
  39263. url: this.name,
  39264. autoplay: this.autoplay,
  39265. loop: this.loop,
  39266. volume: this._volume,
  39267. spatialSound: this.spatialSound,
  39268. maxDistance: this.maxDistance,
  39269. rolloffFactor: this.rolloffFactor,
  39270. refDistance: this.refDistance,
  39271. distanceModel: this.distanceModel,
  39272. playbackRate: this._playbackRate,
  39273. panningModel: this._panningModel,
  39274. soundTrackId: this.soundTrackId
  39275. };
  39276. if (this.spatialSound) {
  39277. if (this._connectedMesh)
  39278. serializationObject.connectedMeshId = this._connectedMesh.id;
  39279. serializationObject.position = this._position.asArray();
  39280. serializationObject.refDistance = this.refDistance;
  39281. serializationObject.distanceModel = this.distanceModel;
  39282. serializationObject.isDirectional = this._isDirectional;
  39283. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39284. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39285. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39286. serializationObject.coneOuterGain = this._coneOuterGain;
  39287. }
  39288. return serializationObject;
  39289. };
  39290. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39291. var soundName = parsedSound.name;
  39292. var soundUrl;
  39293. if (parsedSound.url) {
  39294. soundUrl = rootUrl + parsedSound.url;
  39295. }
  39296. else {
  39297. soundUrl = rootUrl + soundName;
  39298. }
  39299. var options = {
  39300. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39301. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39302. rolloffFactor: parsedSound.rolloffFactor,
  39303. refDistance: parsedSound.refDistance,
  39304. distanceModel: parsedSound.distanceModel,
  39305. playbackRate: parsedSound.playbackRate
  39306. };
  39307. var newSound;
  39308. if (!sourceSound) {
  39309. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39310. scene._addPendingData(newSound);
  39311. }
  39312. else {
  39313. var setBufferAndRun = function () {
  39314. if (sourceSound._isReadyToPlay) {
  39315. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39316. newSound._isReadyToPlay = true;
  39317. if (newSound.autoplay) {
  39318. newSound.play();
  39319. }
  39320. }
  39321. else {
  39322. window.setTimeout(setBufferAndRun, 300);
  39323. }
  39324. };
  39325. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39326. setBufferAndRun();
  39327. }
  39328. if (parsedSound.position) {
  39329. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39330. newSound.setPosition(soundPosition);
  39331. }
  39332. if (parsedSound.isDirectional) {
  39333. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39334. if (parsedSound.localDirectionToMesh) {
  39335. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39336. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39337. }
  39338. }
  39339. if (parsedSound.connectedMeshId) {
  39340. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39341. if (connectedMesh) {
  39342. newSound.attachToMesh(connectedMesh);
  39343. }
  39344. }
  39345. return newSound;
  39346. };
  39347. return Sound;
  39348. }());
  39349. BABYLON.Sound = Sound;
  39350. })(BABYLON || (BABYLON = {}));
  39351. //# sourceMappingURL=babylon.sound.js.map
  39352. var BABYLON;
  39353. (function (BABYLON) {
  39354. var SoundTrack = (function () {
  39355. function SoundTrack(scene, options) {
  39356. this.id = -1;
  39357. this._isMainTrack = false;
  39358. this._isInitialized = false;
  39359. this._scene = scene;
  39360. this.soundCollection = new Array();
  39361. this._options = options;
  39362. if (!this._isMainTrack) {
  39363. this._scene.soundTracks.push(this);
  39364. this.id = this._scene.soundTracks.length - 1;
  39365. }
  39366. }
  39367. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39368. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39369. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39370. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39371. if (this._options) {
  39372. if (this._options.volume) {
  39373. this._outputAudioNode.gain.value = this._options.volume;
  39374. }
  39375. if (this._options.mainTrack) {
  39376. this._isMainTrack = this._options.mainTrack;
  39377. }
  39378. }
  39379. this._isInitialized = true;
  39380. }
  39381. };
  39382. SoundTrack.prototype.dispose = function () {
  39383. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39384. if (this._connectedAnalyser) {
  39385. this._connectedAnalyser.stopDebugCanvas();
  39386. }
  39387. while (this.soundCollection.length) {
  39388. this.soundCollection[0].dispose();
  39389. }
  39390. if (this._outputAudioNode) {
  39391. this._outputAudioNode.disconnect();
  39392. }
  39393. this._outputAudioNode = null;
  39394. }
  39395. };
  39396. SoundTrack.prototype.AddSound = function (sound) {
  39397. if (!this._isInitialized) {
  39398. this._initializeSoundTrackAudioGraph();
  39399. }
  39400. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39401. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39402. }
  39403. if (sound.soundTrackId) {
  39404. if (sound.soundTrackId === -1) {
  39405. this._scene.mainSoundTrack.RemoveSound(sound);
  39406. }
  39407. else {
  39408. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39409. }
  39410. }
  39411. this.soundCollection.push(sound);
  39412. sound.soundTrackId = this.id;
  39413. };
  39414. SoundTrack.prototype.RemoveSound = function (sound) {
  39415. var index = this.soundCollection.indexOf(sound);
  39416. if (index !== -1) {
  39417. this.soundCollection.splice(index, 1);
  39418. }
  39419. };
  39420. SoundTrack.prototype.setVolume = function (newVolume) {
  39421. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39422. this._outputAudioNode.gain.value = newVolume;
  39423. }
  39424. };
  39425. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39426. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39427. for (var i = 0; i < this.soundCollection.length; i++) {
  39428. this.soundCollection[i].switchPanningModelToHRTF();
  39429. }
  39430. }
  39431. };
  39432. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39433. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39434. for (var i = 0; i < this.soundCollection.length; i++) {
  39435. this.soundCollection[i].switchPanningModelToEqualPower();
  39436. }
  39437. }
  39438. };
  39439. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39440. if (this._connectedAnalyser) {
  39441. this._connectedAnalyser.stopDebugCanvas();
  39442. }
  39443. this._connectedAnalyser = analyser;
  39444. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39445. this._outputAudioNode.disconnect();
  39446. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39447. }
  39448. };
  39449. return SoundTrack;
  39450. }());
  39451. BABYLON.SoundTrack = SoundTrack;
  39452. })(BABYLON || (BABYLON = {}));
  39453. //# sourceMappingURL=babylon.soundtrack.js.map
  39454. var BABYLON;
  39455. (function (BABYLON) {
  39456. /**
  39457. * Special Glow Blur post process only blurring the alpha channel
  39458. * It enforces keeping the most luminous color in the color channel.
  39459. */
  39460. var GlowBlurPostProcess = (function (_super) {
  39461. __extends(GlowBlurPostProcess, _super);
  39462. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  39463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39464. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  39465. _this.direction = direction;
  39466. _this.blurWidth = blurWidth;
  39467. _this.onApplyObservable.add(function (effect) {
  39468. effect.setFloat2("screenSize", _this.width, _this.height);
  39469. effect.setVector2("direction", _this.direction);
  39470. effect.setFloat("blurWidth", _this.blurWidth);
  39471. });
  39472. return _this;
  39473. }
  39474. return GlowBlurPostProcess;
  39475. }(BABYLON.PostProcess));
  39476. /**
  39477. * The highlight layer Helps adding a glow effect around a mesh.
  39478. *
  39479. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  39480. * glowy meshes to your scene.
  39481. *
  39482. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  39483. */
  39484. var HighlightLayer = (function () {
  39485. /**
  39486. * Instantiates a new highlight Layer and references it to the scene..
  39487. * @param name The name of the layer
  39488. * @param scene The scene to use the layer in
  39489. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  39490. */
  39491. function HighlightLayer(name, scene, options) {
  39492. this._vertexBuffers = {};
  39493. this._mainTextureDesiredSize = { width: 0, height: 0 };
  39494. this._meshes = {};
  39495. this._maxSize = 0;
  39496. this._shouldRender = false;
  39497. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  39498. this._excludedMeshes = {};
  39499. /**
  39500. * Specifies whether or not the inner glow is ACTIVE in the layer.
  39501. */
  39502. this.innerGlow = true;
  39503. /**
  39504. * Specifies whether or not the outer glow is ACTIVE in the layer.
  39505. */
  39506. this.outerGlow = true;
  39507. /**
  39508. * Specifies wether the highlight layer is enabled or not.
  39509. */
  39510. this.isEnabled = true;
  39511. /**
  39512. * An event triggered when the highlight layer has been disposed.
  39513. * @type {BABYLON.Observable}
  39514. */
  39515. this.onDisposeObservable = new BABYLON.Observable();
  39516. /**
  39517. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  39518. * @type {BABYLON.Observable}
  39519. */
  39520. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  39521. /**
  39522. * An event triggered when the highlight layer is being blurred.
  39523. * @type {BABYLON.Observable}
  39524. */
  39525. this.onBeforeBlurObservable = new BABYLON.Observable();
  39526. /**
  39527. * An event triggered when the highlight layer has been blurred.
  39528. * @type {BABYLON.Observable}
  39529. */
  39530. this.onAfterBlurObservable = new BABYLON.Observable();
  39531. /**
  39532. * An event triggered when the glowing blurred texture is being merged in the scene.
  39533. * @type {BABYLON.Observable}
  39534. */
  39535. this.onBeforeComposeObservable = new BABYLON.Observable();
  39536. /**
  39537. * An event triggered when the glowing blurred texture has been merged in the scene.
  39538. * @type {BABYLON.Observable}
  39539. */
  39540. this.onAfterComposeObservable = new BABYLON.Observable();
  39541. /**
  39542. * An event triggered when the highlight layer changes its size.
  39543. * @type {BABYLON.Observable}
  39544. */
  39545. this.onSizeChangedObservable = new BABYLON.Observable();
  39546. this._scene = scene;
  39547. var engine = scene.getEngine();
  39548. this._engine = engine;
  39549. this._maxSize = this._engine.getCaps().maxTextureSize;
  39550. this._scene.highlightLayers.push(this);
  39551. // Warn on stencil.
  39552. if (!this._engine.isStencilEnable) {
  39553. 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 }");
  39554. }
  39555. // Adapt options
  39556. this._options = options || {
  39557. mainTextureRatio: 0.25,
  39558. blurTextureSizeRatio: 0.5,
  39559. blurHorizontalSize: 1,
  39560. blurVerticalSize: 1,
  39561. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  39562. };
  39563. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  39564. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  39565. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  39566. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  39567. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  39568. // VBO
  39569. var vertices = [];
  39570. vertices.push(1, 1);
  39571. vertices.push(-1, 1);
  39572. vertices.push(-1, -1);
  39573. vertices.push(1, -1);
  39574. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  39576. // Indices
  39577. var indices = [];
  39578. indices.push(0);
  39579. indices.push(1);
  39580. indices.push(2);
  39581. indices.push(0);
  39582. indices.push(2);
  39583. indices.push(3);
  39584. this._indexBuffer = engine.createIndexBuffer(indices);
  39585. // Effect
  39586. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  39587. // Render target
  39588. this.setMainTextureSize();
  39589. // Create Textures and post processes
  39590. this.createTextureAndPostProcesses();
  39591. }
  39592. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  39593. /**
  39594. * Gets the horizontal size of the blur.
  39595. */
  39596. get: function () {
  39597. return this._horizontalBlurPostprocess.blurWidth;
  39598. },
  39599. /**
  39600. * Specifies the horizontal size of the blur.
  39601. */
  39602. set: function (value) {
  39603. this._horizontalBlurPostprocess.blurWidth = value;
  39604. },
  39605. enumerable: true,
  39606. configurable: true
  39607. });
  39608. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  39609. /**
  39610. * Gets the vertical size of the blur.
  39611. */
  39612. get: function () {
  39613. return this._verticalBlurPostprocess.blurWidth;
  39614. },
  39615. /**
  39616. * Specifies the vertical size of the blur.
  39617. */
  39618. set: function (value) {
  39619. this._verticalBlurPostprocess.blurWidth = value;
  39620. },
  39621. enumerable: true,
  39622. configurable: true
  39623. });
  39624. Object.defineProperty(HighlightLayer.prototype, "camera", {
  39625. /**
  39626. * Gets the camera attached to the layer.
  39627. */
  39628. get: function () {
  39629. return this._options.camera;
  39630. },
  39631. enumerable: true,
  39632. configurable: true
  39633. });
  39634. /**
  39635. * Creates the render target textures and post processes used in the highlight layer.
  39636. */
  39637. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  39638. var _this = this;
  39639. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  39640. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  39641. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  39642. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  39643. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  39644. width: this._mainTextureDesiredSize.width,
  39645. height: this._mainTextureDesiredSize.height
  39646. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39647. this._mainTexture.activeCamera = this._options.camera;
  39648. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39649. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39650. this._mainTexture.anisotropicFilteringLevel = 1;
  39651. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39652. this._mainTexture.renderParticles = false;
  39653. this._mainTexture.renderList = null;
  39654. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  39655. width: blurTextureWidth,
  39656. height: blurTextureHeight
  39657. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39658. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39659. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39660. this._blurTexture.anisotropicFilteringLevel = 16;
  39661. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39662. this._blurTexture.renderParticles = false;
  39663. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39664. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  39665. effect.setTexture("textureSampler", _this._mainTexture);
  39666. });
  39667. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  39668. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39669. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39670. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39671. });
  39672. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39673. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39674. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39675. });
  39676. }
  39677. else {
  39678. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39679. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39680. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39681. });
  39682. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39683. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39684. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39685. });
  39686. }
  39687. this._mainTexture.onAfterUnbindObservable.add(function () {
  39688. _this.onBeforeBlurObservable.notifyObservers(_this);
  39689. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  39690. _this.onAfterBlurObservable.notifyObservers(_this);
  39691. });
  39692. // Custom render function
  39693. var renderSubMesh = function (subMesh) {
  39694. var mesh = subMesh.getRenderingMesh();
  39695. var scene = _this._scene;
  39696. var engine = scene.getEngine();
  39697. // Culling
  39698. engine.setState(subMesh.getMaterial().backFaceCulling);
  39699. // Managing instances
  39700. var batch = mesh._getInstancesRenderList(subMesh._id);
  39701. if (batch.mustReturn) {
  39702. return;
  39703. }
  39704. // Excluded Mesh
  39705. if (_this._excludedMeshes[mesh.uniqueId]) {
  39706. return;
  39707. }
  39708. ;
  39709. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  39710. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  39711. var material = subMesh.getMaterial();
  39712. var emissiveTexture = null;
  39713. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  39714. emissiveTexture = material.emissiveTexture;
  39715. }
  39716. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  39717. engine.enableEffect(_this._glowMapGenerationEffect);
  39718. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  39719. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  39720. if (highlightLayerMesh) {
  39721. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  39722. }
  39723. else {
  39724. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  39725. }
  39726. // Alpha test
  39727. if (material && material.needAlphaTesting()) {
  39728. var alphaTexture = material.getAlphaTestTexture();
  39729. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  39730. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39731. }
  39732. // Glow emissive only
  39733. if (emissiveTexture) {
  39734. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  39735. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  39736. }
  39737. // Bones
  39738. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39739. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39740. }
  39741. // Draw
  39742. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  39743. }
  39744. else {
  39745. // Need to reset refresh rate of the shadowMap
  39746. _this._mainTexture.resetRefreshCounter();
  39747. }
  39748. };
  39749. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  39750. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  39751. var index;
  39752. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39753. renderSubMesh(opaqueSubMeshes.data[index]);
  39754. }
  39755. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39756. renderSubMesh(alphaTestSubMeshes.data[index]);
  39757. }
  39758. for (index = 0; index < transparentSubMeshes.length; index++) {
  39759. renderSubMesh(transparentSubMeshes.data[index]);
  39760. }
  39761. };
  39762. this._mainTexture.onClearObservable.add(function (engine) {
  39763. engine.clear(HighlightLayer.neutralColor, true, true, true);
  39764. });
  39765. };
  39766. /**
  39767. * Checks for the readiness of the element composing the layer.
  39768. * @param subMesh the mesh to check for
  39769. * @param useInstances specify wether or not to use instances to render the mesh
  39770. * @param emissiveTexture the associated emissive texture used to generate the glow
  39771. * @return true if ready otherwise, false
  39772. */
  39773. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  39774. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  39775. return false;
  39776. }
  39777. var defines = [];
  39778. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39779. var mesh = subMesh.getMesh();
  39780. var material = subMesh.getMaterial();
  39781. var uv1 = false;
  39782. var uv2 = false;
  39783. // Alpha test
  39784. if (material && material.needAlphaTesting()) {
  39785. var alphaTexture = material.getAlphaTestTexture();
  39786. if (alphaTexture) {
  39787. defines.push("#define ALPHATEST");
  39788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39789. alphaTexture.coordinatesIndex === 1) {
  39790. defines.push("#define DIFFUSEUV2");
  39791. uv2 = true;
  39792. }
  39793. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39794. defines.push("#define DIFFUSEUV1");
  39795. uv1 = true;
  39796. }
  39797. }
  39798. }
  39799. // Emissive
  39800. if (emissiveTexture) {
  39801. defines.push("#define EMISSIVE");
  39802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  39803. emissiveTexture.coordinatesIndex === 1) {
  39804. defines.push("#define EMISSIVEUV2");
  39805. uv2 = true;
  39806. }
  39807. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39808. defines.push("#define EMISSIVEUV1");
  39809. uv1 = true;
  39810. }
  39811. }
  39812. if (uv1) {
  39813. attribs.push(BABYLON.VertexBuffer.UVKind);
  39814. defines.push("#define UV1");
  39815. }
  39816. if (uv2) {
  39817. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39818. defines.push("#define UV2");
  39819. }
  39820. // Bones
  39821. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39824. if (mesh.numBoneInfluencers > 4) {
  39825. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39826. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39827. }
  39828. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39829. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39830. }
  39831. else {
  39832. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39833. }
  39834. // Instances
  39835. if (useInstances) {
  39836. defines.push("#define INSTANCES");
  39837. attribs.push("world0");
  39838. attribs.push("world1");
  39839. attribs.push("world2");
  39840. attribs.push("world3");
  39841. }
  39842. // Get correct effect
  39843. var join = defines.join("\n");
  39844. if (this._cachedDefines !== join) {
  39845. this._cachedDefines = join;
  39846. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  39847. }
  39848. return this._glowMapGenerationEffect.isReady();
  39849. };
  39850. /**
  39851. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  39852. */
  39853. HighlightLayer.prototype.render = function () {
  39854. var currentEffect = this._glowMapMergeEffect;
  39855. // Check
  39856. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  39857. return;
  39858. var engine = this._scene.getEngine();
  39859. this.onBeforeComposeObservable.notifyObservers(this);
  39860. // Render
  39861. engine.enableEffect(currentEffect);
  39862. engine.setState(false);
  39863. // Cache
  39864. var previousStencilBuffer = engine.getStencilBuffer();
  39865. var previousStencilFunction = engine.getStencilFunction();
  39866. var previousStencilMask = engine.getStencilMask();
  39867. var previousAlphaMode = engine.getAlphaMode();
  39868. // Texture
  39869. currentEffect.setTexture("textureSampler", this._blurTexture);
  39870. // VBOs
  39871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  39872. // Draw order
  39873. engine.setAlphaMode(this._options.alphaBlendingMode);
  39874. engine.setStencilMask(0x00);
  39875. engine.setStencilBuffer(true);
  39876. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  39877. if (this.outerGlow) {
  39878. currentEffect.setFloat("offset", 0);
  39879. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  39880. engine.draw(true, 0, 6);
  39881. }
  39882. if (this.innerGlow) {
  39883. currentEffect.setFloat("offset", 1);
  39884. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  39885. engine.draw(true, 0, 6);
  39886. }
  39887. // Restore Cache
  39888. engine.setStencilFunction(previousStencilFunction);
  39889. engine.setStencilMask(previousStencilMask);
  39890. engine.setAlphaMode(previousAlphaMode);
  39891. engine.setStencilBuffer(previousStencilBuffer);
  39892. this.onAfterComposeObservable.notifyObservers(this);
  39893. // Handle size changes.
  39894. var size = this._mainTexture.getSize();
  39895. this.setMainTextureSize();
  39896. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  39897. // Recreate RTT and post processes on size change.
  39898. this.onSizeChangedObservable.notifyObservers(this);
  39899. this.disposeTextureAndPostProcesses();
  39900. this.createTextureAndPostProcesses();
  39901. }
  39902. };
  39903. /**
  39904. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  39905. * @param mesh The mesh to exclude from the highlight layer
  39906. */
  39907. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  39908. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39909. if (!meshExcluded) {
  39910. this._excludedMeshes[mesh.uniqueId] = {
  39911. mesh: mesh,
  39912. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  39913. mesh.getEngine().setStencilBuffer(false);
  39914. }),
  39915. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  39916. mesh.getEngine().setStencilBuffer(true);
  39917. }),
  39918. };
  39919. }
  39920. };
  39921. /**
  39922. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39923. * @param mesh The mesh to highlight
  39924. */
  39925. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39926. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39927. if (meshExcluded) {
  39928. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39929. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39930. }
  39931. this._excludedMeshes[mesh.uniqueId] = undefined;
  39932. };
  39933. /**
  39934. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39935. * @param mesh The mesh to highlight
  39936. * @param color The color of the highlight
  39937. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39938. */
  39939. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39940. var _this = this;
  39941. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39942. var meshHighlight = this._meshes[mesh.uniqueId];
  39943. if (meshHighlight) {
  39944. meshHighlight.color = color;
  39945. }
  39946. else {
  39947. this._meshes[mesh.uniqueId] = {
  39948. mesh: mesh,
  39949. color: color,
  39950. // Lambda required for capture due to Observable this context
  39951. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39952. if (_this._excludedMeshes[mesh.uniqueId]) {
  39953. _this.defaultStencilReference(mesh);
  39954. }
  39955. else {
  39956. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39957. }
  39958. }),
  39959. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39960. glowEmissiveOnly: glowEmissiveOnly
  39961. };
  39962. }
  39963. this._shouldRender = true;
  39964. };
  39965. /**
  39966. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39967. * @param mesh The mesh to highlight
  39968. */
  39969. HighlightLayer.prototype.removeMesh = function (mesh) {
  39970. var meshHighlight = this._meshes[mesh.uniqueId];
  39971. if (meshHighlight) {
  39972. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39973. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39974. }
  39975. this._meshes[mesh.uniqueId] = undefined;
  39976. this._shouldRender = false;
  39977. for (var meshHighlightToCheck in this._meshes) {
  39978. if (meshHighlightToCheck) {
  39979. this._shouldRender = true;
  39980. break;
  39981. }
  39982. }
  39983. };
  39984. /**
  39985. * Returns true if the layer contains information to display, otherwise false.
  39986. */
  39987. HighlightLayer.prototype.shouldRender = function () {
  39988. return this.isEnabled && this._shouldRender;
  39989. };
  39990. /**
  39991. * Sets the main texture desired size which is the closest power of two
  39992. * of the engine canvas size.
  39993. */
  39994. HighlightLayer.prototype.setMainTextureSize = function () {
  39995. if (this._options.mainTextureFixedSize) {
  39996. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39997. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39998. }
  39999. else {
  40000. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  40001. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  40002. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  40003. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  40004. }
  40005. };
  40006. /**
  40007. * Force the stencil to the normal expected value for none glowing parts
  40008. */
  40009. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  40010. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  40011. };
  40012. /**
  40013. * Dispose only the render target textures and post process.
  40014. */
  40015. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  40016. this._blurTexture.dispose();
  40017. this._mainTexture.dispose();
  40018. this._downSamplePostprocess.dispose();
  40019. this._horizontalBlurPostprocess.dispose();
  40020. this._verticalBlurPostprocess.dispose();
  40021. };
  40022. /**
  40023. * Dispose the highlight layer and free resources.
  40024. */
  40025. HighlightLayer.prototype.dispose = function () {
  40026. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40027. if (vertexBuffer) {
  40028. vertexBuffer.dispose();
  40029. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40030. }
  40031. if (this._indexBuffer) {
  40032. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40033. this._indexBuffer = null;
  40034. }
  40035. // Clean textures and post processes
  40036. this.disposeTextureAndPostProcesses();
  40037. // Clean mesh references
  40038. for (var id in this._meshes) {
  40039. var meshHighlight = this._meshes[id];
  40040. if (meshHighlight && meshHighlight.mesh) {
  40041. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40042. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40043. }
  40044. }
  40045. this._meshes = null;
  40046. for (var id in this._excludedMeshes) {
  40047. var meshHighlight = this._excludedMeshes[id];
  40048. if (meshHighlight) {
  40049. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  40050. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  40051. }
  40052. }
  40053. this._excludedMeshes = null;
  40054. // Remove from scene
  40055. var index = this._scene.highlightLayers.indexOf(this, 0);
  40056. if (index > -1) {
  40057. this._scene.highlightLayers.splice(index, 1);
  40058. }
  40059. // Callback
  40060. this.onDisposeObservable.notifyObservers(this);
  40061. this.onDisposeObservable.clear();
  40062. this.onBeforeRenderMainTextureObservable.clear();
  40063. this.onBeforeBlurObservable.clear();
  40064. this.onBeforeComposeObservable.clear();
  40065. this.onAfterComposeObservable.clear();
  40066. this.onSizeChangedObservable.clear();
  40067. };
  40068. return HighlightLayer;
  40069. }());
  40070. /**
  40071. * The neutral color used during the preparation of the glow effect.
  40072. * This is black by default as the blend operation is a blend operation.
  40073. */
  40074. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  40075. /**
  40076. * Stencil value used for glowing meshes.
  40077. */
  40078. HighlightLayer.glowingMeshStencilReference = 0x02;
  40079. /**
  40080. * Stencil value used for the other meshes in the scene.
  40081. */
  40082. HighlightLayer.normalMeshStencilReference = 0x01;
  40083. BABYLON.HighlightLayer = HighlightLayer;
  40084. })(BABYLON || (BABYLON = {}));
  40085. //# sourceMappingURL=babylon.highlightlayer.js.map
  40086. var BABYLON;
  40087. (function (BABYLON) {
  40088. var SIMDVector3 = (function () {
  40089. function SIMDVector3() {
  40090. }
  40091. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  40092. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  40093. };
  40094. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  40095. var m = transformation.m;
  40096. var m0 = SIMD.Float32x4.load(m, 0);
  40097. var m1 = SIMD.Float32x4.load(m, 4);
  40098. var m2 = SIMD.Float32x4.load(m, 8);
  40099. var m3 = SIMD.Float32x4.load(m, 12);
  40100. 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));
  40101. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  40102. result.x = SIMD.Float32x4.extractLane(r, 0);
  40103. result.y = SIMD.Float32x4.extractLane(r, 1);
  40104. result.z = SIMD.Float32x4.extractLane(r, 2);
  40105. };
  40106. return SIMDVector3;
  40107. }());
  40108. var SIMDMatrix = (function () {
  40109. function SIMDMatrix() {
  40110. }
  40111. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  40112. var tm = this.m;
  40113. var om = other.m;
  40114. var m0 = SIMD.Float32x4.load(om, 0);
  40115. var m1 = SIMD.Float32x4.load(om, 4);
  40116. var m2 = SIMD.Float32x4.load(om, 8);
  40117. var m3 = SIMD.Float32x4.load(om, 12);
  40118. for (var i = 0; i < 16; i += 4) {
  40119. 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)))));
  40120. }
  40121. return this;
  40122. };
  40123. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  40124. var src = this.m;
  40125. var dest = other.m;
  40126. // Load the 4 rows
  40127. var src0 = SIMD.Float32x4.load(src, 0);
  40128. var src1 = SIMD.Float32x4.load(src, 4);
  40129. var src2 = SIMD.Float32x4.load(src, 8);
  40130. var src3 = SIMD.Float32x4.load(src, 12);
  40131. // Transpose the source matrix. Sort of. Not a true transpose operation
  40132. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  40133. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  40134. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  40135. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  40136. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  40137. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  40138. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  40139. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  40140. // This is a true transposition, but it will lead to an incorrect result
  40141. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  40142. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  40143. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40144. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40145. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  40146. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  40147. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40148. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40149. // ----
  40150. tmp1 = SIMD.Float32x4.mul(row2, row3);
  40151. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40152. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  40153. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  40154. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40155. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  40156. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  40157. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  40158. // ----
  40159. tmp1 = SIMD.Float32x4.mul(row1, row2);
  40160. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40161. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  40162. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  40163. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40164. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  40165. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  40166. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  40167. // ----
  40168. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  40169. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40170. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  40171. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  40172. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  40173. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40174. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  40175. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  40176. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  40177. // ----
  40178. tmp1 = SIMD.Float32x4.mul(row0, row1);
  40179. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40180. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40181. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  40182. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40183. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40184. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  40185. // ----
  40186. tmp1 = SIMD.Float32x4.mul(row0, row3);
  40187. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40188. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  40189. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  40190. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40191. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  40192. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  40193. // ----
  40194. tmp1 = SIMD.Float32x4.mul(row0, row2);
  40195. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40196. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  40197. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  40198. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40199. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  40200. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  40201. // Compute determinant
  40202. var det = SIMD.Float32x4.mul(row0, minor0);
  40203. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  40204. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  40205. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  40206. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  40207. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  40208. // These shuffles aren't necessary if the faulty transposition is done
  40209. // up at the top of this function.
  40210. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  40211. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  40212. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  40213. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  40214. // Compute final values by multiplying with 1/det
  40215. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  40216. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  40217. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  40218. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  40219. return this;
  40220. };
  40221. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  40222. var out = result.m;
  40223. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  40224. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  40225. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  40226. // cc.kmVec3Subtract(f, pCenter, pEye);
  40227. var f = SIMD.Float32x4.sub(center, eye);
  40228. // cc.kmVec3Normalize(f, f);
  40229. var tmp = SIMD.Float32x4.mul(f, f);
  40230. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40231. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40232. // cc.kmVec3Assign(up, pUp);
  40233. // cc.kmVec3Normalize(up, up);
  40234. tmp = SIMD.Float32x4.mul(up, up);
  40235. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40236. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40237. // cc.kmVec3Cross(s, f, up);
  40238. 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)));
  40239. // cc.kmVec3Normalize(s, s);
  40240. tmp = SIMD.Float32x4.mul(s, s);
  40241. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40242. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40243. // cc.kmVec3Cross(u, s, f);
  40244. 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)));
  40245. // cc.kmVec3Normalize(s, s);
  40246. tmp = SIMD.Float32x4.mul(s, s);
  40247. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40248. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40249. var zero = SIMD.Float32x4.splat(0.0);
  40250. s = SIMD.Float32x4.neg(s);
  40251. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  40252. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  40253. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  40254. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  40255. 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);
  40256. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  40257. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  40258. 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)))));
  40259. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  40260. 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)))));
  40261. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  40262. 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)))));
  40263. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  40264. 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)))));
  40265. };
  40266. return SIMDMatrix;
  40267. }());
  40268. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  40269. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  40270. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  40271. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  40272. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  40273. var SIMDHelper = (function () {
  40274. function SIMDHelper() {
  40275. }
  40276. Object.defineProperty(SIMDHelper, "IsEnabled", {
  40277. get: function () {
  40278. return SIMDHelper._isEnabled;
  40279. },
  40280. enumerable: true,
  40281. configurable: true
  40282. });
  40283. SIMDHelper.DisableSIMD = function () {
  40284. // Replace functions
  40285. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  40286. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  40287. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  40288. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  40289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  40290. SIMDHelper._isEnabled = false;
  40291. };
  40292. SIMDHelper.EnableSIMD = function () {
  40293. if (self.SIMD === undefined) {
  40294. return;
  40295. }
  40296. // check if polyfills needed
  40297. if (!self.Math.fround) {
  40298. self.Math.fround = (function (array) { return function (x) {
  40299. return array[0] = x, array[0];
  40300. }; })(new Float32Array(1));
  40301. }
  40302. if (!self.Math.imul) {
  40303. self.Math.imul = function (a, b) {
  40304. var ah = (a >>> 16) & 0xffff;
  40305. var al = a & 0xffff;
  40306. var bh = (b >>> 16) & 0xffff;
  40307. var bl = b & 0xffff;
  40308. // the shift by 0 fixes the sign on the high part
  40309. // the final |0 converts the unsigned value into a signed value
  40310. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  40311. };
  40312. }
  40313. // Replace functions
  40314. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  40315. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  40316. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  40317. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  40318. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  40319. SIMDHelper._isEnabled = true;
  40320. };
  40321. return SIMDHelper;
  40322. }());
  40323. SIMDHelper._isEnabled = false;
  40324. BABYLON.SIMDHelper = SIMDHelper;
  40325. })(BABYLON || (BABYLON = {}));
  40326. //# sourceMappingURL=babylon.math.SIMD.js.map
  40327. var BABYLON;
  40328. (function (BABYLON) {
  40329. /**
  40330. * This class describe a rectangle that were added to the map.
  40331. * You have access to its coordinates either in pixel or normalized (UV)
  40332. */
  40333. var PackedRect = (function () {
  40334. function PackedRect(root, parent, pos, size) {
  40335. this._pos = pos;
  40336. this._size = size;
  40337. this._root = root;
  40338. this._parent = parent;
  40339. this._contentSize = null;
  40340. this._bottomNode = null;
  40341. this._leftNode = null;
  40342. this._initialSize = null;
  40343. this._rightNode = null;
  40344. }
  40345. Object.defineProperty(PackedRect.prototype, "pos", {
  40346. /**
  40347. * @returns the position of this node into the map
  40348. */
  40349. get: function () {
  40350. return this._pos;
  40351. },
  40352. enumerable: true,
  40353. configurable: true
  40354. });
  40355. Object.defineProperty(PackedRect.prototype, "contentSize", {
  40356. /**
  40357. * @returns the size of the rectangle this node handles
  40358. */
  40359. get: function () {
  40360. return this._contentSize;
  40361. },
  40362. enumerable: true,
  40363. configurable: true
  40364. });
  40365. Object.defineProperty(PackedRect.prototype, "UVs", {
  40366. /**
  40367. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  40368. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  40369. */
  40370. get: function () {
  40371. return this.getUVsForCustomSize(this._root._size);
  40372. },
  40373. enumerable: true,
  40374. configurable: true
  40375. });
  40376. /**
  40377. * 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.
  40378. * This method will return the UVs for this part by given the custom size of what you really use
  40379. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  40380. */
  40381. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  40382. var mainWidth = this._root._size.width;
  40383. var mainHeight = this._root._size.height;
  40384. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  40385. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  40386. var uvs = new Array();
  40387. uvs.push(topLeft);
  40388. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  40389. uvs.push(rightBottom);
  40390. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  40391. return uvs;
  40392. };
  40393. /**
  40394. * Free this rectangle from the map.
  40395. * Call this method when you no longer need the rectangle to be in the map.
  40396. */
  40397. PackedRect.prototype.freeContent = function () {
  40398. if (!this.contentSize) {
  40399. return;
  40400. }
  40401. this._contentSize = null;
  40402. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  40403. this.attemptDefrag();
  40404. };
  40405. Object.defineProperty(PackedRect.prototype, "isUsed", {
  40406. get: function () {
  40407. return this._contentSize != null || this._leftNode != null;
  40408. },
  40409. enumerable: true,
  40410. configurable: true
  40411. });
  40412. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  40413. var node = this.findNode(contentSize);
  40414. // Not enough space...
  40415. if (!node) {
  40416. return null;
  40417. }
  40418. node.splitNode(contentSize);
  40419. return node;
  40420. };
  40421. PackedRect.prototype.findNode = function (size) {
  40422. var resNode = null;
  40423. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  40424. if (this.isUsed) {
  40425. if (this._leftNode) {
  40426. resNode = this._leftNode.findNode(size);
  40427. }
  40428. if (!resNode && this._rightNode) {
  40429. resNode = this._rightNode.findNode(size);
  40430. }
  40431. if (!resNode && this._bottomNode) {
  40432. resNode = this._bottomNode.findNode(size);
  40433. }
  40434. }
  40435. else if (this._initialSize) {
  40436. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  40437. resNode = this;
  40438. }
  40439. else {
  40440. return null;
  40441. }
  40442. }
  40443. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  40444. resNode = this;
  40445. }
  40446. return resNode;
  40447. };
  40448. PackedRect.prototype.splitNode = function (contentSize) {
  40449. // 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)
  40450. if (!this._contentSize && this._initialSize) {
  40451. this._contentSize = contentSize.clone();
  40452. 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));
  40453. return this._leftNode.splitNode(contentSize);
  40454. }
  40455. else {
  40456. this._contentSize = contentSize.clone();
  40457. this._initialSize = contentSize.clone();
  40458. if (contentSize.width !== this._size.width) {
  40459. 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));
  40460. }
  40461. if (contentSize.height !== this._size.height) {
  40462. 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));
  40463. }
  40464. return this;
  40465. }
  40466. };
  40467. PackedRect.prototype.attemptDefrag = function () {
  40468. if (!this.isUsed && this.isRecursiveFree) {
  40469. this.clearNode();
  40470. if (this._parent) {
  40471. this._parent.attemptDefrag();
  40472. }
  40473. }
  40474. };
  40475. PackedRect.prototype.clearNode = function () {
  40476. this._initialSize = null;
  40477. this._rightNode = null;
  40478. this._bottomNode = null;
  40479. };
  40480. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  40481. get: function () {
  40482. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  40483. },
  40484. enumerable: true,
  40485. configurable: true
  40486. });
  40487. PackedRect.prototype.evalFreeSize = function (size) {
  40488. var levelSize = 0;
  40489. if (!this.isUsed) {
  40490. if (this._initialSize) {
  40491. levelSize = this._initialSize.surface;
  40492. }
  40493. else {
  40494. levelSize = this._size.surface;
  40495. }
  40496. }
  40497. if (this._rightNode) {
  40498. levelSize += this._rightNode.evalFreeSize(0);
  40499. }
  40500. if (this._bottomNode) {
  40501. levelSize += this._bottomNode.evalFreeSize(0);
  40502. }
  40503. return levelSize + size;
  40504. };
  40505. return PackedRect;
  40506. }());
  40507. BABYLON.PackedRect = PackedRect;
  40508. /**
  40509. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  40510. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  40511. * 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.
  40512. */
  40513. var RectPackingMap = (function (_super) {
  40514. __extends(RectPackingMap, _super);
  40515. /**
  40516. * Create an instance of the object with a dimension using the given size
  40517. * @param size The dimension of the rectangle that will contain all the sub ones.
  40518. */
  40519. function RectPackingMap(size) {
  40520. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  40521. _this._root = _this;
  40522. return _this;
  40523. }
  40524. /**
  40525. * Add a rectangle, finding the best location to store it into the map
  40526. * @param size the dimension of the rectangle to store
  40527. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  40528. */
  40529. RectPackingMap.prototype.addRect = function (size) {
  40530. var node = this.findAndSplitNode(size);
  40531. return node;
  40532. };
  40533. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  40534. /**
  40535. * Return the current space free normalized between [0;1]
  40536. * @returns {}
  40537. */
  40538. get: function () {
  40539. var freeSize = 0;
  40540. freeSize = this.evalFreeSize(freeSize);
  40541. return freeSize / (this._size.width * this._size.height);
  40542. },
  40543. enumerable: true,
  40544. configurable: true
  40545. });
  40546. return RectPackingMap;
  40547. }(PackedRect));
  40548. BABYLON.RectPackingMap = RectPackingMap;
  40549. })(BABYLON || (BABYLON = {}));
  40550. //# sourceMappingURL=babylon.rectPackingMap.js.map
  40551. var BABYLON;
  40552. (function (BABYLON) {
  40553. var DynamicFloatArrayElementInfo = (function () {
  40554. function DynamicFloatArrayElementInfo() {
  40555. }
  40556. return DynamicFloatArrayElementInfo;
  40557. }());
  40558. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  40559. /**
  40560. * 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.
  40561. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  40562. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  40563. * 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.
  40564. * 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.
  40565. * 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".
  40566. */
  40567. var DynamicFloatArray = (function () {
  40568. /**
  40569. * Construct an instance of the dynamic float array
  40570. * @param stride size of one element in float (i.e. not bytes!)
  40571. * @param initialElementCount the number of available entries at construction
  40572. */
  40573. function DynamicFloatArray(stride, initialElementCount) {
  40574. this.compareValueOffset = null;
  40575. this.sortingAscending = true;
  40576. this._stride = stride;
  40577. this.buffer = new Float32Array(stride * initialElementCount);
  40578. this._lastUsed = 0;
  40579. this._firstFree = 0;
  40580. this._allEntries = new Array(initialElementCount);
  40581. this._freeEntries = new Array(initialElementCount);
  40582. for (var i = 0; i < initialElementCount; i++) {
  40583. var element = new DynamicFloatArrayElementInfo();
  40584. element.offset = i * stride;
  40585. this._allEntries[i] = element;
  40586. this._freeEntries[initialElementCount - i - 1] = element;
  40587. }
  40588. }
  40589. /**
  40590. * Allocate an element in the array.
  40591. * @return the element info instance that contains the offset into the main buffer of the element's location.
  40592. * Beware, this offset may change when you call pack()
  40593. */
  40594. DynamicFloatArray.prototype.allocElement = function () {
  40595. if (this._freeEntries.length === 0) {
  40596. this._growBuffer();
  40597. }
  40598. var el = this._freeEntries.pop();
  40599. this._lastUsed = Math.max(el.offset, this._lastUsed);
  40600. if (el.offset === this._firstFree) {
  40601. if (this._freeEntries.length > 0) {
  40602. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  40603. }
  40604. else {
  40605. this._firstFree += this._stride;
  40606. }
  40607. }
  40608. return el;
  40609. };
  40610. /**
  40611. * Free the element corresponding to the given element info
  40612. * @param elInfo the element that describe the allocated element
  40613. */
  40614. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  40615. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  40616. this._freeEntries.push(elInfo);
  40617. };
  40618. /**
  40619. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  40620. * 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().
  40621. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  40622. */
  40623. DynamicFloatArray.prototype.pack = function () {
  40624. // no free slot? no need to pack
  40625. if (this._freeEntries.length === 0) {
  40626. return this.buffer;
  40627. }
  40628. // If the buffer is already packed the last used will always be lower than the first free
  40629. // 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.
  40630. if (this._lastUsed < this._firstFree) {
  40631. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  40632. return elementsBuffer_1;
  40633. }
  40634. var s = this._stride;
  40635. // 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
  40636. var lastFree = new DynamicFloatArrayElementInfo();
  40637. lastFree.offset = this.totalElementCount * s;
  40638. this._freeEntries.push(lastFree);
  40639. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  40640. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40641. var firstFreeSlotOffset = sortedFree[0].offset;
  40642. var freeZoneSize = 1;
  40643. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  40644. var prevOffset = sortedFree[0].offset;
  40645. for (var i = 1; i < sortedFree.length; i++) {
  40646. // 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
  40647. if (firstFreeSlotOffset >= occupiedZoneSize) {
  40648. break;
  40649. }
  40650. var curFree = sortedFree[i];
  40651. var curOffset = curFree.offset;
  40652. // Compute the distance between this offset and the previous
  40653. var distance = curOffset - prevOffset;
  40654. // If the distance is the stride size, they are adjacent, it good, move to the next
  40655. if (distance === s) {
  40656. // Free zone is one element bigger
  40657. ++freeZoneSize;
  40658. // as we're about to iterate to the next, the cur becomes the previous...
  40659. prevOffset = curOffset;
  40660. continue;
  40661. }
  40662. // Distance is bigger, which means there's x element between the previous free and this one
  40663. var usedRange = (distance / s) - 1;
  40664. // Two cases the free zone is smaller than the data to move or bigger
  40665. // Copy what can fit in the free zone
  40666. var curMoveOffset = curOffset - s;
  40667. var copyCount = Math.min(freeZoneSize, usedRange);
  40668. for (var j = 0; j < copyCount; j++) {
  40669. var freeI = firstFreeSlotOffset / s;
  40670. var curI = curMoveOffset / s;
  40671. var moveEl = sortedAll[curI];
  40672. this._moveElement(moveEl, firstFreeSlotOffset);
  40673. var replacedEl = sortedAll[freeI];
  40674. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  40675. replacedEl.offset = curMoveOffset;
  40676. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  40677. sortedAll[freeI] = moveEl;
  40678. sortedAll[curI] = replacedEl;
  40679. curMoveOffset -= s;
  40680. firstFreeSlotOffset += s;
  40681. }
  40682. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  40683. if (freeZoneSize <= usedRange) {
  40684. firstFreeSlotOffset = curMoveOffset + s;
  40685. freeZoneSize = 1 + copyCount;
  40686. }
  40687. else {
  40688. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  40689. }
  40690. // as we're about to iterate to the next, the cur becomes the previous...
  40691. prevOffset = curOffset;
  40692. }
  40693. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  40694. this._lastUsed = firstFreeSlotOffset - s;
  40695. this._firstFree = firstFreeSlotOffset;
  40696. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  40697. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  40698. this._allEntries = sortedAll;
  40699. return elementsBuffer;
  40700. };
  40701. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  40702. for (var i = 0; i < this._stride; i++) {
  40703. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  40704. }
  40705. element.offset = destOffset;
  40706. };
  40707. DynamicFloatArray.prototype._growBuffer = function () {
  40708. // Allocate the new buffer with 50% more entries, copy the content of the current one
  40709. var newElCount = Math.floor(this.totalElementCount * 1.5);
  40710. var newBuffer = new Float32Array(newElCount * this._stride);
  40711. newBuffer.set(this.buffer);
  40712. var curCount = this.totalElementCount;
  40713. var addedCount = newElCount - this.totalElementCount;
  40714. for (var i = 0; i < addedCount; i++) {
  40715. var element = new DynamicFloatArrayElementInfo();
  40716. element.offset = (curCount + i) * this.stride;
  40717. this._allEntries.push(element);
  40718. this._freeEntries[addedCount - i - 1] = element;
  40719. }
  40720. this._firstFree = curCount * this.stride;
  40721. this.buffer = newBuffer;
  40722. };
  40723. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  40724. /**
  40725. * Get the total count of entries that can fit in the current buffer
  40726. * @returns the elements count
  40727. */
  40728. get: function () {
  40729. return this._allEntries.length;
  40730. },
  40731. enumerable: true,
  40732. configurable: true
  40733. });
  40734. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  40735. /**
  40736. * Get the count of free entries that can still be allocated without resizing the buffer
  40737. * @returns the free elements count
  40738. */
  40739. get: function () {
  40740. return this._freeEntries.length;
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  40746. /**
  40747. * Get the count of allocated elements
  40748. * @returns the allocated elements count
  40749. */
  40750. get: function () {
  40751. return this._allEntries.length - this._freeEntries.length;
  40752. },
  40753. enumerable: true,
  40754. configurable: true
  40755. });
  40756. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  40757. /**
  40758. * Return the size of one element in float
  40759. * @returns the size in float
  40760. */
  40761. get: function () {
  40762. return this._stride;
  40763. },
  40764. enumerable: true,
  40765. configurable: true
  40766. });
  40767. DynamicFloatArray.prototype.sort = function () {
  40768. var _this = this;
  40769. if (!this.compareValueOffset) {
  40770. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  40771. }
  40772. var count = this.usedElementCount;
  40773. // Do we have to (re)create the sort table?
  40774. if (!this._sortTable || this._sortTable.length < count) {
  40775. // 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...
  40776. var newCount = Math.min(this.totalElementCount, count * 2);
  40777. this._sortTable = new Array(newCount);
  40778. }
  40779. if (!this._sortedTable || this._sortedTable.length !== count) {
  40780. this._sortedTable = new Array(count);
  40781. }
  40782. // Because, you know...
  40783. this.pack();
  40784. //let stride = this.stride;
  40785. //for (let i = 0; i < count; i++) {
  40786. // let si = this._sortTable[i];
  40787. // if (!si) {
  40788. // si = new SortInfo();
  40789. // this._sortTable[i] = si;
  40790. // }
  40791. // si.entry = this._allEntries[i];
  40792. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  40793. // si.swapedOffset = null;
  40794. // this._sortedTable[i] = si;
  40795. //}
  40796. var curOffset = 0;
  40797. var stride = this.stride;
  40798. for (var i = 0; i < count; i++, curOffset += stride) {
  40799. var si = this._sortTable[i];
  40800. if (!si) {
  40801. si = new SortInfo();
  40802. this._sortTable[i] = si;
  40803. }
  40804. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  40805. si.offset = curOffset;
  40806. si.swapedOffset = null;
  40807. this._sortedTable[i] = si;
  40808. }
  40809. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  40810. if (this.sortingAscending) {
  40811. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  40812. }
  40813. else {
  40814. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  40815. }
  40816. var swapElements = function (src, dst) {
  40817. for (var i = 0; i < stride; i++) {
  40818. var tps = _this.buffer[dst + i];
  40819. _this.buffer[dst + i] = _this.buffer[src + i];
  40820. _this.buffer[src + i] = tps;
  40821. }
  40822. };
  40823. // 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:
  40824. // 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),
  40825. // and I still want something with a good algorithm complexity.
  40826. // 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,
  40827. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  40828. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  40829. // 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
  40830. // until we find a SortInfo object without a swapedOffset which means we got the right location
  40831. // 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
  40832. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  40833. for (var i = 0; i < count; i++) {
  40834. // Get the element to move
  40835. var sourceSI = this._sortedTable[i];
  40836. var destSI = this._sortTable[i];
  40837. var sourceOff = sourceSI.offset;
  40838. // If the source changed location, find the new one
  40839. if (sourceSI.swapedOffset) {
  40840. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  40841. var curSI = sourceSI;
  40842. while (curSI.swapedOffset) {
  40843. curSI = this._sortTable[curSI.swapedOffset / stride];
  40844. }
  40845. // Finally get the right location
  40846. sourceOff = curSI.offset;
  40847. }
  40848. // Tag the element being replaced with its new location
  40849. destSI.swapedOffset = sourceOff;
  40850. // Swap elements (only if needed)
  40851. if (sourceOff !== destSI.offset) {
  40852. swapElements(sourceOff, destSI.offset);
  40853. }
  40854. // Update the offset in the corresponding DFAE
  40855. //sourceSI.entry.offset = destSI.entry.offset;
  40856. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  40857. }
  40858. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40859. return true;
  40860. };
  40861. return DynamicFloatArray;
  40862. }());
  40863. BABYLON.DynamicFloatArray = DynamicFloatArray;
  40864. var SortInfo = (function () {
  40865. function SortInfo() {
  40866. this.compareData = this.offset = this.swapedOffset = null;
  40867. }
  40868. return SortInfo;
  40869. }());
  40870. })(BABYLON || (BABYLON = {}));
  40871. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  40872. var BABYLON;
  40873. (function (BABYLON) {
  40874. var MapTexture = (function (_super) {
  40875. __extends(MapTexture, _super);
  40876. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40878. if (useMipMap === void 0) { useMipMap = false; }
  40879. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40880. _this.name = name;
  40881. _this._size = size;
  40882. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40883. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40884. // Create the rectPackMap that will allocate portion of the texture
  40885. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40886. // Create the texture that will store the content
  40887. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40888. return _this;
  40889. }
  40890. /**
  40891. * Allocate a rectangle of a given size in the texture map
  40892. * @param size the size of the rectangle to allocation
  40893. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40894. */
  40895. MapTexture.prototype.allocateRect = function (size) {
  40896. return this._rectPackingMap.addRect(size);
  40897. };
  40898. /**
  40899. * Free a given rectangle from the texture map
  40900. * @param rectInfo the instance corresponding to the rect to free.
  40901. */
  40902. MapTexture.prototype.freeRect = function (rectInfo) {
  40903. if (rectInfo) {
  40904. rectInfo.freeContent();
  40905. }
  40906. };
  40907. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40908. /**
  40909. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40910. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40911. * @returns {}
  40912. */
  40913. get: function () {
  40914. return this._rectPackingMap.freeSpace;
  40915. },
  40916. enumerable: true,
  40917. configurable: true
  40918. });
  40919. /**
  40920. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40921. * 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.
  40922. * Don't forget to call unbindTexture when you're done rendering
  40923. * @param rect the zone to render to
  40924. * @param clear true to clear the portion's color/depth data
  40925. */
  40926. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40927. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40928. };
  40929. /**
  40930. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40931. * 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.
  40932. * Don't forget to call unbindTexture when you're done rendering
  40933. * @param pos the position into the texture
  40934. * @param size the portion to fit the clip space to
  40935. * @param clear true to clear the portion's color/depth data
  40936. */
  40937. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40938. var engine = this.getScene().getEngine();
  40939. engine.bindFramebuffer(this._texture);
  40940. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40941. if (clear) {
  40942. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40943. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40944. }
  40945. };
  40946. /**
  40947. * Unbind the texture map from the rendering engine.
  40948. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40949. * @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.
  40950. */
  40951. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40952. // Dump ?
  40953. if (dumpForDebug) {
  40954. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40955. }
  40956. var engine = this.getScene().getEngine();
  40957. if (this._replacedViewport) {
  40958. engine.setViewport(this._replacedViewport);
  40959. this._replacedViewport = null;
  40960. }
  40961. engine.unBindFramebuffer(this._texture);
  40962. };
  40963. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40964. get: function () {
  40965. return false;
  40966. },
  40967. enumerable: true,
  40968. configurable: true
  40969. });
  40970. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40971. // Anyway, there's not much point to use this method for this kind of texture I guess
  40972. MapTexture.prototype.clone = function () {
  40973. return null;
  40974. };
  40975. return MapTexture;
  40976. }(BABYLON.Texture));
  40977. BABYLON.MapTexture = MapTexture;
  40978. })(BABYLON || (BABYLON = {}));
  40979. //# sourceMappingURL=babylon.mapTexture.js.map
  40980. var BABYLON;
  40981. (function (BABYLON) {
  40982. var ShaderMaterial = (function (_super) {
  40983. __extends(ShaderMaterial, _super);
  40984. function ShaderMaterial(name, scene, shaderPath, options) {
  40985. var _this = _super.call(this, name, scene) || this;
  40986. _this._textures = {};
  40987. _this._textureArrays = {};
  40988. _this._floats = {};
  40989. _this._floatsArrays = {};
  40990. _this._colors3 = {};
  40991. _this._colors4 = {};
  40992. _this._vectors2 = {};
  40993. _this._vectors3 = {};
  40994. _this._vectors4 = {};
  40995. _this._matrices = {};
  40996. _this._matrices3x3 = {};
  40997. _this._matrices2x2 = {};
  40998. _this._vectors3Arrays = {};
  40999. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41000. _this._shaderPath = shaderPath;
  41001. options.needAlphaBlending = options.needAlphaBlending || false;
  41002. options.needAlphaTesting = options.needAlphaTesting || false;
  41003. options.attributes = options.attributes || ["position", "normal", "uv"];
  41004. options.uniforms = options.uniforms || ["worldViewProjection"];
  41005. options.samplers = options.samplers || [];
  41006. options.defines = options.defines || [];
  41007. _this._options = options;
  41008. return _this;
  41009. }
  41010. ShaderMaterial.prototype.getClassName = function () {
  41011. return "ShaderMaterial";
  41012. };
  41013. ShaderMaterial.prototype.needAlphaBlending = function () {
  41014. return this._options.needAlphaBlending;
  41015. };
  41016. ShaderMaterial.prototype.needAlphaTesting = function () {
  41017. return this._options.needAlphaTesting;
  41018. };
  41019. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41020. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41021. this._options.uniforms.push(uniformName);
  41022. }
  41023. };
  41024. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41025. if (this._options.samplers.indexOf(name) === -1) {
  41026. this._options.samplers.push(name);
  41027. }
  41028. this._textures[name] = texture;
  41029. return this;
  41030. };
  41031. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41032. if (this._options.samplers.indexOf(name) === -1) {
  41033. this._options.samplers.push(name);
  41034. }
  41035. this._checkUniform(name);
  41036. this._textureArrays[name] = textures;
  41037. return this;
  41038. };
  41039. ShaderMaterial.prototype.setFloat = function (name, value) {
  41040. this._checkUniform(name);
  41041. this._floats[name] = value;
  41042. return this;
  41043. };
  41044. ShaderMaterial.prototype.setFloats = function (name, value) {
  41045. this._checkUniform(name);
  41046. this._floatsArrays[name] = value;
  41047. return this;
  41048. };
  41049. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41050. this._checkUniform(name);
  41051. this._colors3[name] = value;
  41052. return this;
  41053. };
  41054. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41055. this._checkUniform(name);
  41056. this._colors4[name] = value;
  41057. return this;
  41058. };
  41059. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41060. this._checkUniform(name);
  41061. this._vectors2[name] = value;
  41062. return this;
  41063. };
  41064. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41065. this._checkUniform(name);
  41066. this._vectors3[name] = value;
  41067. return this;
  41068. };
  41069. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41070. this._checkUniform(name);
  41071. this._vectors4[name] = value;
  41072. return this;
  41073. };
  41074. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41075. this._checkUniform(name);
  41076. this._matrices[name] = value;
  41077. return this;
  41078. };
  41079. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41080. this._checkUniform(name);
  41081. this._matrices3x3[name] = value;
  41082. return this;
  41083. };
  41084. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41085. this._checkUniform(name);
  41086. this._matrices2x2[name] = value;
  41087. return this;
  41088. };
  41089. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41090. this._checkUniform(name);
  41091. this._vectors3Arrays[name] = value;
  41092. return this;
  41093. };
  41094. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41095. if (!mesh) {
  41096. return true;
  41097. }
  41098. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41099. return false;
  41100. }
  41101. return false;
  41102. };
  41103. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41104. var scene = this.getScene();
  41105. var engine = scene.getEngine();
  41106. if (!this.checkReadyOnEveryCall) {
  41107. if (this._renderId === scene.getRenderId()) {
  41108. if (this._checkCache(scene, mesh, useInstances)) {
  41109. return true;
  41110. }
  41111. }
  41112. }
  41113. // Instances
  41114. var defines = [];
  41115. var fallbacks = new BABYLON.EffectFallbacks();
  41116. if (useInstances) {
  41117. defines.push("#define INSTANCES");
  41118. }
  41119. for (var index = 0; index < this._options.defines.length; index++) {
  41120. defines.push(this._options.defines[index]);
  41121. }
  41122. // Bones
  41123. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41124. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41125. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41126. fallbacks.addCPUSkinningFallback(0, mesh);
  41127. }
  41128. // Alpha test
  41129. if (engine.getAlphaTesting()) {
  41130. defines.push("#define ALPHATEST");
  41131. }
  41132. var previousEffect = this._effect;
  41133. var join = defines.join("\n");
  41134. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  41135. if (!this._effect.isReady()) {
  41136. return false;
  41137. }
  41138. if (previousEffect !== this._effect) {
  41139. scene.resetCachedMaterial();
  41140. }
  41141. this._renderId = scene.getRenderId();
  41142. return true;
  41143. };
  41144. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41145. var scene = this.getScene();
  41146. if (this._options.uniforms.indexOf("world") !== -1) {
  41147. this._effect.setMatrix("world", world);
  41148. }
  41149. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41150. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41151. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41152. }
  41153. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41154. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41155. }
  41156. };
  41157. ShaderMaterial.prototype.bind = function (world, mesh) {
  41158. // Std values
  41159. this.bindOnlyWorldMatrix(world);
  41160. if (this.getScene().getCachedMaterial() !== this) {
  41161. if (this._options.uniforms.indexOf("view") !== -1) {
  41162. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41163. }
  41164. if (this._options.uniforms.indexOf("projection") !== -1) {
  41165. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41166. }
  41167. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41168. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41169. }
  41170. // Bones
  41171. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41172. var name;
  41173. // Texture
  41174. for (name in this._textures) {
  41175. this._effect.setTexture(name, this._textures[name]);
  41176. }
  41177. // Texture arrays
  41178. for (name in this._textureArrays) {
  41179. this._effect.setTextureArray(name, this._textureArrays[name]);
  41180. }
  41181. // Float
  41182. for (name in this._floats) {
  41183. this._effect.setFloat(name, this._floats[name]);
  41184. }
  41185. // Float s
  41186. for (name in this._floatsArrays) {
  41187. this._effect.setArray(name, this._floatsArrays[name]);
  41188. }
  41189. // Color3
  41190. for (name in this._colors3) {
  41191. this._effect.setColor3(name, this._colors3[name]);
  41192. }
  41193. // Color4
  41194. for (name in this._colors4) {
  41195. var color = this._colors4[name];
  41196. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41197. }
  41198. // Vector2
  41199. for (name in this._vectors2) {
  41200. this._effect.setVector2(name, this._vectors2[name]);
  41201. }
  41202. // Vector3
  41203. for (name in this._vectors3) {
  41204. this._effect.setVector3(name, this._vectors3[name]);
  41205. }
  41206. // Vector4
  41207. for (name in this._vectors4) {
  41208. this._effect.setVector4(name, this._vectors4[name]);
  41209. }
  41210. // Matrix
  41211. for (name in this._matrices) {
  41212. this._effect.setMatrix(name, this._matrices[name]);
  41213. }
  41214. // Matrix 3x3
  41215. for (name in this._matrices3x3) {
  41216. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41217. }
  41218. // Matrix 2x2
  41219. for (name in this._matrices2x2) {
  41220. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41221. }
  41222. // Vector3Array
  41223. for (name in this._vectors3Arrays) {
  41224. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41225. }
  41226. }
  41227. _super.prototype.bind.call(this, world, mesh);
  41228. };
  41229. ShaderMaterial.prototype.clone = function (name) {
  41230. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41231. return newShaderMaterial;
  41232. };
  41233. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41234. if (forceDisposeTextures) {
  41235. var name;
  41236. for (name in this._textures) {
  41237. this._textures[name].dispose();
  41238. }
  41239. for (name in this._textureArrays) {
  41240. var array = this._textureArrays[name];
  41241. for (var index = 0; index < array.length; index++) {
  41242. array[index].dispose();
  41243. }
  41244. }
  41245. }
  41246. this._textures = {};
  41247. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41248. };
  41249. ShaderMaterial.prototype.serialize = function () {
  41250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41251. serializationObject.customType = "BABYLON.ShaderMaterial";
  41252. serializationObject.options = this._options;
  41253. serializationObject.shaderPath = this._shaderPath;
  41254. var name;
  41255. // Texture
  41256. serializationObject.textures = {};
  41257. for (name in this._textures) {
  41258. serializationObject.textures[name] = this._textures[name].serialize();
  41259. }
  41260. // Texture arrays
  41261. serializationObject.textureArrays = {};
  41262. for (name in this._textureArrays) {
  41263. serializationObject.textureArrays[name] = [];
  41264. var array = this._textureArrays[name];
  41265. for (var index = 0; index < array.length; index++) {
  41266. serializationObject.textureArrays[name].push(array[index].serialize());
  41267. }
  41268. }
  41269. // Float
  41270. serializationObject.floats = {};
  41271. for (name in this._floats) {
  41272. serializationObject.floats[name] = this._floats[name];
  41273. }
  41274. // Float s
  41275. serializationObject.floatArrays = {};
  41276. for (name in this._floatsArrays) {
  41277. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41278. }
  41279. // Color3
  41280. serializationObject.colors3 = {};
  41281. for (name in this._colors3) {
  41282. serializationObject.colors3[name] = this._colors3[name].asArray();
  41283. }
  41284. // Color4
  41285. serializationObject.colors4 = {};
  41286. for (name in this._colors4) {
  41287. serializationObject.colors4[name] = this._colors4[name].asArray();
  41288. }
  41289. // Vector2
  41290. serializationObject.vectors2 = {};
  41291. for (name in this._vectors2) {
  41292. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41293. }
  41294. // Vector3
  41295. serializationObject.vectors3 = {};
  41296. for (name in this._vectors3) {
  41297. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41298. }
  41299. // Vector4
  41300. serializationObject.vectors4 = {};
  41301. for (name in this._vectors4) {
  41302. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41303. }
  41304. // Matrix
  41305. serializationObject.matrices = {};
  41306. for (name in this._matrices) {
  41307. serializationObject.matrices[name] = this._matrices[name].asArray();
  41308. }
  41309. // Matrix 3x3
  41310. serializationObject.matrices3x3 = {};
  41311. for (name in this._matrices3x3) {
  41312. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41313. }
  41314. // Matrix 2x2
  41315. serializationObject.matrices2x2 = {};
  41316. for (name in this._matrices2x2) {
  41317. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41318. }
  41319. // Vector3Array
  41320. serializationObject.vectors3Arrays = {};
  41321. for (name in this._vectors3Arrays) {
  41322. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41323. }
  41324. return serializationObject;
  41325. };
  41326. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41327. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41328. var name;
  41329. // Texture
  41330. for (name in source.textures) {
  41331. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41332. }
  41333. // Texture arrays
  41334. for (name in source.textureArrays) {
  41335. var array = source.textureArrays[name];
  41336. var textureArray = new Array();
  41337. for (var index = 0; index < array.length; index++) {
  41338. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41339. }
  41340. material.setTextureArray(name, textureArray);
  41341. }
  41342. // Float
  41343. for (name in source.floats) {
  41344. material.setFloat(name, source.floats[name]);
  41345. }
  41346. // Float s
  41347. for (name in source.floatsArrays) {
  41348. material.setFloats(name, source.floatsArrays[name]);
  41349. }
  41350. // Color3
  41351. for (name in source.colors3) {
  41352. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41353. }
  41354. // Color4
  41355. for (name in source.colors4) {
  41356. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41357. }
  41358. // Vector2
  41359. for (name in source.vectors2) {
  41360. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41361. }
  41362. // Vector3
  41363. for (name in source.vectors3) {
  41364. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41365. }
  41366. // Vector4
  41367. for (name in source.vectors4) {
  41368. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41369. }
  41370. // Matrix
  41371. for (name in source.matrices) {
  41372. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41373. }
  41374. // Matrix 3x3
  41375. for (name in source.matrices3x3) {
  41376. material.setMatrix3x3(name, source.matrices3x3[name]);
  41377. }
  41378. // Matrix 2x2
  41379. for (name in source.matrices2x2) {
  41380. material.setMatrix2x2(name, source.matrices2x2[name]);
  41381. }
  41382. // Vector3Array
  41383. for (name in source.vectors3Arrays) {
  41384. material.setArray3(name, source.vectors3Arrays[name]);
  41385. }
  41386. return material;
  41387. };
  41388. return ShaderMaterial;
  41389. }(BABYLON.Material));
  41390. BABYLON.ShaderMaterial = ShaderMaterial;
  41391. })(BABYLON || (BABYLON = {}));
  41392. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41393. var BABYLON;
  41394. (function (BABYLON) {
  41395. var Internals;
  41396. (function (Internals) {
  41397. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41398. // All values and structures referenced from:
  41399. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41400. var DDS_MAGIC = 0x20534444;
  41401. 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;
  41402. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41403. 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;
  41404. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41405. function FourCCToInt32(value) {
  41406. return value.charCodeAt(0) +
  41407. (value.charCodeAt(1) << 8) +
  41408. (value.charCodeAt(2) << 16) +
  41409. (value.charCodeAt(3) << 24);
  41410. }
  41411. function Int32ToFourCC(value) {
  41412. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41413. }
  41414. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41415. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41416. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41417. var headerLengthInt = 31; // The header length in 32 bit ints
  41418. // Offsets into the header array
  41419. var off_magic = 0;
  41420. var off_size = 1;
  41421. var off_flags = 2;
  41422. var off_height = 3;
  41423. var off_width = 4;
  41424. var off_mipmapCount = 7;
  41425. var off_pfFlags = 20;
  41426. var off_pfFourCC = 21;
  41427. var off_RGBbpp = 22;
  41428. var off_RMask = 23;
  41429. var off_GMask = 24;
  41430. var off_BMask = 25;
  41431. var off_AMask = 26;
  41432. var off_caps1 = 27;
  41433. var off_caps2 = 28;
  41434. ;
  41435. var DDSTools = (function () {
  41436. function DDSTools() {
  41437. }
  41438. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41439. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41440. var mipmapCount = 1;
  41441. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41442. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41443. }
  41444. return {
  41445. width: header[off_width],
  41446. height: header[off_height],
  41447. mipmapCount: mipmapCount,
  41448. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41449. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41450. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41451. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41452. };
  41453. };
  41454. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41455. var byteArray = new Uint8Array(dataLength);
  41456. var srcData = new Uint8Array(arrayBuffer);
  41457. var index = 0;
  41458. for (var y = height - 1; y >= 0; y--) {
  41459. for (var x = 0; x < width; x++) {
  41460. var srcPos = dataOffset + (x + y * width) * 4;
  41461. byteArray[index + 2] = srcData[srcPos];
  41462. byteArray[index + 1] = srcData[srcPos + 1];
  41463. byteArray[index] = srcData[srcPos + 2];
  41464. byteArray[index + 3] = srcData[srcPos + 3];
  41465. index += 4;
  41466. }
  41467. }
  41468. return byteArray;
  41469. };
  41470. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41471. var byteArray = new Uint8Array(dataLength);
  41472. var srcData = new Uint8Array(arrayBuffer);
  41473. var index = 0;
  41474. for (var y = height - 1; y >= 0; y--) {
  41475. for (var x = 0; x < width; x++) {
  41476. var srcPos = dataOffset + (x + y * width) * 3;
  41477. byteArray[index + 2] = srcData[srcPos];
  41478. byteArray[index + 1] = srcData[srcPos + 1];
  41479. byteArray[index] = srcData[srcPos + 2];
  41480. index += 3;
  41481. }
  41482. }
  41483. return byteArray;
  41484. };
  41485. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41486. var byteArray = new Uint8Array(dataLength);
  41487. var srcData = new Uint8Array(arrayBuffer);
  41488. var index = 0;
  41489. for (var y = height - 1; y >= 0; y--) {
  41490. for (var x = 0; x < width; x++) {
  41491. var srcPos = dataOffset + (x + y * width);
  41492. byteArray[index] = srcData[srcPos];
  41493. index++;
  41494. }
  41495. }
  41496. return byteArray;
  41497. };
  41498. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41499. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41500. if (header[off_magic] != DDS_MAGIC) {
  41501. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41502. return;
  41503. }
  41504. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41505. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41506. return;
  41507. }
  41508. if (info.isFourCC) {
  41509. fourCC = header[off_pfFourCC];
  41510. switch (fourCC) {
  41511. case FOURCC_DXT1:
  41512. blockBytes = 8;
  41513. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41514. break;
  41515. case FOURCC_DXT3:
  41516. blockBytes = 16;
  41517. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41518. break;
  41519. case FOURCC_DXT5:
  41520. blockBytes = 16;
  41521. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41522. break;
  41523. default:
  41524. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41525. return;
  41526. }
  41527. }
  41528. mipmapCount = 1;
  41529. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41530. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41531. }
  41532. var bpp = header[off_RGBbpp];
  41533. for (var face = 0; face < faces; face++) {
  41534. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41535. width = header[off_width];
  41536. height = header[off_height];
  41537. dataOffset = header[off_size] + 4;
  41538. for (i = 0; i < mipmapCount; ++i) {
  41539. if (info.isRGB) {
  41540. if (bpp === 24) {
  41541. dataLength = width * height * 3;
  41542. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41543. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41544. }
  41545. else {
  41546. dataLength = width * height * 4;
  41547. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41548. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41549. }
  41550. }
  41551. else if (info.isLuminance) {
  41552. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41553. var unpaddedRowSize = width;
  41554. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41555. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41556. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41557. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41558. }
  41559. else {
  41560. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41561. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41562. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41563. }
  41564. dataOffset += dataLength;
  41565. width *= 0.5;
  41566. height *= 0.5;
  41567. width = Math.max(1.0, width);
  41568. height = Math.max(1.0, height);
  41569. }
  41570. }
  41571. };
  41572. return DDSTools;
  41573. }());
  41574. Internals.DDSTools = DDSTools;
  41575. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41576. })(BABYLON || (BABYLON = {}));
  41577. //# sourceMappingURL=babylon.tools.dds.js.map
  41578. var BABYLON;
  41579. (function (BABYLON) {
  41580. var Internals;
  41581. (function (Internals) {
  41582. /**
  41583. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  41584. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  41585. */
  41586. var KhronosTextureContainer = (function () {
  41587. /**
  41588. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  41589. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  41590. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  41591. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  41592. */
  41593. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  41594. this.arrayBuffer = arrayBuffer;
  41595. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  41596. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  41597. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  41598. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  41599. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  41600. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  41601. BABYLON.Tools.Error("texture missing KTX identifier");
  41602. return;
  41603. }
  41604. // load the reset of the header in native 32 bit int
  41605. var header = new Int32Array(this.arrayBuffer, 12, 13);
  41606. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  41607. var oppositeEndianess = header[0] === 0x01020304;
  41608. // read all the header elements in order they exist in the file, without modification (sans endainness)
  41609. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  41610. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  41611. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  41612. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  41613. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  41614. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  41615. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  41616. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  41617. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  41618. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  41619. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  41620. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  41621. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  41622. if (this.glType !== 0) {
  41623. BABYLON.Tools.Error("only compressed formats currently supported");
  41624. return;
  41625. }
  41626. else {
  41627. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  41628. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  41629. }
  41630. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  41631. BABYLON.Tools.Error("only 2D textures currently supported");
  41632. return;
  41633. }
  41634. if (this.numberOfArrayElements !== 0) {
  41635. BABYLON.Tools.Error("texture arrays not currently supported");
  41636. return;
  41637. }
  41638. if (this.numberOfFaces !== facesExpected) {
  41639. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  41640. return;
  41641. }
  41642. // we now have a completely validated file, so could use existence of loadType as success
  41643. // would need to make this more elaborate & adjust checks above to support more than one load type
  41644. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  41645. }
  41646. // not as fast hardware based, but will probably never need to use
  41647. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  41648. return ((val & 0xFF) << 24)
  41649. | ((val & 0xFF00) << 8)
  41650. | ((val >> 8) & 0xFF00)
  41651. | ((val >> 24) & 0xFF);
  41652. };
  41653. /**
  41654. * It is assumed that the texture has already been created & is currently bound
  41655. */
  41656. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  41657. switch (this.loadType) {
  41658. case KhronosTextureContainer.COMPRESSED_2D:
  41659. this._upload2DCompressedLevels(gl, loadMipmaps);
  41660. break;
  41661. case KhronosTextureContainer.TEX_2D:
  41662. case KhronosTextureContainer.COMPRESSED_3D:
  41663. case KhronosTextureContainer.TEX_3D:
  41664. }
  41665. };
  41666. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  41667. // initialize width & height for level 1
  41668. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  41669. var width = this.pixelWidth;
  41670. var height = this.pixelHeight;
  41671. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  41672. for (var level = 0; level < mipmapCount; level++) {
  41673. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  41674. for (var face = 0; face < this.numberOfFaces; face++) {
  41675. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41676. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  41677. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  41678. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  41679. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  41680. }
  41681. width = Math.max(1.0, width * 0.5);
  41682. height = Math.max(1.0, height * 0.5);
  41683. }
  41684. };
  41685. return KhronosTextureContainer;
  41686. }());
  41687. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  41688. // load types
  41689. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  41690. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  41691. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  41692. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  41693. Internals.KhronosTextureContainer = KhronosTextureContainer;
  41694. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41695. })(BABYLON || (BABYLON = {}));
  41696. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  41697. var BABYLON;
  41698. (function (BABYLON) {
  41699. var CannonJSPlugin = (function () {
  41700. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41701. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41702. if (iterations === void 0) { iterations = 10; }
  41703. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41704. this.name = "CannonJSPlugin";
  41705. this._physicsMaterials = [];
  41706. this._fixedTimeStep = 1 / 60;
  41707. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41708. this._currentCollisionGroup = 2;
  41709. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41710. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41711. this._tmpPosition = BABYLON.Vector3.Zero();
  41712. this._tmpQuaternion = new BABYLON.Quaternion();
  41713. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41714. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41715. this._tmpUnityRotation = new BABYLON.Quaternion();
  41716. if (!this.isSupported()) {
  41717. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41718. return;
  41719. }
  41720. this.world = new CANNON.World();
  41721. this.world.broadphase = new CANNON.NaiveBroadphase();
  41722. this.world.solver.iterations = iterations;
  41723. }
  41724. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41725. this.world.gravity.copy(gravity);
  41726. };
  41727. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41728. this._fixedTimeStep = timeStep;
  41729. };
  41730. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41731. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41732. };
  41733. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41734. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41735. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41736. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41737. };
  41738. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41739. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41740. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41741. impostor.physicsBody.applyForce(impulse, worldPoint);
  41742. };
  41743. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41744. //parent-child relationship. Does this impostor has a parent impostor?
  41745. if (impostor.parent) {
  41746. if (impostor.physicsBody) {
  41747. this.removePhysicsBody(impostor);
  41748. //TODO is that needed?
  41749. impostor.forceUpdate();
  41750. }
  41751. return;
  41752. }
  41753. //should a new body be created for this impostor?
  41754. if (impostor.isBodyInitRequired()) {
  41755. var shape = this._createShape(impostor);
  41756. //unregister events, if body is being changed
  41757. var oldBody = impostor.physicsBody;
  41758. if (oldBody) {
  41759. this.removePhysicsBody(impostor);
  41760. }
  41761. //create the body and material
  41762. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41763. var bodyCreationObject = {
  41764. mass: impostor.getParam("mass"),
  41765. material: material
  41766. };
  41767. // A simple extend, in case native options were used.
  41768. var nativeOptions = impostor.getParam("nativeOptions");
  41769. for (var key in nativeOptions) {
  41770. if (nativeOptions.hasOwnProperty(key)) {
  41771. bodyCreationObject[key] = nativeOptions[key];
  41772. }
  41773. }
  41774. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41775. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41776. this.world.addEventListener("preStep", impostor.beforeStep);
  41777. this.world.addEventListener("postStep", impostor.afterStep);
  41778. impostor.physicsBody.addShape(shape);
  41779. this.world.add(impostor.physicsBody);
  41780. //try to keep the body moving in the right direction by taking old properties.
  41781. //Should be tested!
  41782. if (oldBody) {
  41783. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41784. impostor.physicsBody[param].copy(oldBody[param]);
  41785. });
  41786. }
  41787. this._processChildMeshes(impostor);
  41788. }
  41789. //now update the body's transformation
  41790. this._updatePhysicsBodyTransformation(impostor);
  41791. };
  41792. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41793. var _this = this;
  41794. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41795. if (meshChildren.length) {
  41796. var processMesh = function (localPosition, mesh) {
  41797. var childImpostor = mesh.getPhysicsImpostor();
  41798. if (childImpostor) {
  41799. var parent = childImpostor.parent;
  41800. if (parent !== mainImpostor) {
  41801. var localPosition = mesh.position;
  41802. if (childImpostor.physicsBody) {
  41803. _this.removePhysicsBody(childImpostor);
  41804. childImpostor.physicsBody = null;
  41805. }
  41806. childImpostor.parent = mainImpostor;
  41807. childImpostor.resetUpdateFlags();
  41808. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41809. //Add the mass of the children.
  41810. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41811. }
  41812. }
  41813. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41814. };
  41815. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41816. }
  41817. };
  41818. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41819. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41820. this.world.removeEventListener("preStep", impostor.beforeStep);
  41821. this.world.removeEventListener("postStep", impostor.afterStep);
  41822. this.world.remove(impostor.physicsBody);
  41823. };
  41824. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41825. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41826. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41827. if (!mainBody || !connectedBody) {
  41828. return;
  41829. }
  41830. var constraint;
  41831. var jointData = impostorJoint.joint.jointData;
  41832. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41833. var constraintData = {
  41834. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41835. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41836. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41837. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41838. maxForce: jointData.nativeParams.maxForce,
  41839. collideConnected: !!jointData.collision
  41840. };
  41841. switch (impostorJoint.joint.type) {
  41842. case BABYLON.PhysicsJoint.HingeJoint:
  41843. case BABYLON.PhysicsJoint.Hinge2Joint:
  41844. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41845. break;
  41846. case BABYLON.PhysicsJoint.DistanceJoint:
  41847. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41848. break;
  41849. case BABYLON.PhysicsJoint.SpringJoint:
  41850. var springData = jointData;
  41851. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41852. restLength: springData.length,
  41853. stiffness: springData.stiffness,
  41854. damping: springData.damping,
  41855. localAnchorA: constraintData.pivotA,
  41856. localAnchorB: constraintData.pivotB
  41857. });
  41858. break;
  41859. case BABYLON.PhysicsJoint.LockJoint:
  41860. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41861. break;
  41862. case BABYLON.PhysicsJoint.PointToPointJoint:
  41863. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41864. default:
  41865. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41866. break;
  41867. }
  41868. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41869. constraint.collideConnected = !!jointData.collision;
  41870. impostorJoint.joint.physicsJoint = constraint;
  41871. //don't add spring as constraint, as it is not one.
  41872. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41873. this.world.addConstraint(constraint);
  41874. }
  41875. else {
  41876. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41877. constraint.applyForce();
  41878. });
  41879. }
  41880. };
  41881. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41882. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41883. };
  41884. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41885. var index;
  41886. var mat;
  41887. for (index = 0; index < this._physicsMaterials.length; index++) {
  41888. mat = this._physicsMaterials[index];
  41889. if (mat.friction === friction && mat.restitution === restitution) {
  41890. return mat;
  41891. }
  41892. }
  41893. var currentMat = new CANNON.Material(name);
  41894. currentMat.friction = friction;
  41895. currentMat.restitution = restitution;
  41896. this._physicsMaterials.push(currentMat);
  41897. return currentMat;
  41898. };
  41899. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41900. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41901. };
  41902. CannonJSPlugin.prototype._createShape = function (impostor) {
  41903. var object = impostor.object;
  41904. var returnValue;
  41905. var extendSize = impostor.getObjectExtendSize();
  41906. switch (impostor.type) {
  41907. case BABYLON.PhysicsEngine.SphereImpostor:
  41908. var radiusX = extendSize.x;
  41909. var radiusY = extendSize.y;
  41910. var radiusZ = extendSize.z;
  41911. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41912. break;
  41913. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41914. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41915. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41916. break;
  41917. case BABYLON.PhysicsImpostor.BoxImpostor:
  41918. var box = extendSize.scale(0.5);
  41919. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41920. break;
  41921. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41922. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41923. returnValue = new CANNON.Plane();
  41924. break;
  41925. case BABYLON.PhysicsImpostor.MeshImpostor:
  41926. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41927. var rawFaces = object.getIndices ? object.getIndices() : [];
  41928. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41929. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41930. break;
  41931. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41932. returnValue = this._createHeightmap(object);
  41933. break;
  41934. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41935. returnValue = new CANNON.Particle();
  41936. break;
  41937. }
  41938. return returnValue;
  41939. };
  41940. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41941. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41942. var matrix = [];
  41943. //For now pointDepth will not be used and will be automatically calculated.
  41944. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41945. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41946. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41947. var elementSize = dim * 2 / arraySize;
  41948. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41949. for (var i = 0; i < pos.length; i = i + 3) {
  41950. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41951. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41952. var y = pos[i + 1] + minY;
  41953. if (!matrix[x]) {
  41954. matrix[x] = [];
  41955. }
  41956. if (!matrix[x][z]) {
  41957. matrix[x][z] = y;
  41958. }
  41959. matrix[x][z] = Math.max(y, matrix[x][z]);
  41960. }
  41961. for (var x = 0; x <= arraySize; ++x) {
  41962. if (!matrix[x]) {
  41963. var loc = 1;
  41964. while (!matrix[(x + loc) % arraySize]) {
  41965. loc++;
  41966. }
  41967. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41968. }
  41969. for (var z = 0; z <= arraySize; ++z) {
  41970. if (!matrix[x][z]) {
  41971. var loc = 1;
  41972. var newValue;
  41973. while (newValue === undefined) {
  41974. newValue = matrix[x][(z + loc++) % arraySize];
  41975. }
  41976. matrix[x][z] = newValue;
  41977. }
  41978. }
  41979. }
  41980. var shape = new CANNON.Heightfield(matrix, {
  41981. elementSize: elementSize
  41982. });
  41983. //For future reference, needed for body transformation
  41984. shape.minY = minY;
  41985. return shape;
  41986. };
  41987. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41988. var object = impostor.object;
  41989. //make sure it is updated...
  41990. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41991. // The delta between the mesh position and the mesh bounding box center
  41992. var center = impostor.getObjectCenter();
  41993. var extendSize = impostor.getObjectExtendSize();
  41994. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41995. this._tmpPosition.copyFrom(center);
  41996. var quaternion = object.rotationQuaternion;
  41997. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41998. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41999. //-90 DEG in X, precalculated
  42000. quaternion = quaternion.multiply(this._minus90X);
  42001. //Invert! (Precalculated, 90 deg in X)
  42002. //No need to clone. this will never change.
  42003. impostor.setDeltaRotation(this._plus90X);
  42004. }
  42005. //If it is a heightfield, if should be centered.
  42006. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  42007. var mesh = object;
  42008. //calculate the correct body position:
  42009. var rotationQuaternion = mesh.rotationQuaternion;
  42010. mesh.rotationQuaternion = this._tmpUnityRotation;
  42011. mesh.computeWorldMatrix(true);
  42012. //get original center with no rotation
  42013. var c = center.clone();
  42014. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  42015. //rotation is back
  42016. mesh.rotationQuaternion = rotationQuaternion;
  42017. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  42018. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  42019. mesh.setPivotMatrix(p);
  42020. mesh.computeWorldMatrix(true);
  42021. //calculate the translation
  42022. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  42023. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  42024. //add it inverted to the delta
  42025. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  42026. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  42027. mesh.setPivotMatrix(oldPivot);
  42028. mesh.computeWorldMatrix(true);
  42029. }
  42030. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  42031. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  42032. this._tmpPosition.copyFrom(object.position);
  42033. }
  42034. impostor.setDeltaPosition(this._tmpDeltaPosition);
  42035. //Now update the impostor object
  42036. impostor.physicsBody.position.copy(this._tmpPosition);
  42037. impostor.physicsBody.quaternion.copy(quaternion);
  42038. };
  42039. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42040. impostor.object.position.copyFrom(impostor.physicsBody.position);
  42041. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  42042. };
  42043. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42044. impostor.physicsBody.position.copy(newPosition);
  42045. impostor.physicsBody.quaternion.copy(newRotation);
  42046. };
  42047. CannonJSPlugin.prototype.isSupported = function () {
  42048. return window.CANNON !== undefined;
  42049. };
  42050. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42051. impostor.physicsBody.velocity.copy(velocity);
  42052. };
  42053. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42054. impostor.physicsBody.angularVelocity.copy(velocity);
  42055. };
  42056. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42057. var v = impostor.physicsBody.velocity;
  42058. if (!v)
  42059. return null;
  42060. return new BABYLON.Vector3(v.x, v.y, v.z);
  42061. };
  42062. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42063. var v = impostor.physicsBody.angularVelocity;
  42064. if (!v)
  42065. return null;
  42066. return new BABYLON.Vector3(v.x, v.y, v.z);
  42067. };
  42068. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42069. impostor.physicsBody.mass = mass;
  42070. impostor.physicsBody.updateMassProperties();
  42071. };
  42072. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  42073. impostor.physicsBody.sleep();
  42074. };
  42075. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  42076. impostor.physicsBody.wakeUp();
  42077. };
  42078. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42079. joint.physicsJoint.distance = maxDistance;
  42080. };
  42081. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  42082. if (!motorIndex) {
  42083. joint.physicsJoint.enableMotor();
  42084. }
  42085. };
  42086. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  42087. if (!motorIndex) {
  42088. joint.physicsJoint.disableMotor();
  42089. }
  42090. };
  42091. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42092. if (!motorIndex) {
  42093. joint.physicsJoint.enableMotor();
  42094. joint.physicsJoint.setMotorSpeed(speed);
  42095. if (maxForce) {
  42096. this.setLimit(joint, maxForce);
  42097. }
  42098. }
  42099. };
  42100. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  42101. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  42102. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  42103. };
  42104. CannonJSPlugin.prototype.dispose = function () {
  42105. //nothing to do, actually.
  42106. };
  42107. return CannonJSPlugin;
  42108. }());
  42109. BABYLON.CannonJSPlugin = CannonJSPlugin;
  42110. })(BABYLON || (BABYLON = {}));
  42111. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  42112. var BABYLON;
  42113. (function (BABYLON) {
  42114. var OimoJSPlugin = (function () {
  42115. function OimoJSPlugin(iterations) {
  42116. this.name = "OimoJSPlugin";
  42117. this._tmpImpostorsArray = [];
  42118. this._tmpPositionVector = BABYLON.Vector3.Zero();
  42119. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  42120. this.world.worldscale(1);
  42121. this.world.clear();
  42122. //making sure no stats are calculated
  42123. this.world.isNoStat = true;
  42124. }
  42125. OimoJSPlugin.prototype.setGravity = function (gravity) {
  42126. this.world.gravity.copy(gravity);
  42127. };
  42128. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  42129. this.world.timeStep = timeStep;
  42130. };
  42131. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  42132. var _this = this;
  42133. impostors.forEach(function (impostor) {
  42134. impostor.beforeStep();
  42135. });
  42136. this.world.step();
  42137. impostors.forEach(function (impostor) {
  42138. impostor.afterStep();
  42139. //update the ordered impostors array
  42140. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  42141. });
  42142. //check for collisions
  42143. var contact = this.world.contacts;
  42144. while (contact !== null) {
  42145. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  42146. contact = contact.next;
  42147. continue;
  42148. }
  42149. //is this body colliding with any other? get the impostor
  42150. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  42151. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  42152. if (!mainImpostor || !collidingImpostor) {
  42153. contact = contact.next;
  42154. continue;
  42155. }
  42156. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  42157. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42158. contact = contact.next;
  42159. }
  42160. };
  42161. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42162. var mass = impostor.physicsBody.massInfo.mass;
  42163. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  42164. };
  42165. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42166. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  42167. this.applyImpulse(impostor, force, contactPoint);
  42168. };
  42169. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42170. var _this = this;
  42171. //parent-child relationship. Does this impostor has a parent impostor?
  42172. if (impostor.parent) {
  42173. if (impostor.physicsBody) {
  42174. this.removePhysicsBody(impostor);
  42175. //TODO is that needed?
  42176. impostor.forceUpdate();
  42177. }
  42178. return;
  42179. }
  42180. if (impostor.isBodyInitRequired()) {
  42181. var bodyConfig = {
  42182. name: impostor.uniqueId,
  42183. //Oimo must have mass, also for static objects.
  42184. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  42185. size: [],
  42186. type: [],
  42187. pos: [],
  42188. rot: [],
  42189. move: impostor.getParam("mass") !== 0,
  42190. //Supporting older versions of Oimo
  42191. world: this.world
  42192. };
  42193. var impostors = [impostor];
  42194. var addToArray = function (parent) {
  42195. if (!parent.getChildMeshes)
  42196. return;
  42197. parent.getChildMeshes().forEach(function (m) {
  42198. if (m.physicsImpostor) {
  42199. impostors.push(m.physicsImpostor);
  42200. m.physicsImpostor._init();
  42201. }
  42202. });
  42203. };
  42204. addToArray(impostor.object);
  42205. var checkWithEpsilon_1 = function (value) {
  42206. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  42207. };
  42208. impostors.forEach(function (i) {
  42209. //get the correct bounding box
  42210. var oldQuaternion = i.object.rotationQuaternion;
  42211. var rot = new OIMO.Euler().setFromQuaternion({
  42212. x: impostor.object.rotationQuaternion.x,
  42213. y: impostor.object.rotationQuaternion.y,
  42214. z: impostor.object.rotationQuaternion.z,
  42215. s: impostor.object.rotationQuaternion.w
  42216. });
  42217. var extendSize = i.getObjectExtendSize();
  42218. if (i === impostor) {
  42219. var center = impostor.getObjectCenter();
  42220. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  42221. //Can also use Array.prototype.push.apply
  42222. bodyConfig.pos.push(center.x);
  42223. bodyConfig.pos.push(center.y);
  42224. bodyConfig.pos.push(center.z);
  42225. //tmp solution
  42226. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  42227. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  42228. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  42229. }
  42230. else {
  42231. bodyConfig.pos.push(i.object.position.x);
  42232. bodyConfig.pos.push(i.object.position.y);
  42233. bodyConfig.pos.push(i.object.position.z);
  42234. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  42235. bodyConfig.rot.push(0);
  42236. bodyConfig.rot.push(0);
  42237. bodyConfig.rot.push(0);
  42238. }
  42239. // register mesh
  42240. switch (i.type) {
  42241. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42242. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  42243. case BABYLON.PhysicsImpostor.SphereImpostor:
  42244. var radiusX = extendSize.x;
  42245. var radiusY = extendSize.y;
  42246. var radiusZ = extendSize.z;
  42247. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  42248. bodyConfig.type.push('sphere');
  42249. //due to the way oimo works with compounds, add 3 times
  42250. bodyConfig.size.push(size);
  42251. bodyConfig.size.push(size);
  42252. bodyConfig.size.push(size);
  42253. break;
  42254. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42255. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  42256. var sizeY = checkWithEpsilon_1(extendSize.y);
  42257. bodyConfig.type.push('cylinder');
  42258. bodyConfig.size.push(sizeX);
  42259. bodyConfig.size.push(sizeY);
  42260. //due to the way oimo works with compounds, add one more value.
  42261. bodyConfig.size.push(sizeY);
  42262. break;
  42263. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42264. case BABYLON.PhysicsImpostor.BoxImpostor:
  42265. default:
  42266. var sizeX = checkWithEpsilon_1(extendSize.x);
  42267. var sizeY = checkWithEpsilon_1(extendSize.y);
  42268. var sizeZ = checkWithEpsilon_1(extendSize.z);
  42269. bodyConfig.type.push('box');
  42270. bodyConfig.size.push(sizeX);
  42271. bodyConfig.size.push(sizeY);
  42272. bodyConfig.size.push(sizeZ);
  42273. break;
  42274. }
  42275. //actually not needed, but hey...
  42276. i.object.rotationQuaternion = oldQuaternion;
  42277. });
  42278. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  42279. }
  42280. else {
  42281. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  42282. }
  42283. impostor.setDeltaPosition(this._tmpPositionVector);
  42284. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  42285. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  42286. };
  42287. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42288. //impostor.physicsBody.dispose();
  42289. //Same as : (older oimo versions)
  42290. this.world.removeRigidBody(impostor.physicsBody);
  42291. };
  42292. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42293. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42294. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42295. if (!mainBody || !connectedBody) {
  42296. return;
  42297. }
  42298. var jointData = impostorJoint.joint.jointData;
  42299. var options = jointData.nativeParams || {};
  42300. var type;
  42301. var nativeJointData = {
  42302. body1: mainBody,
  42303. body2: connectedBody,
  42304. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  42305. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  42306. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  42307. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  42308. min: options.min,
  42309. max: options.max,
  42310. collision: options.collision || jointData.collision,
  42311. spring: options.spring,
  42312. //supporting older version of Oimo
  42313. world: this.world
  42314. };
  42315. switch (impostorJoint.joint.type) {
  42316. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42317. type = "jointBall";
  42318. break;
  42319. case BABYLON.PhysicsJoint.SpringJoint:
  42320. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42321. var springData = jointData;
  42322. nativeJointData.min = springData.length || nativeJointData.min;
  42323. //Max should also be set, just make sure it is at least min
  42324. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42325. case BABYLON.PhysicsJoint.DistanceJoint:
  42326. type = "jointDistance";
  42327. nativeJointData.max = jointData.maxDistance;
  42328. break;
  42329. case BABYLON.PhysicsJoint.PrismaticJoint:
  42330. type = "jointPrisme";
  42331. break;
  42332. case BABYLON.PhysicsJoint.SliderJoint:
  42333. type = "jointSlide";
  42334. break;
  42335. case BABYLON.PhysicsJoint.WheelJoint:
  42336. type = "jointWheel";
  42337. break;
  42338. case BABYLON.PhysicsJoint.HingeJoint:
  42339. default:
  42340. type = "jointHinge";
  42341. break;
  42342. }
  42343. nativeJointData.type = type;
  42344. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42345. };
  42346. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42347. //Bug in Oimo prevents us from disposing a joint in the playground
  42348. //joint.joint.physicsJoint.dispose();
  42349. //So we will bruteforce it!
  42350. try {
  42351. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42352. }
  42353. catch (e) {
  42354. BABYLON.Tools.Warn(e);
  42355. }
  42356. };
  42357. OimoJSPlugin.prototype.isSupported = function () {
  42358. return OIMO !== undefined;
  42359. };
  42360. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42361. if (!impostor.physicsBody.sleeping) {
  42362. //TODO check that
  42363. if (impostor.physicsBody.shapes.next) {
  42364. var parentShape = this._getLastShape(impostor.physicsBody);
  42365. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42366. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42367. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42368. }
  42369. else {
  42370. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42371. }
  42372. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42373. impostor.object.rotationQuaternion.normalize();
  42374. }
  42375. };
  42376. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42377. var body = impostor.physicsBody;
  42378. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42379. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42380. body.syncShapes();
  42381. body.awake();
  42382. };
  42383. OimoJSPlugin.prototype._getLastShape = function (body) {
  42384. var lastShape = body.shapes;
  42385. while (lastShape.next) {
  42386. lastShape = lastShape.next;
  42387. }
  42388. return lastShape;
  42389. };
  42390. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42391. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42392. };
  42393. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42394. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42395. };
  42396. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42397. var v = impostor.physicsBody.linearVelocity;
  42398. if (!v)
  42399. return null;
  42400. return new BABYLON.Vector3(v.x, v.y, v.z);
  42401. };
  42402. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42403. var v = impostor.physicsBody.angularVelocity;
  42404. if (!v)
  42405. return null;
  42406. return new BABYLON.Vector3(v.x, v.y, v.z);
  42407. };
  42408. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42409. var staticBody = mass === 0;
  42410. //this will actually set the body's density and not its mass.
  42411. //But this is how oimo treats the mass variable.
  42412. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42413. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42414. };
  42415. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42416. impostor.physicsBody.sleep();
  42417. };
  42418. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42419. impostor.physicsBody.awake();
  42420. };
  42421. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42422. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  42423. if (minDistance !== void 0) {
  42424. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  42425. }
  42426. };
  42427. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42428. //TODO separate rotational and transational motors.
  42429. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42430. if (motor) {
  42431. motor.setMotor(speed, maxForce);
  42432. }
  42433. };
  42434. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42435. //TODO separate rotational and transational motors.
  42436. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42437. if (motor) {
  42438. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42439. }
  42440. };
  42441. OimoJSPlugin.prototype.dispose = function () {
  42442. this.world.clear();
  42443. };
  42444. return OimoJSPlugin;
  42445. }());
  42446. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42447. })(BABYLON || (BABYLON = {}));
  42448. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  42449. var BABYLON;
  42450. (function (BABYLON) {
  42451. var DisplayPassPostProcess = (function (_super) {
  42452. __extends(DisplayPassPostProcess, _super);
  42453. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42454. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  42455. }
  42456. return DisplayPassPostProcess;
  42457. }(BABYLON.PostProcess));
  42458. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42459. })(BABYLON || (BABYLON = {}));
  42460. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  42461. var BABYLON;
  42462. (function (BABYLON) {
  42463. var SimplificationSettings = (function () {
  42464. function SimplificationSettings(quality, distance, optimizeMesh) {
  42465. this.quality = quality;
  42466. this.distance = distance;
  42467. this.optimizeMesh = optimizeMesh;
  42468. }
  42469. return SimplificationSettings;
  42470. }());
  42471. BABYLON.SimplificationSettings = SimplificationSettings;
  42472. var SimplificationQueue = (function () {
  42473. function SimplificationQueue() {
  42474. this.running = false;
  42475. this._simplificationArray = [];
  42476. }
  42477. SimplificationQueue.prototype.addTask = function (task) {
  42478. this._simplificationArray.push(task);
  42479. };
  42480. SimplificationQueue.prototype.executeNext = function () {
  42481. var task = this._simplificationArray.pop();
  42482. if (task) {
  42483. this.running = true;
  42484. this.runSimplification(task);
  42485. }
  42486. else {
  42487. this.running = false;
  42488. }
  42489. };
  42490. SimplificationQueue.prototype.runSimplification = function (task) {
  42491. var _this = this;
  42492. if (task.parallelProcessing) {
  42493. //parallel simplifier
  42494. task.settings.forEach(function (setting) {
  42495. var simplifier = _this.getSimplifier(task);
  42496. simplifier.simplify(setting, function (newMesh) {
  42497. task.mesh.addLODLevel(setting.distance, newMesh);
  42498. newMesh.isVisible = true;
  42499. //check if it is the last
  42500. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42501. //all done, run the success callback.
  42502. task.successCallback();
  42503. }
  42504. _this.executeNext();
  42505. });
  42506. });
  42507. }
  42508. else {
  42509. //single simplifier.
  42510. var simplifier = this.getSimplifier(task);
  42511. var runDecimation = function (setting, callback) {
  42512. simplifier.simplify(setting, function (newMesh) {
  42513. task.mesh.addLODLevel(setting.distance, newMesh);
  42514. newMesh.isVisible = true;
  42515. //run the next quality level
  42516. callback();
  42517. });
  42518. };
  42519. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42520. runDecimation(task.settings[loop.index], function () {
  42521. loop.executeNext();
  42522. });
  42523. }, function () {
  42524. //execution ended, run the success callback.
  42525. if (task.successCallback) {
  42526. task.successCallback();
  42527. }
  42528. _this.executeNext();
  42529. });
  42530. }
  42531. };
  42532. SimplificationQueue.prototype.getSimplifier = function (task) {
  42533. switch (task.simplificationType) {
  42534. case SimplificationType.QUADRATIC:
  42535. default:
  42536. return new QuadraticErrorSimplification(task.mesh);
  42537. }
  42538. };
  42539. return SimplificationQueue;
  42540. }());
  42541. BABYLON.SimplificationQueue = SimplificationQueue;
  42542. /**
  42543. * The implemented types of simplification.
  42544. * At the moment only Quadratic Error Decimation is implemented.
  42545. */
  42546. var SimplificationType;
  42547. (function (SimplificationType) {
  42548. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42549. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42550. var DecimationTriangle = (function () {
  42551. function DecimationTriangle(vertices) {
  42552. this.vertices = vertices;
  42553. this.error = new Array(4);
  42554. this.deleted = false;
  42555. this.isDirty = false;
  42556. this.deletePending = false;
  42557. this.borderFactor = 0;
  42558. }
  42559. return DecimationTriangle;
  42560. }());
  42561. BABYLON.DecimationTriangle = DecimationTriangle;
  42562. var DecimationVertex = (function () {
  42563. function DecimationVertex(position, id) {
  42564. this.position = position;
  42565. this.id = id;
  42566. this.isBorder = true;
  42567. this.q = new QuadraticMatrix();
  42568. this.triangleCount = 0;
  42569. this.triangleStart = 0;
  42570. this.originalOffsets = [];
  42571. }
  42572. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42573. this.position.copyFrom(newPosition);
  42574. };
  42575. return DecimationVertex;
  42576. }());
  42577. BABYLON.DecimationVertex = DecimationVertex;
  42578. var QuadraticMatrix = (function () {
  42579. function QuadraticMatrix(data) {
  42580. this.data = new Array(10);
  42581. for (var i = 0; i < 10; ++i) {
  42582. if (data && data[i]) {
  42583. this.data[i] = data[i];
  42584. }
  42585. else {
  42586. this.data[i] = 0;
  42587. }
  42588. }
  42589. }
  42590. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42591. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42592. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42593. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42594. return det;
  42595. };
  42596. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42597. for (var i = 0; i < 10; ++i) {
  42598. this.data[i] += matrix.data[i];
  42599. }
  42600. };
  42601. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42602. for (var i = 0; i < 10; ++i) {
  42603. this.data[i] += data[i];
  42604. }
  42605. };
  42606. QuadraticMatrix.prototype.add = function (matrix) {
  42607. var m = new QuadraticMatrix();
  42608. for (var i = 0; i < 10; ++i) {
  42609. m.data[i] = this.data[i] + matrix.data[i];
  42610. }
  42611. return m;
  42612. };
  42613. QuadraticMatrix.FromData = function (a, b, c, d) {
  42614. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42615. };
  42616. //returning an array to avoid garbage collection
  42617. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42618. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42619. };
  42620. return QuadraticMatrix;
  42621. }());
  42622. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42623. var Reference = (function () {
  42624. function Reference(vertexId, triangleId) {
  42625. this.vertexId = vertexId;
  42626. this.triangleId = triangleId;
  42627. }
  42628. return Reference;
  42629. }());
  42630. BABYLON.Reference = Reference;
  42631. /**
  42632. * An implementation of the Quadratic Error simplification algorithm.
  42633. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42634. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42635. * @author RaananW
  42636. */
  42637. var QuadraticErrorSimplification = (function () {
  42638. function QuadraticErrorSimplification(_mesh) {
  42639. this._mesh = _mesh;
  42640. this.initialized = false;
  42641. this.syncIterations = 5000;
  42642. this.aggressiveness = 7;
  42643. this.decimationIterations = 100;
  42644. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42645. }
  42646. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42647. var _this = this;
  42648. this.initDecimatedMesh();
  42649. //iterating through the submeshes array, one after the other.
  42650. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42651. _this.initWithMesh(loop.index, function () {
  42652. _this.runDecimation(settings, loop.index, function () {
  42653. loop.executeNext();
  42654. });
  42655. }, settings.optimizeMesh);
  42656. }, function () {
  42657. setTimeout(function () {
  42658. successCallback(_this._reconstructedMesh);
  42659. }, 0);
  42660. });
  42661. };
  42662. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42663. var _this = this;
  42664. var gCount = 0;
  42665. triangle.vertices.forEach(function (vertex) {
  42666. var count = 0;
  42667. var vPos = vertex.position;
  42668. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42669. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42670. ++count;
  42671. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42672. ++count;
  42673. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42674. ++count;
  42675. if (count > 1) {
  42676. ++gCount;
  42677. }
  42678. ;
  42679. });
  42680. if (gCount > 1) {
  42681. console.log(triangle, gCount);
  42682. }
  42683. return gCount > 1;
  42684. };
  42685. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42686. var _this = this;
  42687. var targetCount = ~~(this.triangles.length * settings.quality);
  42688. var deletedTriangles = 0;
  42689. var triangleCount = this.triangles.length;
  42690. var iterationFunction = function (iteration, callback) {
  42691. setTimeout(function () {
  42692. if (iteration % 5 === 0) {
  42693. _this.updateMesh(iteration === 0);
  42694. }
  42695. for (var i = 0; i < _this.triangles.length; ++i) {
  42696. _this.triangles[i].isDirty = false;
  42697. }
  42698. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42699. var trianglesIterator = function (i) {
  42700. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42701. var t = _this.triangles[tIdx];
  42702. if (!t)
  42703. return;
  42704. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42705. return;
  42706. }
  42707. for (var j = 0; j < 3; ++j) {
  42708. if (t.error[j] < threshold) {
  42709. var deleted0 = [];
  42710. var deleted1 = [];
  42711. var v0 = t.vertices[j];
  42712. var v1 = t.vertices[(j + 1) % 3];
  42713. if (v0.isBorder || v1.isBorder)
  42714. continue;
  42715. var p = BABYLON.Vector3.Zero();
  42716. var n = BABYLON.Vector3.Zero();
  42717. var uv = BABYLON.Vector2.Zero();
  42718. var color = new BABYLON.Color4(0, 0, 0, 1);
  42719. _this.calculateError(v0, v1, p, n, uv, color);
  42720. var delTr = [];
  42721. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42722. continue;
  42723. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42724. continue;
  42725. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42726. continue;
  42727. var uniqueArray = [];
  42728. delTr.forEach(function (deletedT) {
  42729. if (uniqueArray.indexOf(deletedT) === -1) {
  42730. deletedT.deletePending = true;
  42731. uniqueArray.push(deletedT);
  42732. }
  42733. });
  42734. if (uniqueArray.length % 2 !== 0) {
  42735. continue;
  42736. }
  42737. v0.q = v1.q.add(v0.q);
  42738. v0.updatePosition(p);
  42739. var tStart = _this.references.length;
  42740. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42741. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42742. var tCount = _this.references.length - tStart;
  42743. if (tCount <= v0.triangleCount) {
  42744. if (tCount) {
  42745. for (var c = 0; c < tCount; c++) {
  42746. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42747. }
  42748. }
  42749. }
  42750. else {
  42751. v0.triangleStart = tStart;
  42752. }
  42753. v0.triangleCount = tCount;
  42754. break;
  42755. }
  42756. }
  42757. };
  42758. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42759. }, 0);
  42760. };
  42761. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42762. if (triangleCount - deletedTriangles <= targetCount)
  42763. loop.breakLoop();
  42764. else {
  42765. iterationFunction(loop.index, function () {
  42766. loop.executeNext();
  42767. });
  42768. }
  42769. }, function () {
  42770. setTimeout(function () {
  42771. //reconstruct this part of the mesh
  42772. _this.reconstructMesh(submeshIndex);
  42773. successCallback();
  42774. }, 0);
  42775. });
  42776. };
  42777. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42778. var _this = this;
  42779. this.vertices = [];
  42780. this.triangles = [];
  42781. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42782. var indices = this._mesh.getIndices();
  42783. var submesh = this._mesh.subMeshes[submeshIndex];
  42784. var findInVertices = function (positionToSearch) {
  42785. if (optimizeMesh) {
  42786. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42787. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42788. return _this.vertices[ii];
  42789. }
  42790. }
  42791. }
  42792. return null;
  42793. };
  42794. var vertexReferences = [];
  42795. var vertexInit = function (i) {
  42796. var offset = i + submesh.verticesStart;
  42797. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42798. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42799. vertex.originalOffsets.push(offset);
  42800. if (vertex.id === _this.vertices.length) {
  42801. _this.vertices.push(vertex);
  42802. }
  42803. vertexReferences.push(vertex.id);
  42804. };
  42805. //var totalVertices = mesh.getTotalVertices();
  42806. var totalVertices = submesh.verticesCount;
  42807. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42808. var indicesInit = function (i) {
  42809. var offset = (submesh.indexStart / 3) + i;
  42810. var pos = (offset * 3);
  42811. var i0 = indices[pos + 0];
  42812. var i1 = indices[pos + 1];
  42813. var i2 = indices[pos + 2];
  42814. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42815. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42816. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42817. var triangle = new DecimationTriangle([v0, v1, v2]);
  42818. triangle.originalOffset = pos;
  42819. _this.triangles.push(triangle);
  42820. };
  42821. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42822. _this.init(callback);
  42823. });
  42824. });
  42825. };
  42826. QuadraticErrorSimplification.prototype.init = function (callback) {
  42827. var _this = this;
  42828. var triangleInit1 = function (i) {
  42829. var t = _this.triangles[i];
  42830. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42831. for (var j = 0; j < 3; j++) {
  42832. 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))));
  42833. }
  42834. };
  42835. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42836. var triangleInit2 = function (i) {
  42837. var t = _this.triangles[i];
  42838. for (var j = 0; j < 3; ++j) {
  42839. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42840. }
  42841. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42842. };
  42843. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42844. _this.initialized = true;
  42845. callback();
  42846. });
  42847. });
  42848. };
  42849. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42850. var newTriangles = [];
  42851. var i;
  42852. for (i = 0; i < this.vertices.length; ++i) {
  42853. this.vertices[i].triangleCount = 0;
  42854. }
  42855. var t;
  42856. var j;
  42857. for (i = 0; i < this.triangles.length; ++i) {
  42858. if (!this.triangles[i].deleted) {
  42859. t = this.triangles[i];
  42860. for (j = 0; j < 3; ++j) {
  42861. t.vertices[j].triangleCount = 1;
  42862. }
  42863. newTriangles.push(t);
  42864. }
  42865. }
  42866. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42867. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42868. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42869. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42870. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42871. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42872. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42873. var vertexCount = 0;
  42874. for (i = 0; i < this.vertices.length; ++i) {
  42875. var vertex = this.vertices[i];
  42876. vertex.id = vertexCount;
  42877. if (vertex.triangleCount) {
  42878. vertex.originalOffsets.forEach(function (originalOffset) {
  42879. newPositionData.push(vertex.position.x);
  42880. newPositionData.push(vertex.position.y);
  42881. newPositionData.push(vertex.position.z);
  42882. newNormalData.push(normalData[originalOffset * 3]);
  42883. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42884. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42885. if (uvs && uvs.length) {
  42886. newUVsData.push(uvs[(originalOffset * 2)]);
  42887. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42888. }
  42889. else if (colorsData && colorsData.length) {
  42890. newColorsData.push(colorsData[(originalOffset * 4)]);
  42891. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42892. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42893. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42894. }
  42895. ++vertexCount;
  42896. });
  42897. }
  42898. }
  42899. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42900. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42901. var submeshesArray = this._reconstructedMesh.subMeshes;
  42902. this._reconstructedMesh.subMeshes = [];
  42903. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42904. var originalIndices = this._mesh.getIndices();
  42905. for (i = 0; i < newTriangles.length; ++i) {
  42906. t = newTriangles[i]; //now get the new referencing point for each vertex
  42907. [0, 1, 2].forEach(function (idx) {
  42908. var id = originalIndices[t.originalOffset + idx];
  42909. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42910. if (offset < 0)
  42911. offset = 0;
  42912. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42913. });
  42914. }
  42915. //overwriting the old vertex buffers and indices.
  42916. this._reconstructedMesh.setIndices(newIndicesArray);
  42917. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42918. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42919. if (newUVsData.length > 0)
  42920. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42921. if (newColorsData.length > 0)
  42922. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42923. //create submesh
  42924. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42925. if (submeshIndex > 0) {
  42926. this._reconstructedMesh.subMeshes = [];
  42927. submeshesArray.forEach(function (submesh) {
  42928. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42929. });
  42930. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42931. }
  42932. };
  42933. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42934. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42935. this._reconstructedMesh.material = this._mesh.material;
  42936. this._reconstructedMesh.parent = this._mesh.parent;
  42937. this._reconstructedMesh.isVisible = false;
  42938. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42939. };
  42940. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42941. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42942. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42943. if (t.deleted)
  42944. continue;
  42945. var s = this.references[vertex1.triangleStart + i].vertexId;
  42946. var v1 = t.vertices[(s + 1) % 3];
  42947. var v2 = t.vertices[(s + 2) % 3];
  42948. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42949. deletedArray[i] = true;
  42950. delTr.push(t);
  42951. continue;
  42952. }
  42953. var d1 = v1.position.subtract(point);
  42954. d1 = d1.normalize();
  42955. var d2 = v2.position.subtract(point);
  42956. d2 = d2.normalize();
  42957. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42958. return true;
  42959. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42960. deletedArray[i] = false;
  42961. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42962. return true;
  42963. }
  42964. return false;
  42965. };
  42966. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42967. var newDeleted = deletedTriangles;
  42968. for (var i = 0; i < vertex.triangleCount; ++i) {
  42969. var ref = this.references[vertex.triangleStart + i];
  42970. var t = this.triangles[ref.triangleId];
  42971. if (t.deleted)
  42972. continue;
  42973. if (deletedArray[i] && t.deletePending) {
  42974. t.deleted = true;
  42975. newDeleted++;
  42976. continue;
  42977. }
  42978. t.vertices[ref.vertexId] = origVertex;
  42979. t.isDirty = true;
  42980. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42981. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42982. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42983. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42984. this.references.push(ref);
  42985. }
  42986. return newDeleted;
  42987. };
  42988. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42989. for (var i = 0; i < this.vertices.length; ++i) {
  42990. var vCount = [];
  42991. var vId = [];
  42992. var v = this.vertices[i];
  42993. var j;
  42994. for (j = 0; j < v.triangleCount; ++j) {
  42995. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42996. for (var ii = 0; ii < 3; ii++) {
  42997. var ofs = 0;
  42998. var vv = triangle.vertices[ii];
  42999. while (ofs < vCount.length) {
  43000. if (vId[ofs] === vv.id)
  43001. break;
  43002. ++ofs;
  43003. }
  43004. if (ofs === vCount.length) {
  43005. vCount.push(1);
  43006. vId.push(vv.id);
  43007. }
  43008. else {
  43009. vCount[ofs]++;
  43010. }
  43011. }
  43012. }
  43013. for (j = 0; j < vCount.length; ++j) {
  43014. if (vCount[j] === 1) {
  43015. this.vertices[vId[j]].isBorder = true;
  43016. }
  43017. else {
  43018. this.vertices[vId[j]].isBorder = false;
  43019. }
  43020. }
  43021. }
  43022. };
  43023. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  43024. if (identifyBorders === void 0) { identifyBorders = false; }
  43025. var i;
  43026. if (!identifyBorders) {
  43027. var newTrianglesVector = [];
  43028. for (i = 0; i < this.triangles.length; ++i) {
  43029. if (!this.triangles[i].deleted) {
  43030. newTrianglesVector.push(this.triangles[i]);
  43031. }
  43032. }
  43033. this.triangles = newTrianglesVector;
  43034. }
  43035. for (i = 0; i < this.vertices.length; ++i) {
  43036. this.vertices[i].triangleCount = 0;
  43037. this.vertices[i].triangleStart = 0;
  43038. }
  43039. var t;
  43040. var j;
  43041. var v;
  43042. for (i = 0; i < this.triangles.length; ++i) {
  43043. t = this.triangles[i];
  43044. for (j = 0; j < 3; ++j) {
  43045. v = t.vertices[j];
  43046. v.triangleCount++;
  43047. }
  43048. }
  43049. var tStart = 0;
  43050. for (i = 0; i < this.vertices.length; ++i) {
  43051. this.vertices[i].triangleStart = tStart;
  43052. tStart += this.vertices[i].triangleCount;
  43053. this.vertices[i].triangleCount = 0;
  43054. }
  43055. var newReferences = new Array(this.triangles.length * 3);
  43056. for (i = 0; i < this.triangles.length; ++i) {
  43057. t = this.triangles[i];
  43058. for (j = 0; j < 3; ++j) {
  43059. v = t.vertices[j];
  43060. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  43061. v.triangleCount++;
  43062. }
  43063. }
  43064. this.references = newReferences;
  43065. if (identifyBorders) {
  43066. this.identifyBorder();
  43067. }
  43068. };
  43069. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  43070. var x = point.x;
  43071. var y = point.y;
  43072. var z = point.z;
  43073. 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
  43074. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  43075. };
  43076. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  43077. var q = vertex1.q.add(vertex2.q);
  43078. var border = vertex1.isBorder && vertex2.isBorder;
  43079. var error = 0;
  43080. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  43081. if (qDet !== 0 && !border) {
  43082. if (!pointResult) {
  43083. pointResult = BABYLON.Vector3.Zero();
  43084. }
  43085. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  43086. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  43087. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  43088. error = this.vertexError(q, pointResult);
  43089. }
  43090. else {
  43091. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  43092. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  43093. var error1 = this.vertexError(q, vertex1.position);
  43094. var error2 = this.vertexError(q, vertex2.position);
  43095. var error3 = this.vertexError(q, p3);
  43096. error = Math.min(error1, error2, error3);
  43097. if (error === error1) {
  43098. if (pointResult) {
  43099. pointResult.copyFrom(vertex1.position);
  43100. }
  43101. }
  43102. else if (error === error2) {
  43103. if (pointResult) {
  43104. pointResult.copyFrom(vertex2.position);
  43105. }
  43106. }
  43107. else {
  43108. if (pointResult) {
  43109. pointResult.copyFrom(p3);
  43110. }
  43111. }
  43112. }
  43113. return error;
  43114. };
  43115. return QuadraticErrorSimplification;
  43116. }());
  43117. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  43118. })(BABYLON || (BABYLON = {}));
  43119. //# sourceMappingURL=babylon.meshSimplification.js.map
  43120. var BABYLON;
  43121. (function (BABYLON) {
  43122. var serializedGeometries = [];
  43123. var serializeGeometry = function (geometry, serializationGeometries) {
  43124. if (serializedGeometries[geometry.id]) {
  43125. return;
  43126. }
  43127. if (geometry.doNotSerialize) {
  43128. return;
  43129. }
  43130. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  43131. serializationGeometries.boxes.push(geometry.serialize());
  43132. }
  43133. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  43134. serializationGeometries.spheres.push(geometry.serialize());
  43135. }
  43136. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  43137. serializationGeometries.cylinders.push(geometry.serialize());
  43138. }
  43139. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  43140. serializationGeometries.toruses.push(geometry.serialize());
  43141. }
  43142. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  43143. serializationGeometries.grounds.push(geometry.serialize());
  43144. }
  43145. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  43146. serializationGeometries.planes.push(geometry.serialize());
  43147. }
  43148. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  43149. serializationGeometries.torusKnots.push(geometry.serialize());
  43150. }
  43151. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  43152. throw new Error("Unknown primitive type");
  43153. }
  43154. else {
  43155. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  43156. }
  43157. serializedGeometries[geometry.id] = true;
  43158. };
  43159. var serializeMesh = function (mesh, serializationScene) {
  43160. var serializationObject = {};
  43161. serializationObject.name = mesh.name;
  43162. serializationObject.id = mesh.id;
  43163. if (BABYLON.Tags.HasTags(mesh)) {
  43164. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  43165. }
  43166. serializationObject.position = mesh.position.asArray();
  43167. if (mesh.rotationQuaternion) {
  43168. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  43169. }
  43170. else if (mesh.rotation) {
  43171. serializationObject.rotation = mesh.rotation.asArray();
  43172. }
  43173. serializationObject.scaling = mesh.scaling.asArray();
  43174. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  43175. serializationObject.isEnabled = mesh.isEnabled();
  43176. serializationObject.isVisible = mesh.isVisible;
  43177. serializationObject.infiniteDistance = mesh.infiniteDistance;
  43178. serializationObject.pickable = mesh.isPickable;
  43179. serializationObject.receiveShadows = mesh.receiveShadows;
  43180. serializationObject.billboardMode = mesh.billboardMode;
  43181. serializationObject.visibility = mesh.visibility;
  43182. serializationObject.checkCollisions = mesh.checkCollisions;
  43183. serializationObject.isBlocker = mesh.isBlocker;
  43184. // Parent
  43185. if (mesh.parent) {
  43186. serializationObject.parentId = mesh.parent.id;
  43187. }
  43188. // Geometry
  43189. var geometry = mesh._geometry;
  43190. if (geometry) {
  43191. var geometryId = geometry.id;
  43192. serializationObject.geometryId = geometryId;
  43193. if (!mesh.getScene().getGeometryByID(geometryId)) {
  43194. // 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
  43195. serializeGeometry(geometry, serializationScene.geometries);
  43196. }
  43197. // SubMeshes
  43198. serializationObject.subMeshes = [];
  43199. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43200. var subMesh = mesh.subMeshes[subIndex];
  43201. serializationObject.subMeshes.push({
  43202. materialIndex: subMesh.materialIndex,
  43203. verticesStart: subMesh.verticesStart,
  43204. verticesCount: subMesh.verticesCount,
  43205. indexStart: subMesh.indexStart,
  43206. indexCount: subMesh.indexCount
  43207. });
  43208. }
  43209. }
  43210. // Material
  43211. if (mesh.material) {
  43212. serializationObject.materialId = mesh.material.id;
  43213. }
  43214. else {
  43215. mesh.material = null;
  43216. }
  43217. // Skeleton
  43218. if (mesh.skeleton) {
  43219. serializationObject.skeletonId = mesh.skeleton.id;
  43220. }
  43221. // Physics
  43222. //TODO implement correct serialization for physics impostors.
  43223. if (mesh.getPhysicsImpostor()) {
  43224. serializationObject.physicsMass = mesh.getPhysicsMass();
  43225. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  43226. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  43227. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  43228. }
  43229. // Metadata
  43230. if (mesh.metadata) {
  43231. serializationObject.metadata = mesh.metadata;
  43232. }
  43233. // Instances
  43234. serializationObject.instances = [];
  43235. for (var index = 0; index < mesh.instances.length; index++) {
  43236. var instance = mesh.instances[index];
  43237. var serializationInstance = {
  43238. name: instance.name,
  43239. position: instance.position.asArray(),
  43240. scaling: instance.scaling.asArray()
  43241. };
  43242. if (instance.rotationQuaternion) {
  43243. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  43244. }
  43245. else if (instance.rotation) {
  43246. serializationInstance.rotation = instance.rotation.asArray();
  43247. }
  43248. serializationObject.instances.push(serializationInstance);
  43249. // Animations
  43250. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  43251. serializationInstance.ranges = instance.serializeAnimationRanges();
  43252. }
  43253. // Animations
  43254. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  43255. serializationObject.ranges = mesh.serializeAnimationRanges();
  43256. // Layer mask
  43257. serializationObject.layerMask = mesh.layerMask;
  43258. // Alpha
  43259. serializationObject.alphaIndex = mesh.alphaIndex;
  43260. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  43261. // Overlay
  43262. serializationObject.overlayAlpha = mesh.overlayAlpha;
  43263. serializationObject.overlayColor = mesh.overlayColor.asArray();
  43264. serializationObject.renderOverlay = mesh.renderOverlay;
  43265. // Fog
  43266. serializationObject.applyFog = mesh.applyFog;
  43267. // Action Manager
  43268. if (mesh.actionManager) {
  43269. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  43270. }
  43271. return serializationObject;
  43272. };
  43273. var finalizeSingleMesh = function (mesh, serializationObject) {
  43274. //only works if the mesh is already loaded
  43275. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43276. //serialize material
  43277. if (mesh.material) {
  43278. if (mesh.material instanceof BABYLON.StandardMaterial) {
  43279. serializationObject.materials = serializationObject.materials || [];
  43280. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43281. serializationObject.materials.push(mesh.material.serialize());
  43282. }
  43283. }
  43284. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  43285. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  43286. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43287. serializationObject.multiMaterials.push(mesh.material.serialize());
  43288. }
  43289. }
  43290. }
  43291. //serialize geometry
  43292. var geometry = mesh._geometry;
  43293. if (geometry) {
  43294. if (!serializationObject.geometries) {
  43295. serializationObject.geometries = {};
  43296. serializationObject.geometries.boxes = [];
  43297. serializationObject.geometries.spheres = [];
  43298. serializationObject.geometries.cylinders = [];
  43299. serializationObject.geometries.toruses = [];
  43300. serializationObject.geometries.grounds = [];
  43301. serializationObject.geometries.planes = [];
  43302. serializationObject.geometries.torusKnots = [];
  43303. serializationObject.geometries.vertexData = [];
  43304. }
  43305. serializeGeometry(geometry, serializationObject.geometries);
  43306. }
  43307. // Skeletons
  43308. if (mesh.skeleton) {
  43309. serializationObject.skeletons = serializationObject.skeletons || [];
  43310. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43311. }
  43312. //serialize the actual mesh
  43313. serializationObject.meshes = serializationObject.meshes || [];
  43314. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43315. }
  43316. };
  43317. var SceneSerializer = (function () {
  43318. function SceneSerializer() {
  43319. }
  43320. SceneSerializer.ClearCache = function () {
  43321. serializedGeometries = [];
  43322. };
  43323. SceneSerializer.Serialize = function (scene) {
  43324. var serializationObject = {};
  43325. // Scene
  43326. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43327. serializationObject.autoClear = scene.autoClear;
  43328. serializationObject.clearColor = scene.clearColor.asArray();
  43329. serializationObject.ambientColor = scene.ambientColor.asArray();
  43330. serializationObject.gravity = scene.gravity.asArray();
  43331. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43332. serializationObject.workerCollisions = scene.workerCollisions;
  43333. // Fog
  43334. if (scene.fogMode && scene.fogMode !== 0) {
  43335. serializationObject.fogMode = scene.fogMode;
  43336. serializationObject.fogColor = scene.fogColor.asArray();
  43337. serializationObject.fogStart = scene.fogStart;
  43338. serializationObject.fogEnd = scene.fogEnd;
  43339. serializationObject.fogDensity = scene.fogDensity;
  43340. }
  43341. //Physics
  43342. if (scene.isPhysicsEnabled()) {
  43343. serializationObject.physicsEnabled = true;
  43344. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43345. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43346. }
  43347. // Metadata
  43348. if (scene.metadata) {
  43349. serializationObject.metadata = scene.metadata;
  43350. }
  43351. // Lights
  43352. serializationObject.lights = [];
  43353. var index;
  43354. var light;
  43355. for (index = 0; index < scene.lights.length; index++) {
  43356. light = scene.lights[index];
  43357. if (!light.doNotSerialize) {
  43358. serializationObject.lights.push(light.serialize());
  43359. }
  43360. }
  43361. // Cameras
  43362. serializationObject.cameras = [];
  43363. for (index = 0; index < scene.cameras.length; index++) {
  43364. var camera = scene.cameras[index];
  43365. if (!camera.doNotSerialize) {
  43366. serializationObject.cameras.push(camera.serialize());
  43367. }
  43368. }
  43369. if (scene.activeCamera) {
  43370. serializationObject.activeCameraID = scene.activeCamera.id;
  43371. }
  43372. // Animations
  43373. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43374. // Materials
  43375. serializationObject.materials = [];
  43376. serializationObject.multiMaterials = [];
  43377. var material;
  43378. for (index = 0; index < scene.materials.length; index++) {
  43379. material = scene.materials[index];
  43380. if (!material.doNotSerialize) {
  43381. serializationObject.materials.push(material.serialize());
  43382. }
  43383. }
  43384. // MultiMaterials
  43385. serializationObject.multiMaterials = [];
  43386. for (index = 0; index < scene.multiMaterials.length; index++) {
  43387. var multiMaterial = scene.multiMaterials[index];
  43388. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43389. }
  43390. // Skeletons
  43391. serializationObject.skeletons = [];
  43392. for (index = 0; index < scene.skeletons.length; index++) {
  43393. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43394. }
  43395. // Geometries
  43396. serializationObject.geometries = {};
  43397. serializationObject.geometries.boxes = [];
  43398. serializationObject.geometries.spheres = [];
  43399. serializationObject.geometries.cylinders = [];
  43400. serializationObject.geometries.toruses = [];
  43401. serializationObject.geometries.grounds = [];
  43402. serializationObject.geometries.planes = [];
  43403. serializationObject.geometries.torusKnots = [];
  43404. serializationObject.geometries.vertexData = [];
  43405. serializedGeometries = [];
  43406. var geometries = scene.getGeometries();
  43407. for (index = 0; index < geometries.length; index++) {
  43408. var geometry = geometries[index];
  43409. if (geometry.isReady()) {
  43410. serializeGeometry(geometry, serializationObject.geometries);
  43411. }
  43412. }
  43413. // Meshes
  43414. serializationObject.meshes = [];
  43415. for (index = 0; index < scene.meshes.length; index++) {
  43416. var abstractMesh = scene.meshes[index];
  43417. if (abstractMesh instanceof BABYLON.Mesh) {
  43418. var mesh = abstractMesh;
  43419. if (!mesh.doNotSerialize) {
  43420. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43421. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43422. }
  43423. }
  43424. }
  43425. }
  43426. // Particles Systems
  43427. serializationObject.particleSystems = [];
  43428. for (index = 0; index < scene.particleSystems.length; index++) {
  43429. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43430. }
  43431. // Lens flares
  43432. serializationObject.lensFlareSystems = [];
  43433. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43434. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43435. }
  43436. // Shadows
  43437. serializationObject.shadowGenerators = [];
  43438. for (index = 0; index < scene.lights.length; index++) {
  43439. light = scene.lights[index];
  43440. var shadowGenerator = light.getShadowGenerator();
  43441. // Only support serialization for official generator so far.
  43442. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  43443. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  43444. }
  43445. }
  43446. // Action Manager
  43447. if (scene.actionManager) {
  43448. serializationObject.actions = scene.actionManager.serialize("scene");
  43449. }
  43450. // Audio
  43451. serializationObject.sounds = [];
  43452. for (index = 0; index < scene.soundTracks.length; index++) {
  43453. var soundtrack = scene.soundTracks[index];
  43454. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  43455. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  43456. }
  43457. }
  43458. return serializationObject;
  43459. };
  43460. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43461. if (withParents === void 0) { withParents = false; }
  43462. if (withChildren === void 0) { withChildren = false; }
  43463. var serializationObject = {};
  43464. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43465. if (withParents || withChildren) {
  43466. //deliberate for loop! not for each, appended should be processed as well.
  43467. for (var i = 0; i < toSerialize.length; ++i) {
  43468. if (withChildren) {
  43469. toSerialize[i].getDescendants().forEach(function (node) {
  43470. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43471. toSerialize.push(node);
  43472. }
  43473. });
  43474. }
  43475. //make sure the array doesn't contain the object already
  43476. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43477. toSerialize.push(toSerialize[i].parent);
  43478. }
  43479. }
  43480. }
  43481. toSerialize.forEach(function (mesh) {
  43482. finalizeSingleMesh(mesh, serializationObject);
  43483. });
  43484. return serializationObject;
  43485. };
  43486. return SceneSerializer;
  43487. }());
  43488. BABYLON.SceneSerializer = SceneSerializer;
  43489. })(BABYLON || (BABYLON = {}));
  43490. //# sourceMappingURL=babylon.sceneSerializer.js.map
  43491. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  43492. // Huge respect for a such great lib.
  43493. // Earcut license:
  43494. // Copyright (c) 2016, Mapbox
  43495. //
  43496. // Permission to use, copy, modify, and/or distribute this software for any purpose
  43497. // with or without fee is hereby granted, provided that the above copyright notice
  43498. // and this permission notice appear in all copies.
  43499. //
  43500. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  43501. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  43502. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  43503. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  43504. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  43505. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  43506. // THIS SOFTWARE.
  43507. var Earcut;
  43508. (function (Earcut) {
  43509. /**
  43510. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  43511. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  43512. * @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).
  43513. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  43514. */
  43515. function earcut(data, holeIndices, dim) {
  43516. dim = dim || 2;
  43517. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43518. if (!outerNode)
  43519. return triangles;
  43520. var minX, minY, maxX, maxY, x, y, size;
  43521. if (hasHoles)
  43522. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43523. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43524. if (data.length > 80 * dim) {
  43525. minX = maxX = data[0];
  43526. minY = maxY = data[1];
  43527. for (var i = dim; i < outerLen; i += dim) {
  43528. x = data[i];
  43529. y = data[i + 1];
  43530. if (x < minX)
  43531. minX = x;
  43532. if (y < minY)
  43533. minY = y;
  43534. if (x > maxX)
  43535. maxX = x;
  43536. if (y > maxY)
  43537. maxY = y;
  43538. }
  43539. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43540. size = Math.max(maxX - minX, maxY - minY);
  43541. }
  43542. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43543. return triangles;
  43544. }
  43545. Earcut.earcut = earcut;
  43546. // create a circular doubly linked list from polygon points in the specified winding order
  43547. function linkedList(data, start, end, dim, clockwise) {
  43548. var i, last;
  43549. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43550. for (i = start; i < end; i += dim)
  43551. last = insertNode(i, data[i], data[i + 1], last);
  43552. }
  43553. else {
  43554. for (i = end - dim; i >= start; i -= dim)
  43555. last = insertNode(i, data[i], data[i + 1], last);
  43556. }
  43557. if (last && equals(last, last.next)) {
  43558. removeNode(last);
  43559. last = last.next;
  43560. }
  43561. return last;
  43562. }
  43563. // eliminate colinear or duplicate points
  43564. function filterPoints(start, end) {
  43565. if (!start)
  43566. return start;
  43567. if (!end)
  43568. end = start;
  43569. var p = start, again;
  43570. do {
  43571. again = false;
  43572. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43573. removeNode(p);
  43574. p = end = p.prev;
  43575. if (p === p.next)
  43576. return null;
  43577. again = true;
  43578. }
  43579. else {
  43580. p = p.next;
  43581. }
  43582. } while (again || p !== end);
  43583. return end;
  43584. }
  43585. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43586. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43587. if (!ear)
  43588. return;
  43589. // interlink polygon nodes in z-order
  43590. if (!pass && size)
  43591. indexCurve(ear, minX, minY, size);
  43592. var stop = ear, prev, next;
  43593. // iterate through ears, slicing them one by one
  43594. while (ear.prev !== ear.next) {
  43595. prev = ear.prev;
  43596. next = ear.next;
  43597. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43598. // cut off the triangle
  43599. triangles.push(prev.i / dim);
  43600. triangles.push(ear.i / dim);
  43601. triangles.push(next.i / dim);
  43602. removeNode(ear);
  43603. // skipping the next vertice leads to less sliver triangles
  43604. ear = next.next;
  43605. stop = next.next;
  43606. continue;
  43607. }
  43608. ear = next;
  43609. // if we looped through the whole remaining polygon and can't find any more ears
  43610. if (ear === stop) {
  43611. // try filtering points and slicing again
  43612. if (!pass) {
  43613. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43614. }
  43615. else if (pass === 1) {
  43616. ear = cureLocalIntersections(ear, triangles, dim);
  43617. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43618. }
  43619. else if (pass === 2) {
  43620. splitEarcut(ear, triangles, dim, minX, minY, size);
  43621. }
  43622. break;
  43623. }
  43624. }
  43625. }
  43626. // check whether a polygon node forms a valid ear with adjacent nodes
  43627. function isEar(ear) {
  43628. var a = ear.prev, b = ear, c = ear.next;
  43629. if (area(a, b, c) >= 0)
  43630. return false; // reflex, can't be an ear
  43631. // now make sure we don't have other points inside the potential ear
  43632. var p = ear.next.next;
  43633. while (p !== ear.prev) {
  43634. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43635. area(p.prev, p, p.next) >= 0)
  43636. return false;
  43637. p = p.next;
  43638. }
  43639. return true;
  43640. }
  43641. function isEarHashed(ear, minX, minY, size) {
  43642. var a = ear.prev, b = ear, c = ear.next;
  43643. if (area(a, b, c) >= 0)
  43644. return false; // reflex, can't be an ear
  43645. // triangle bbox; min & max are calculated like this for speed
  43646. 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);
  43647. // z-order range for the current triangle bbox;
  43648. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43649. // first look for points inside the triangle in increasing z-order
  43650. var p = ear.nextZ;
  43651. while (p && p.z <= maxZ) {
  43652. if (p !== ear.prev &&
  43653. p !== ear.next &&
  43654. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43655. area(p.prev, p, p.next) >= 0)
  43656. return false;
  43657. p = p.nextZ;
  43658. }
  43659. // then look for points in decreasing z-order
  43660. p = ear.prevZ;
  43661. while (p && p.z >= minZ) {
  43662. if (p !== ear.prev &&
  43663. p !== ear.next &&
  43664. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43665. area(p.prev, p, p.next) >= 0)
  43666. return false;
  43667. p = p.prevZ;
  43668. }
  43669. return true;
  43670. }
  43671. // go through all polygon nodes and cure small local self-intersections
  43672. function cureLocalIntersections(start, triangles, dim) {
  43673. var p = start;
  43674. do {
  43675. var a = p.prev, b = p.next.next;
  43676. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43677. triangles.push(a.i / dim);
  43678. triangles.push(p.i / dim);
  43679. triangles.push(b.i / dim);
  43680. // remove two nodes involved
  43681. removeNode(p);
  43682. removeNode(p.next);
  43683. p = start = b;
  43684. }
  43685. p = p.next;
  43686. } while (p !== start);
  43687. return p;
  43688. }
  43689. // try splitting polygon into two and triangulate them independently
  43690. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43691. // look for a valid diagonal that divides the polygon into two
  43692. var a = start;
  43693. do {
  43694. var b = a.next.next;
  43695. while (b !== a.prev) {
  43696. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43697. // split the polygon in two by the diagonal
  43698. var c = splitPolygon(a, b);
  43699. // filter colinear points around the cuts
  43700. a = filterPoints(a, a.next);
  43701. c = filterPoints(c, c.next);
  43702. // run earcut on each half
  43703. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43704. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43705. return;
  43706. }
  43707. b = b.next;
  43708. }
  43709. a = a.next;
  43710. } while (a !== start);
  43711. }
  43712. // link every hole into the outer loop, producing a single-ring polygon without holes
  43713. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43714. var queue = [], i, len, start, end, list;
  43715. for (i = 0, len = holeIndices.length; i < len; i++) {
  43716. start = holeIndices[i] * dim;
  43717. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43718. list = linkedList(data, start, end, dim, false);
  43719. if (list === list.next)
  43720. list.steiner = true;
  43721. queue.push(getLeftmost(list));
  43722. }
  43723. queue.sort(compareX);
  43724. // process holes from left to right
  43725. for (i = 0; i < queue.length; i++) {
  43726. eliminateHole(queue[i], outerNode);
  43727. outerNode = filterPoints(outerNode, outerNode.next);
  43728. }
  43729. return outerNode;
  43730. }
  43731. function compareX(a, b) {
  43732. return a.x - b.x;
  43733. }
  43734. // find a bridge between vertices that connects hole with an outer ring and and link it
  43735. function eliminateHole(hole, outerNode) {
  43736. outerNode = findHoleBridge(hole, outerNode);
  43737. if (outerNode) {
  43738. var b = splitPolygon(outerNode, hole);
  43739. filterPoints(b, b.next);
  43740. }
  43741. }
  43742. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43743. function findHoleBridge(hole, outerNode) {
  43744. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43745. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43746. // segment's endpoint with lesser x will be potential connection point
  43747. do {
  43748. if (hy <= p.y && hy >= p.next.y) {
  43749. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43750. if (x <= hx && x > qx) {
  43751. qx = x;
  43752. if (x === hx) {
  43753. if (hy === p.y)
  43754. return p;
  43755. if (hy === p.next.y)
  43756. return p.next;
  43757. }
  43758. m = p.x < p.next.x ? p : p.next;
  43759. }
  43760. }
  43761. p = p.next;
  43762. } while (p !== outerNode);
  43763. if (!m)
  43764. return null;
  43765. if (hx === qx)
  43766. return m.prev; // hole touches outer segment; pick lower endpoint
  43767. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43768. // if there are no points found, we have a valid connection;
  43769. // otherwise choose the point of the minimum angle with the ray as connection point
  43770. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43771. p = m.next;
  43772. while (p !== stop) {
  43773. if (hx >= p.x &&
  43774. p.x >= mx &&
  43775. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43776. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43777. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43778. m = p;
  43779. tanMin = tan;
  43780. }
  43781. }
  43782. p = p.next;
  43783. }
  43784. return m;
  43785. }
  43786. // interlink polygon nodes in z-order
  43787. function indexCurve(start, minX, minY, size) {
  43788. var p = start;
  43789. do {
  43790. if (p.z === null)
  43791. p.z = zOrder(p.x, p.y, minX, minY, size);
  43792. p.prevZ = p.prev;
  43793. p.nextZ = p.next;
  43794. p = p.next;
  43795. } while (p !== start);
  43796. p.prevZ.nextZ = null;
  43797. p.prevZ = null;
  43798. sortLinked(p);
  43799. }
  43800. // Simon Tatham's linked list merge sort algorithm
  43801. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43802. function sortLinked(list) {
  43803. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43804. do {
  43805. p = list;
  43806. list = null;
  43807. tail = null;
  43808. numMerges = 0;
  43809. while (p) {
  43810. numMerges++;
  43811. q = p;
  43812. pSize = 0;
  43813. for (i = 0; i < inSize; i++) {
  43814. pSize++;
  43815. q = q.nextZ;
  43816. if (!q)
  43817. break;
  43818. }
  43819. qSize = inSize;
  43820. while (pSize > 0 || (qSize > 0 && q)) {
  43821. if (pSize === 0) {
  43822. e = q;
  43823. q = q.nextZ;
  43824. qSize--;
  43825. }
  43826. else if (qSize === 0 || !q) {
  43827. e = p;
  43828. p = p.nextZ;
  43829. pSize--;
  43830. }
  43831. else if (p.z <= q.z) {
  43832. e = p;
  43833. p = p.nextZ;
  43834. pSize--;
  43835. }
  43836. else {
  43837. e = q;
  43838. q = q.nextZ;
  43839. qSize--;
  43840. }
  43841. if (tail)
  43842. tail.nextZ = e;
  43843. else
  43844. list = e;
  43845. e.prevZ = tail;
  43846. tail = e;
  43847. }
  43848. p = q;
  43849. }
  43850. tail.nextZ = null;
  43851. inSize *= 2;
  43852. } while (numMerges > 1);
  43853. return list;
  43854. }
  43855. // z-order of a point given coords and size of the data bounding box
  43856. function zOrder(x, y, minX, minY, size) {
  43857. // coords are transformed into non-negative 15-bit integer range
  43858. x = 32767 * (x - minX) / size;
  43859. y = 32767 * (y - minY) / size;
  43860. x = (x | (x << 8)) & 0x00FF00FF;
  43861. x = (x | (x << 4)) & 0x0F0F0F0F;
  43862. x = (x | (x << 2)) & 0x33333333;
  43863. x = (x | (x << 1)) & 0x55555555;
  43864. y = (y | (y << 8)) & 0x00FF00FF;
  43865. y = (y | (y << 4)) & 0x0F0F0F0F;
  43866. y = (y | (y << 2)) & 0x33333333;
  43867. y = (y | (y << 1)) & 0x55555555;
  43868. return x | (y << 1);
  43869. }
  43870. // find the leftmost node of a polygon ring
  43871. function getLeftmost(start) {
  43872. var p = start, leftmost = start;
  43873. do {
  43874. if (p.x < leftmost.x)
  43875. leftmost = p;
  43876. p = p.next;
  43877. } while (p !== start);
  43878. return leftmost;
  43879. }
  43880. // check if a point lies within a convex triangle
  43881. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43882. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43883. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43884. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43885. }
  43886. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43887. function isValidDiagonal(a, b) {
  43888. return a.next.i !== b.i &&
  43889. a.prev.i !== b.i &&
  43890. !intersectsPolygon(a, b) &&
  43891. locallyInside(a, b) &&
  43892. locallyInside(b, a) &&
  43893. middleInside(a, b);
  43894. }
  43895. // signed area of a triangle
  43896. function area(p, q, r) {
  43897. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43898. }
  43899. // check if two points are equal
  43900. function equals(p1, p2) {
  43901. return p1.x === p2.x && p1.y === p2.y;
  43902. }
  43903. // check if two segments intersect
  43904. function intersects(p1, q1, p2, q2) {
  43905. if ((equals(p1, q1) && equals(p2, q2)) ||
  43906. (equals(p1, q2) && equals(p2, q1)))
  43907. return true;
  43908. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43909. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43910. }
  43911. // check if a polygon diagonal intersects any polygon segments
  43912. function intersectsPolygon(a, b) {
  43913. var p = a;
  43914. do {
  43915. if (p.i !== a.i &&
  43916. p.next.i !== a.i &&
  43917. p.i !== b.i &&
  43918. p.next.i !== b.i &&
  43919. intersects(p, p.next, a, b))
  43920. return true;
  43921. p = p.next;
  43922. } while (p !== a);
  43923. return false;
  43924. }
  43925. // check if a polygon diagonal is locally inside the polygon
  43926. function locallyInside(a, b) {
  43927. return area(a.prev, a, a.next) < 0
  43928. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43929. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43930. }
  43931. // check if the middle point of a polygon diagonal is inside the polygon
  43932. function middleInside(a, b) {
  43933. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43934. do {
  43935. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43936. inside = !inside;
  43937. p = p.next;
  43938. } while (p !== a);
  43939. return inside;
  43940. }
  43941. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43942. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43943. function splitPolygon(a, b) {
  43944. 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;
  43945. a.next = b;
  43946. b.prev = a;
  43947. a2.next = an;
  43948. an.prev = a2;
  43949. b2.next = a2;
  43950. a2.prev = b2;
  43951. bp.next = b2;
  43952. b2.prev = bp;
  43953. return b2;
  43954. }
  43955. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43956. function insertNode(i, x, y, last) {
  43957. var p = new Node(i, x, y);
  43958. if (!last) {
  43959. p.prev = p;
  43960. p.next = p;
  43961. }
  43962. else {
  43963. p.next = last.next;
  43964. p.prev = last;
  43965. last.next.prev = p;
  43966. last.next = p;
  43967. }
  43968. return p;
  43969. }
  43970. function removeNode(p) {
  43971. p.next.prev = p.prev;
  43972. p.prev.next = p.next;
  43973. if (p.prevZ)
  43974. p.prevZ.nextZ = p.nextZ;
  43975. if (p.nextZ)
  43976. p.nextZ.prevZ = p.prevZ;
  43977. }
  43978. function Node(i, x, y) {
  43979. // vertice index in coordinates array
  43980. this.i = i;
  43981. // vertex coordinates
  43982. this.x = x;
  43983. this.y = y;
  43984. // previous and next vertice nodes in a polygon ring
  43985. this.prev = null;
  43986. this.next = null;
  43987. // z-order curve value
  43988. this.z = null;
  43989. // previous and next nodes in z-order
  43990. this.prevZ = null;
  43991. this.nextZ = null;
  43992. // indicates whether this is a steiner point
  43993. this.steiner = false;
  43994. }
  43995. /**
  43996. * return a percentage difference between the polygon area and its triangulation area;
  43997. * used to verify correctness of triangulation
  43998. */
  43999. function deviation(data, holeIndices, dim, triangles) {
  44000. var hasHoles = holeIndices && holeIndices.length;
  44001. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  44002. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  44003. if (hasHoles) {
  44004. for (var i = 0, len = holeIndices.length; i < len; i++) {
  44005. var start = holeIndices[i] * dim;
  44006. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  44007. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  44008. }
  44009. }
  44010. var trianglesArea = 0;
  44011. for (i = 0; i < triangles.length; i += 3) {
  44012. var a = triangles[i] * dim;
  44013. var b = triangles[i + 1] * dim;
  44014. var c = triangles[i + 2] * dim;
  44015. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  44016. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  44017. }
  44018. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  44019. }
  44020. Earcut.deviation = deviation;
  44021. ;
  44022. function signedArea(data, start, end, dim) {
  44023. var sum = 0;
  44024. for (var i = start, j = end - dim; i < end; i += dim) {
  44025. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  44026. j = i;
  44027. }
  44028. return sum;
  44029. }
  44030. /**
  44031. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  44032. */
  44033. function flatten(data) {
  44034. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  44035. for (var i = 0; i < data.length; i++) {
  44036. for (var j = 0; j < data[i].length; j++) {
  44037. for (var d = 0; d < dim; d++)
  44038. result.vertices.push(data[i][j][d]);
  44039. }
  44040. if (i > 0) {
  44041. holeIndex += data[i - 1].length;
  44042. result.holes.push(holeIndex);
  44043. }
  44044. }
  44045. return result;
  44046. }
  44047. Earcut.flatten = flatten;
  44048. ;
  44049. })(Earcut || (Earcut = {}));
  44050. //# sourceMappingURL=babylon.earcut.js.map
  44051. var BABYLON;
  44052. (function (BABYLON) {
  44053. // Unique ID when we import meshes from Babylon to CSG
  44054. var currentCSGMeshId = 0;
  44055. // # class Vertex
  44056. // Represents a vertex of a polygon. Use your own vertex class instead of this
  44057. // one to provide additional features like texture coordinates and vertex
  44058. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  44059. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  44060. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  44061. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  44062. // is not used anywhere else.
  44063. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  44064. var Vertex = (function () {
  44065. function Vertex(pos, normal, uv) {
  44066. this.pos = pos;
  44067. this.normal = normal;
  44068. this.uv = uv;
  44069. }
  44070. Vertex.prototype.clone = function () {
  44071. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  44072. };
  44073. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  44074. // orientation of a polygon is flipped.
  44075. Vertex.prototype.flip = function () {
  44076. this.normal = this.normal.scale(-1);
  44077. };
  44078. // Create a new vertex between this vertex and `other` by linearly
  44079. // interpolating all properties using a parameter of `t`. Subclasses should
  44080. // override this to interpolate additional properties.
  44081. Vertex.prototype.interpolate = function (other, t) {
  44082. 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));
  44083. };
  44084. return Vertex;
  44085. }());
  44086. // # class Plane
  44087. // Represents a plane in 3D space.
  44088. var Plane = (function () {
  44089. function Plane(normal, w) {
  44090. this.normal = normal;
  44091. this.w = w;
  44092. }
  44093. Plane.FromPoints = function (a, b, c) {
  44094. var v0 = c.subtract(a);
  44095. var v1 = b.subtract(a);
  44096. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  44097. return null;
  44098. }
  44099. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  44100. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  44101. };
  44102. Plane.prototype.clone = function () {
  44103. return new Plane(this.normal.clone(), this.w);
  44104. };
  44105. Plane.prototype.flip = function () {
  44106. this.normal.scaleInPlace(-1);
  44107. this.w = -this.w;
  44108. };
  44109. // Split `polygon` by this plane if needed, then put the polygon or polygon
  44110. // fragments in the appropriate lists. Coplanar polygons go into either
  44111. // `coplanarFront` or `coplanarBack` depending on their orientation with
  44112. // respect to this plane. Polygons in front or in back of this plane go into
  44113. // either `front` or `back`.
  44114. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  44115. var COPLANAR = 0;
  44116. var FRONT = 1;
  44117. var BACK = 2;
  44118. var SPANNING = 3;
  44119. // Classify each point as well as the entire polygon into one of the above
  44120. // four classes.
  44121. var polygonType = 0;
  44122. var types = [];
  44123. var i;
  44124. var t;
  44125. for (i = 0; i < polygon.vertices.length; i++) {
  44126. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  44127. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  44128. polygonType |= type;
  44129. types.push(type);
  44130. }
  44131. // Put the polygon in the correct list, splitting it when necessary.
  44132. switch (polygonType) {
  44133. case COPLANAR:
  44134. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  44135. break;
  44136. case FRONT:
  44137. front.push(polygon);
  44138. break;
  44139. case BACK:
  44140. back.push(polygon);
  44141. break;
  44142. case SPANNING:
  44143. var f = [], b = [];
  44144. for (i = 0; i < polygon.vertices.length; i++) {
  44145. var j = (i + 1) % polygon.vertices.length;
  44146. var ti = types[i], tj = types[j];
  44147. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  44148. if (ti !== BACK)
  44149. f.push(vi);
  44150. if (ti !== FRONT)
  44151. b.push(ti !== BACK ? vi.clone() : vi);
  44152. if ((ti | tj) === SPANNING) {
  44153. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  44154. var v = vi.interpolate(vj, t);
  44155. f.push(v);
  44156. b.push(v.clone());
  44157. }
  44158. }
  44159. var poly;
  44160. if (f.length >= 3) {
  44161. poly = new Polygon(f, polygon.shared);
  44162. if (poly.plane)
  44163. front.push(poly);
  44164. }
  44165. if (b.length >= 3) {
  44166. poly = new Polygon(b, polygon.shared);
  44167. if (poly.plane)
  44168. back.push(poly);
  44169. }
  44170. break;
  44171. }
  44172. };
  44173. return Plane;
  44174. }());
  44175. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  44176. // point is on the plane.
  44177. Plane.EPSILON = 1e-5;
  44178. // # class Polygon
  44179. // Represents a convex polygon. The vertices used to initialize a polygon must
  44180. // be coplanar and form a convex loop.
  44181. //
  44182. // Each convex polygon has a `shared` property, which is shared between all
  44183. // polygons that are clones of each other or were split from the same polygon.
  44184. // This can be used to define per-polygon properties (such as surface color).
  44185. var Polygon = (function () {
  44186. function Polygon(vertices, shared) {
  44187. this.vertices = vertices;
  44188. this.shared = shared;
  44189. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  44190. }
  44191. Polygon.prototype.clone = function () {
  44192. var vertices = this.vertices.map(function (v) { return v.clone(); });
  44193. return new Polygon(vertices, this.shared);
  44194. };
  44195. Polygon.prototype.flip = function () {
  44196. this.vertices.reverse().map(function (v) { v.flip(); });
  44197. this.plane.flip();
  44198. };
  44199. return Polygon;
  44200. }());
  44201. // # class Node
  44202. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  44203. // by picking a polygon to split along. That polygon (and all other coplanar
  44204. // polygons) are added directly to that node and the other polygons are added to
  44205. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  44206. // no distinction between internal and leaf nodes.
  44207. var Node = (function () {
  44208. function Node(polygons) {
  44209. this.plane = null;
  44210. this.front = null;
  44211. this.back = null;
  44212. this.polygons = [];
  44213. if (polygons) {
  44214. this.build(polygons);
  44215. }
  44216. }
  44217. Node.prototype.clone = function () {
  44218. var node = new Node();
  44219. node.plane = this.plane && this.plane.clone();
  44220. node.front = this.front && this.front.clone();
  44221. node.back = this.back && this.back.clone();
  44222. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  44223. return node;
  44224. };
  44225. // Convert solid space to empty space and empty space to solid space.
  44226. Node.prototype.invert = function () {
  44227. for (var i = 0; i < this.polygons.length; i++) {
  44228. this.polygons[i].flip();
  44229. }
  44230. if (this.plane) {
  44231. this.plane.flip();
  44232. }
  44233. if (this.front) {
  44234. this.front.invert();
  44235. }
  44236. if (this.back) {
  44237. this.back.invert();
  44238. }
  44239. var temp = this.front;
  44240. this.front = this.back;
  44241. this.back = temp;
  44242. };
  44243. // Recursively remove all polygons in `polygons` that are inside this BSP
  44244. // tree.
  44245. Node.prototype.clipPolygons = function (polygons) {
  44246. if (!this.plane)
  44247. return polygons.slice();
  44248. var front = [], back = [];
  44249. for (var i = 0; i < polygons.length; i++) {
  44250. this.plane.splitPolygon(polygons[i], front, back, front, back);
  44251. }
  44252. if (this.front) {
  44253. front = this.front.clipPolygons(front);
  44254. }
  44255. if (this.back) {
  44256. back = this.back.clipPolygons(back);
  44257. }
  44258. else {
  44259. back = [];
  44260. }
  44261. return front.concat(back);
  44262. };
  44263. // Remove all polygons in this BSP tree that are inside the other BSP tree
  44264. // `bsp`.
  44265. Node.prototype.clipTo = function (bsp) {
  44266. this.polygons = bsp.clipPolygons(this.polygons);
  44267. if (this.front)
  44268. this.front.clipTo(bsp);
  44269. if (this.back)
  44270. this.back.clipTo(bsp);
  44271. };
  44272. // Return a list of all polygons in this BSP tree.
  44273. Node.prototype.allPolygons = function () {
  44274. var polygons = this.polygons.slice();
  44275. if (this.front)
  44276. polygons = polygons.concat(this.front.allPolygons());
  44277. if (this.back)
  44278. polygons = polygons.concat(this.back.allPolygons());
  44279. return polygons;
  44280. };
  44281. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  44282. // new polygons are filtered down to the bottom of the tree and become new
  44283. // nodes there. Each set of polygons is partitioned using the first polygon
  44284. // (no heuristic is used to pick a good split).
  44285. Node.prototype.build = function (polygons) {
  44286. if (!polygons.length)
  44287. return;
  44288. if (!this.plane)
  44289. this.plane = polygons[0].plane.clone();
  44290. var front = [], back = [];
  44291. for (var i = 0; i < polygons.length; i++) {
  44292. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  44293. }
  44294. if (front.length) {
  44295. if (!this.front)
  44296. this.front = new Node();
  44297. this.front.build(front);
  44298. }
  44299. if (back.length) {
  44300. if (!this.back)
  44301. this.back = new Node();
  44302. this.back.build(back);
  44303. }
  44304. };
  44305. return Node;
  44306. }());
  44307. var CSG = (function () {
  44308. function CSG() {
  44309. this.polygons = new Array();
  44310. }
  44311. // Convert BABYLON.Mesh to BABYLON.CSG
  44312. CSG.FromMesh = function (mesh) {
  44313. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44314. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44315. if (mesh instanceof BABYLON.Mesh) {
  44316. mesh.computeWorldMatrix(true);
  44317. matrix = mesh.getWorldMatrix();
  44318. meshPosition = mesh.position.clone();
  44319. meshRotation = mesh.rotation.clone();
  44320. if (mesh.rotationQuaternion) {
  44321. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44322. }
  44323. meshScaling = mesh.scaling.clone();
  44324. }
  44325. else {
  44326. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44327. }
  44328. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44329. var subMeshes = mesh.subMeshes;
  44330. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44331. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44332. vertices = [];
  44333. for (var j = 0; j < 3; j++) {
  44334. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44335. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44336. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44337. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44338. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44339. vertex = new Vertex(position, normal, uv);
  44340. vertices.push(vertex);
  44341. }
  44342. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44343. // To handle the case of degenerated triangle
  44344. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44345. if (polygon.plane)
  44346. polygons.push(polygon);
  44347. }
  44348. }
  44349. var csg = CSG.FromPolygons(polygons);
  44350. csg.matrix = matrix;
  44351. csg.position = meshPosition;
  44352. csg.rotation = meshRotation;
  44353. csg.scaling = meshScaling;
  44354. csg.rotationQuaternion = meshRotationQuaternion;
  44355. currentCSGMeshId++;
  44356. return csg;
  44357. };
  44358. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44359. CSG.FromPolygons = function (polygons) {
  44360. var csg = new CSG();
  44361. csg.polygons = polygons;
  44362. return csg;
  44363. };
  44364. CSG.prototype.clone = function () {
  44365. var csg = new CSG();
  44366. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44367. csg.copyTransformAttributes(this);
  44368. return csg;
  44369. };
  44370. CSG.prototype.toPolygons = function () {
  44371. return this.polygons;
  44372. };
  44373. CSG.prototype.union = function (csg) {
  44374. var a = new Node(this.clone().polygons);
  44375. var b = new Node(csg.clone().polygons);
  44376. a.clipTo(b);
  44377. b.clipTo(a);
  44378. b.invert();
  44379. b.clipTo(a);
  44380. b.invert();
  44381. a.build(b.allPolygons());
  44382. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44383. };
  44384. CSG.prototype.unionInPlace = function (csg) {
  44385. var a = new Node(this.polygons);
  44386. var b = new Node(csg.polygons);
  44387. a.clipTo(b);
  44388. b.clipTo(a);
  44389. b.invert();
  44390. b.clipTo(a);
  44391. b.invert();
  44392. a.build(b.allPolygons());
  44393. this.polygons = a.allPolygons();
  44394. };
  44395. CSG.prototype.subtract = function (csg) {
  44396. var a = new Node(this.clone().polygons);
  44397. var b = new Node(csg.clone().polygons);
  44398. a.invert();
  44399. a.clipTo(b);
  44400. b.clipTo(a);
  44401. b.invert();
  44402. b.clipTo(a);
  44403. b.invert();
  44404. a.build(b.allPolygons());
  44405. a.invert();
  44406. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44407. };
  44408. CSG.prototype.subtractInPlace = function (csg) {
  44409. var a = new Node(this.polygons);
  44410. var b = new Node(csg.polygons);
  44411. a.invert();
  44412. a.clipTo(b);
  44413. b.clipTo(a);
  44414. b.invert();
  44415. b.clipTo(a);
  44416. b.invert();
  44417. a.build(b.allPolygons());
  44418. a.invert();
  44419. this.polygons = a.allPolygons();
  44420. };
  44421. CSG.prototype.intersect = function (csg) {
  44422. var a = new Node(this.clone().polygons);
  44423. var b = new Node(csg.clone().polygons);
  44424. a.invert();
  44425. b.clipTo(a);
  44426. b.invert();
  44427. a.clipTo(b);
  44428. b.clipTo(a);
  44429. a.build(b.allPolygons());
  44430. a.invert();
  44431. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44432. };
  44433. CSG.prototype.intersectInPlace = function (csg) {
  44434. var a = new Node(this.polygons);
  44435. var b = new Node(csg.polygons);
  44436. a.invert();
  44437. b.clipTo(a);
  44438. b.invert();
  44439. a.clipTo(b);
  44440. b.clipTo(a);
  44441. a.build(b.allPolygons());
  44442. a.invert();
  44443. this.polygons = a.allPolygons();
  44444. };
  44445. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44446. // not modified.
  44447. CSG.prototype.inverse = function () {
  44448. var csg = this.clone();
  44449. csg.inverseInPlace();
  44450. return csg;
  44451. };
  44452. CSG.prototype.inverseInPlace = function () {
  44453. this.polygons.map(function (p) { p.flip(); });
  44454. };
  44455. // This is used to keep meshes transformations so they can be restored
  44456. // when we build back a Babylon Mesh
  44457. // NB : All CSG operations are performed in world coordinates
  44458. CSG.prototype.copyTransformAttributes = function (csg) {
  44459. this.matrix = csg.matrix;
  44460. this.position = csg.position;
  44461. this.rotation = csg.rotation;
  44462. this.scaling = csg.scaling;
  44463. this.rotationQuaternion = csg.rotationQuaternion;
  44464. return this;
  44465. };
  44466. // Build Raw mesh from CSG
  44467. // Coordinates here are in world space
  44468. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44469. var matrix = this.matrix.clone();
  44470. matrix.invert();
  44471. 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;
  44472. if (keepSubMeshes) {
  44473. // Sort Polygons, since subMeshes are indices range
  44474. polygons.sort(function (a, b) {
  44475. if (a.shared.meshId === b.shared.meshId) {
  44476. return a.shared.subMeshId - b.shared.subMeshId;
  44477. }
  44478. else {
  44479. return a.shared.meshId - b.shared.meshId;
  44480. }
  44481. });
  44482. }
  44483. for (var i = 0, il = polygons.length; i < il; i++) {
  44484. polygon = polygons[i];
  44485. // Building SubMeshes
  44486. if (!subMesh_dict[polygon.shared.meshId]) {
  44487. subMesh_dict[polygon.shared.meshId] = {};
  44488. }
  44489. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44490. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44491. indexStart: +Infinity,
  44492. indexEnd: -Infinity,
  44493. materialIndex: polygon.shared.materialIndex
  44494. };
  44495. }
  44496. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44497. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44498. polygonIndices[0] = 0;
  44499. polygonIndices[1] = j - 1;
  44500. polygonIndices[2] = j;
  44501. for (var k = 0; k < 3; k++) {
  44502. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44503. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44504. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44505. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44506. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44507. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44508. // Check if 2 points can be merged
  44509. if (!(typeof vertex_idx !== 'undefined' &&
  44510. normals[vertex_idx * 3] === localNormal.x &&
  44511. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44512. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44513. uvs[vertex_idx * 2] === uv.x &&
  44514. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44515. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44516. uvs.push(uv.x, uv.y);
  44517. normals.push(normal.x, normal.y, normal.z);
  44518. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44519. }
  44520. indices.push(vertex_idx);
  44521. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44522. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44523. currentIndex++;
  44524. }
  44525. }
  44526. }
  44527. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44528. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44529. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44530. mesh.setIndices(indices);
  44531. if (keepSubMeshes) {
  44532. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44533. var materialIndexOffset = 0, materialMaxIndex;
  44534. mesh.subMeshes = new Array();
  44535. for (var m in subMesh_dict) {
  44536. materialMaxIndex = -1;
  44537. for (var sm in subMesh_dict[m]) {
  44538. subMesh_obj = subMesh_dict[m][sm];
  44539. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44540. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44541. }
  44542. materialIndexOffset += ++materialMaxIndex;
  44543. }
  44544. }
  44545. return mesh;
  44546. };
  44547. // Build Mesh from CSG taking material and transforms into account
  44548. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44549. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44550. mesh.material = material;
  44551. mesh.position.copyFrom(this.position);
  44552. mesh.rotation.copyFrom(this.rotation);
  44553. if (this.rotationQuaternion) {
  44554. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44555. }
  44556. mesh.scaling.copyFrom(this.scaling);
  44557. mesh.computeWorldMatrix(true);
  44558. return mesh;
  44559. };
  44560. return CSG;
  44561. }());
  44562. BABYLON.CSG = CSG;
  44563. })(BABYLON || (BABYLON = {}));
  44564. //# sourceMappingURL=babylon.csg.js.map
  44565. var BABYLON;
  44566. (function (BABYLON) {
  44567. var VRDistortionCorrectionPostProcess = (function (_super) {
  44568. __extends(VRDistortionCorrectionPostProcess, _super);
  44569. //ANY
  44570. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44571. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44572. 'LensCenter',
  44573. 'Scale',
  44574. 'ScaleIn',
  44575. 'HmdWarpParam'
  44576. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44577. _this._isRightEye = isRightEye;
  44578. _this._distortionFactors = vrMetrics.distortionK;
  44579. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44580. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44581. _this.onSizeChangedObservable.add(function () {
  44582. _this.aspectRatio = _this.width * .5 / _this.height;
  44583. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44584. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44585. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44586. });
  44587. _this.onApplyObservable.add(function (effect) {
  44588. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44589. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44590. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44591. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44592. });
  44593. return _this;
  44594. }
  44595. return VRDistortionCorrectionPostProcess;
  44596. }(BABYLON.PostProcess));
  44597. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44598. })(BABYLON || (BABYLON = {}));
  44599. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44600. // Mainly based on these 2 articles :
  44601. // 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
  44602. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44603. var BABYLON;
  44604. (function (BABYLON) {
  44605. var JoystickAxis;
  44606. (function (JoystickAxis) {
  44607. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44608. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44609. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44610. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44611. var VirtualJoystick = (function () {
  44612. function VirtualJoystick(leftJoystick) {
  44613. var _this = this;
  44614. if (leftJoystick) {
  44615. this._leftJoystick = true;
  44616. }
  44617. else {
  44618. this._leftJoystick = false;
  44619. }
  44620. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44621. VirtualJoystick._globalJoystickIndex++;
  44622. // By default left & right arrow keys are moving the X
  44623. // and up & down keys are moving the Y
  44624. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44625. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44626. this.reverseLeftRight = false;
  44627. this.reverseUpDown = false;
  44628. // collections of pointers
  44629. this._touches = new BABYLON.StringDictionary();
  44630. this.deltaPosition = BABYLON.Vector3.Zero();
  44631. this._joystickSensibility = 25;
  44632. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44633. this._rotationSpeed = 25;
  44634. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44635. this._rotateOnAxisRelativeToMesh = false;
  44636. this._onResize = function (evt) {
  44637. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44638. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44639. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44640. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44641. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44642. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44643. };
  44644. // injecting a canvas element on top of the canvas 3D game
  44645. if (!VirtualJoystick.vjCanvas) {
  44646. window.addEventListener("resize", this._onResize, false);
  44647. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44648. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44649. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44650. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44651. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44652. VirtualJoystick.vjCanvas.style.width = "100%";
  44653. VirtualJoystick.vjCanvas.style.height = "100%";
  44654. VirtualJoystick.vjCanvas.style.position = "absolute";
  44655. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44656. VirtualJoystick.vjCanvas.style.top = "0px";
  44657. VirtualJoystick.vjCanvas.style.left = "0px";
  44658. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44659. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44660. // Support for jQuery PEP polyfill
  44661. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44662. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44663. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44664. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44665. document.body.appendChild(VirtualJoystick.vjCanvas);
  44666. }
  44667. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44668. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44669. this.pressed = false;
  44670. // default joystick color
  44671. this._joystickColor = "cyan";
  44672. this._joystickPointerID = -1;
  44673. // current joystick position
  44674. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44675. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44676. // origin joystick position
  44677. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44678. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44679. this._onPointerDownHandlerRef = function (evt) {
  44680. _this._onPointerDown(evt);
  44681. };
  44682. this._onPointerMoveHandlerRef = function (evt) {
  44683. _this._onPointerMove(evt);
  44684. };
  44685. this._onPointerOutHandlerRef = function (evt) {
  44686. _this._onPointerUp(evt);
  44687. };
  44688. this._onPointerUpHandlerRef = function (evt) {
  44689. _this._onPointerUp(evt);
  44690. };
  44691. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44692. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44693. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44694. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44695. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44696. evt.preventDefault(); // Disables system menu
  44697. }, false);
  44698. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44699. }
  44700. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44701. this._joystickSensibility = newJoystickSensibility;
  44702. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44703. };
  44704. VirtualJoystick.prototype._onPointerDown = function (e) {
  44705. var positionOnScreenCondition;
  44706. e.preventDefault();
  44707. if (this._leftJoystick === true) {
  44708. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44709. }
  44710. else {
  44711. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44712. }
  44713. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44714. // First contact will be dedicated to the virtual joystick
  44715. this._joystickPointerID = e.pointerId;
  44716. this._joystickPointerStartPos.x = e.clientX;
  44717. this._joystickPointerStartPos.y = e.clientY;
  44718. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44719. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44720. this._deltaJoystickVector.x = 0;
  44721. this._deltaJoystickVector.y = 0;
  44722. this.pressed = true;
  44723. this._touches.add(e.pointerId.toString(), e);
  44724. }
  44725. else {
  44726. // You can only trigger the action buttons with a joystick declared
  44727. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44728. this._action();
  44729. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44730. }
  44731. }
  44732. };
  44733. VirtualJoystick.prototype._onPointerMove = function (e) {
  44734. // If the current pointer is the one associated to the joystick (first touch contact)
  44735. if (this._joystickPointerID == e.pointerId) {
  44736. this._joystickPointerPos.x = e.clientX;
  44737. this._joystickPointerPos.y = e.clientY;
  44738. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44739. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44740. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44741. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44742. switch (this._axisTargetedByLeftAndRight) {
  44743. case JoystickAxis.X:
  44744. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44745. break;
  44746. case JoystickAxis.Y:
  44747. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44748. break;
  44749. case JoystickAxis.Z:
  44750. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44751. break;
  44752. }
  44753. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44754. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44755. switch (this._axisTargetedByUpAndDown) {
  44756. case JoystickAxis.X:
  44757. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44758. break;
  44759. case JoystickAxis.Y:
  44760. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44761. break;
  44762. case JoystickAxis.Z:
  44763. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44764. break;
  44765. }
  44766. }
  44767. else {
  44768. var data = this._touches.get(e.pointerId.toString());
  44769. if (data) {
  44770. data.x = e.clientX;
  44771. data.y = e.clientY;
  44772. }
  44773. }
  44774. };
  44775. VirtualJoystick.prototype._onPointerUp = function (e) {
  44776. if (this._joystickPointerID == e.pointerId) {
  44777. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44778. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44779. this._joystickPointerID = -1;
  44780. this.pressed = false;
  44781. }
  44782. else {
  44783. var touch = this._touches.get(e.pointerId.toString());
  44784. if (touch) {
  44785. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44786. }
  44787. }
  44788. this._deltaJoystickVector.x = 0;
  44789. this._deltaJoystickVector.y = 0;
  44790. this._touches.remove(e.pointerId.toString());
  44791. };
  44792. /**
  44793. * Change the color of the virtual joystick
  44794. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44795. */
  44796. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44797. this._joystickColor = newColor;
  44798. };
  44799. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44800. this._action = action;
  44801. };
  44802. // Define which axis you'd like to control for left & right
  44803. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44804. switch (axis) {
  44805. case JoystickAxis.X:
  44806. case JoystickAxis.Y:
  44807. case JoystickAxis.Z:
  44808. this._axisTargetedByLeftAndRight = axis;
  44809. break;
  44810. default:
  44811. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44812. break;
  44813. }
  44814. };
  44815. // Define which axis you'd like to control for up & down
  44816. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44817. switch (axis) {
  44818. case JoystickAxis.X:
  44819. case JoystickAxis.Y:
  44820. case JoystickAxis.Z:
  44821. this._axisTargetedByUpAndDown = axis;
  44822. break;
  44823. default:
  44824. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44825. break;
  44826. }
  44827. };
  44828. VirtualJoystick.prototype._clearCanvas = function () {
  44829. if (this._leftJoystick) {
  44830. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44831. }
  44832. else {
  44833. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44834. }
  44835. };
  44836. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44837. var _this = this;
  44838. if (this.pressed) {
  44839. this._touches.forEach(function (key, touch) {
  44840. if (touch.pointerId === _this._joystickPointerID) {
  44841. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44842. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44843. VirtualJoystick.vjCanvasContext.beginPath();
  44844. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44845. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44846. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44847. VirtualJoystick.vjCanvasContext.stroke();
  44848. VirtualJoystick.vjCanvasContext.closePath();
  44849. VirtualJoystick.vjCanvasContext.beginPath();
  44850. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44851. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44852. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44853. VirtualJoystick.vjCanvasContext.stroke();
  44854. VirtualJoystick.vjCanvasContext.closePath();
  44855. VirtualJoystick.vjCanvasContext.beginPath();
  44856. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44857. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44858. VirtualJoystick.vjCanvasContext.stroke();
  44859. VirtualJoystick.vjCanvasContext.closePath();
  44860. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44861. }
  44862. else {
  44863. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44864. VirtualJoystick.vjCanvasContext.beginPath();
  44865. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44866. VirtualJoystick.vjCanvasContext.beginPath();
  44867. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44868. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44869. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44870. VirtualJoystick.vjCanvasContext.stroke();
  44871. VirtualJoystick.vjCanvasContext.closePath();
  44872. touch.prevX = touch.x;
  44873. touch.prevY = touch.y;
  44874. }
  44875. ;
  44876. });
  44877. }
  44878. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44879. };
  44880. VirtualJoystick.prototype.releaseCanvas = function () {
  44881. if (VirtualJoystick.vjCanvas) {
  44882. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44883. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44884. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44885. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44886. window.removeEventListener("resize", this._onResize);
  44887. document.body.removeChild(VirtualJoystick.vjCanvas);
  44888. VirtualJoystick.vjCanvas = null;
  44889. }
  44890. };
  44891. return VirtualJoystick;
  44892. }());
  44893. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44894. VirtualJoystick._globalJoystickIndex = 0;
  44895. BABYLON.VirtualJoystick = VirtualJoystick;
  44896. })(BABYLON || (BABYLON = {}));
  44897. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44898. var BABYLON;
  44899. (function (BABYLON) {
  44900. // We're mainly based on the logic defined into the FreeCamera code
  44901. var VirtualJoysticksCamera = (function (_super) {
  44902. __extends(VirtualJoysticksCamera, _super);
  44903. function VirtualJoysticksCamera(name, position, scene) {
  44904. var _this = _super.call(this, name, position, scene) || this;
  44905. _this.inputs.addVirtualJoystick();
  44906. return _this;
  44907. }
  44908. VirtualJoysticksCamera.prototype.getClassName = function () {
  44909. return "VirtualJoysticksCamera";
  44910. };
  44911. return VirtualJoysticksCamera;
  44912. }(BABYLON.FreeCamera));
  44913. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44914. })(BABYLON || (BABYLON = {}));
  44915. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44916. var BABYLON;
  44917. (function (BABYLON) {
  44918. var FreeCameraVirtualJoystickInput = (function () {
  44919. function FreeCameraVirtualJoystickInput() {
  44920. }
  44921. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44922. return this._leftjoystick;
  44923. };
  44924. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44925. return this._rightjoystick;
  44926. };
  44927. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44928. if (this._leftjoystick) {
  44929. var camera = this.camera;
  44930. var speed = camera._computeLocalCameraSpeed() * 50;
  44931. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44932. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44933. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44934. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44935. if (!this._leftjoystick.pressed) {
  44936. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44937. }
  44938. if (!this._rightjoystick.pressed) {
  44939. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44940. }
  44941. }
  44942. };
  44943. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44944. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44945. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44946. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44947. this._leftjoystick.setJoystickSensibility(0.15);
  44948. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44949. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44950. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44951. this._rightjoystick.reverseUpDown = true;
  44952. this._rightjoystick.setJoystickSensibility(0.05);
  44953. this._rightjoystick.setJoystickColor("yellow");
  44954. };
  44955. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44956. this._leftjoystick.releaseCanvas();
  44957. this._rightjoystick.releaseCanvas();
  44958. };
  44959. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44960. return "FreeCameraVirtualJoystickInput";
  44961. };
  44962. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44963. return "virtualJoystick";
  44964. };
  44965. return FreeCameraVirtualJoystickInput;
  44966. }());
  44967. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44968. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44969. })(BABYLON || (BABYLON = {}));
  44970. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44971. var BABYLON;
  44972. (function (BABYLON) {
  44973. var AnaglyphPostProcess = (function (_super) {
  44974. __extends(AnaglyphPostProcess, _super);
  44975. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44976. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44977. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44978. _this.onApplyObservable.add(function (effect) {
  44979. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44980. });
  44981. return _this;
  44982. }
  44983. return AnaglyphPostProcess;
  44984. }(BABYLON.PostProcess));
  44985. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44986. })(BABYLON || (BABYLON = {}));
  44987. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44988. var BABYLON;
  44989. (function (BABYLON) {
  44990. var OutlineRenderer = (function () {
  44991. function OutlineRenderer(scene) {
  44992. this._scene = scene;
  44993. }
  44994. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44995. var _this = this;
  44996. if (useOverlay === void 0) { useOverlay = false; }
  44997. var scene = this._scene;
  44998. var engine = this._scene.getEngine();
  44999. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  45000. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  45001. return;
  45002. }
  45003. var mesh = subMesh.getRenderingMesh();
  45004. var material = subMesh.getMaterial();
  45005. engine.enableEffect(this._effect);
  45006. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  45007. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  45008. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45009. // Bones
  45010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45011. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45012. }
  45013. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  45014. // Alpha test
  45015. if (material && material.needAlphaTesting()) {
  45016. var alphaTexture = material.getAlphaTestTexture();
  45017. this._effect.setTexture("diffuseSampler", alphaTexture);
  45018. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45019. }
  45020. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  45021. };
  45022. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  45023. var defines = [];
  45024. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  45025. var mesh = subMesh.getMesh();
  45026. var material = subMesh.getMaterial();
  45027. // Alpha test
  45028. if (material && material.needAlphaTesting()) {
  45029. defines.push("#define ALPHATEST");
  45030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45031. attribs.push(BABYLON.VertexBuffer.UVKind);
  45032. defines.push("#define UV1");
  45033. }
  45034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45035. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45036. defines.push("#define UV2");
  45037. }
  45038. }
  45039. // Bones
  45040. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45043. if (mesh.numBoneInfluencers > 4) {
  45044. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45045. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45046. }
  45047. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45048. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45049. }
  45050. else {
  45051. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45052. }
  45053. // Instances
  45054. if (useInstances) {
  45055. defines.push("#define INSTANCES");
  45056. attribs.push("world0");
  45057. attribs.push("world1");
  45058. attribs.push("world2");
  45059. attribs.push("world3");
  45060. }
  45061. // Get correct effect
  45062. var join = defines.join("\n");
  45063. if (this._cachedDefines !== join) {
  45064. this._cachedDefines = join;
  45065. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  45066. }
  45067. return this._effect.isReady();
  45068. };
  45069. return OutlineRenderer;
  45070. }());
  45071. BABYLON.OutlineRenderer = OutlineRenderer;
  45072. })(BABYLON || (BABYLON = {}));
  45073. //# sourceMappingURL=babylon.outlineRenderer.js.map
  45074. var BABYLON;
  45075. (function (BABYLON) {
  45076. var MeshAssetTask = (function () {
  45077. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  45078. this.name = name;
  45079. this.meshesNames = meshesNames;
  45080. this.rootUrl = rootUrl;
  45081. this.sceneFilename = sceneFilename;
  45082. this.isCompleted = false;
  45083. }
  45084. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45085. var _this = this;
  45086. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  45087. _this.loadedMeshes = meshes;
  45088. _this.loadedParticleSystems = particleSystems;
  45089. _this.loadedSkeletons = skeletons;
  45090. _this.isCompleted = true;
  45091. if (_this.onSuccess) {
  45092. _this.onSuccess(_this);
  45093. }
  45094. onSuccess();
  45095. }, null, function () {
  45096. if (_this.onError) {
  45097. _this.onError(_this);
  45098. }
  45099. onError();
  45100. });
  45101. };
  45102. return MeshAssetTask;
  45103. }());
  45104. BABYLON.MeshAssetTask = MeshAssetTask;
  45105. var TextFileAssetTask = (function () {
  45106. function TextFileAssetTask(name, url) {
  45107. this.name = name;
  45108. this.url = url;
  45109. this.isCompleted = false;
  45110. }
  45111. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45112. var _this = this;
  45113. BABYLON.Tools.LoadFile(this.url, function (data) {
  45114. _this.text = data;
  45115. _this.isCompleted = true;
  45116. if (_this.onSuccess) {
  45117. _this.onSuccess(_this);
  45118. }
  45119. onSuccess();
  45120. }, null, scene.database, false, function () {
  45121. if (_this.onError) {
  45122. _this.onError(_this);
  45123. }
  45124. onError();
  45125. });
  45126. };
  45127. return TextFileAssetTask;
  45128. }());
  45129. BABYLON.TextFileAssetTask = TextFileAssetTask;
  45130. var BinaryFileAssetTask = (function () {
  45131. function BinaryFileAssetTask(name, url) {
  45132. this.name = name;
  45133. this.url = url;
  45134. this.isCompleted = false;
  45135. }
  45136. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45137. var _this = this;
  45138. BABYLON.Tools.LoadFile(this.url, function (data) {
  45139. _this.data = data;
  45140. _this.isCompleted = true;
  45141. if (_this.onSuccess) {
  45142. _this.onSuccess(_this);
  45143. }
  45144. onSuccess();
  45145. }, null, scene.database, true, function () {
  45146. if (_this.onError) {
  45147. _this.onError(_this);
  45148. }
  45149. onError();
  45150. });
  45151. };
  45152. return BinaryFileAssetTask;
  45153. }());
  45154. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  45155. var ImageAssetTask = (function () {
  45156. function ImageAssetTask(name, url) {
  45157. this.name = name;
  45158. this.url = url;
  45159. this.isCompleted = false;
  45160. }
  45161. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45162. var _this = this;
  45163. var img = new Image();
  45164. BABYLON.Tools.SetCorsBehavior(this.url, img);
  45165. img.onload = function () {
  45166. _this.image = img;
  45167. _this.isCompleted = true;
  45168. if (_this.onSuccess) {
  45169. _this.onSuccess(_this);
  45170. }
  45171. onSuccess();
  45172. };
  45173. img.onerror = function () {
  45174. if (_this.onError) {
  45175. _this.onError(_this);
  45176. }
  45177. onError();
  45178. };
  45179. img.src = this.url;
  45180. };
  45181. return ImageAssetTask;
  45182. }());
  45183. BABYLON.ImageAssetTask = ImageAssetTask;
  45184. var TextureAssetTask = (function () {
  45185. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  45186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45187. this.name = name;
  45188. this.url = url;
  45189. this.noMipmap = noMipmap;
  45190. this.invertY = invertY;
  45191. this.samplingMode = samplingMode;
  45192. this.isCompleted = false;
  45193. }
  45194. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45195. var _this = this;
  45196. var onload = function () {
  45197. _this.isCompleted = true;
  45198. if (_this.onSuccess) {
  45199. _this.onSuccess(_this);
  45200. }
  45201. onSuccess();
  45202. };
  45203. var onerror = function () {
  45204. if (_this.onError) {
  45205. _this.onError(_this);
  45206. }
  45207. onError();
  45208. };
  45209. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  45210. };
  45211. return TextureAssetTask;
  45212. }());
  45213. BABYLON.TextureAssetTask = TextureAssetTask;
  45214. var CubeTextureAssetTask = (function () {
  45215. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  45216. this.name = name;
  45217. this.url = url;
  45218. this.extensions = extensions;
  45219. this.noMipmap = noMipmap;
  45220. this.files = files;
  45221. this.isCompleted = false;
  45222. }
  45223. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45224. var _this = this;
  45225. var onload = function () {
  45226. _this.isCompleted = true;
  45227. if (_this.onSuccess) {
  45228. _this.onSuccess(_this);
  45229. }
  45230. onSuccess();
  45231. };
  45232. var onerror = function () {
  45233. if (_this.onError) {
  45234. _this.onError(_this);
  45235. }
  45236. onError();
  45237. };
  45238. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  45239. };
  45240. return CubeTextureAssetTask;
  45241. }());
  45242. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  45243. var AssetsManager = (function () {
  45244. function AssetsManager(scene) {
  45245. this.tasks = new Array();
  45246. this.waitingTasksCount = 0;
  45247. this.useDefaultLoadingScreen = true;
  45248. this._scene = scene;
  45249. }
  45250. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  45251. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  45252. this.tasks.push(task);
  45253. return task;
  45254. };
  45255. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  45256. var task = new TextFileAssetTask(taskName, url);
  45257. this.tasks.push(task);
  45258. return task;
  45259. };
  45260. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  45261. var task = new BinaryFileAssetTask(taskName, url);
  45262. this.tasks.push(task);
  45263. return task;
  45264. };
  45265. AssetsManager.prototype.addImageTask = function (taskName, url) {
  45266. var task = new ImageAssetTask(taskName, url);
  45267. this.tasks.push(task);
  45268. return task;
  45269. };
  45270. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  45271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45272. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  45273. this.tasks.push(task);
  45274. return task;
  45275. };
  45276. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  45277. this.waitingTasksCount--;
  45278. if (this.waitingTasksCount === 0) {
  45279. if (this.onFinish) {
  45280. this.onFinish(this.tasks);
  45281. }
  45282. this._scene.getEngine().hideLoadingUI();
  45283. }
  45284. };
  45285. AssetsManager.prototype._runTask = function (task) {
  45286. var _this = this;
  45287. task.run(this._scene, function () {
  45288. if (_this.onTaskSuccess) {
  45289. _this.onTaskSuccess(task);
  45290. }
  45291. _this._decreaseWaitingTasksCount();
  45292. }, function () {
  45293. if (_this.onTaskError) {
  45294. _this.onTaskError(task);
  45295. }
  45296. _this._decreaseWaitingTasksCount();
  45297. });
  45298. };
  45299. AssetsManager.prototype.reset = function () {
  45300. this.tasks = new Array();
  45301. return this;
  45302. };
  45303. AssetsManager.prototype.load = function () {
  45304. this.waitingTasksCount = this.tasks.length;
  45305. if (this.waitingTasksCount === 0) {
  45306. if (this.onFinish) {
  45307. this.onFinish(this.tasks);
  45308. }
  45309. return this;
  45310. }
  45311. if (this.useDefaultLoadingScreen) {
  45312. this._scene.getEngine().displayLoadingUI();
  45313. }
  45314. for (var index = 0; index < this.tasks.length; index++) {
  45315. var task = this.tasks[index];
  45316. this._runTask(task);
  45317. }
  45318. return this;
  45319. };
  45320. return AssetsManager;
  45321. }());
  45322. BABYLON.AssetsManager = AssetsManager;
  45323. })(BABYLON || (BABYLON = {}));
  45324. //# sourceMappingURL=babylon.assetsManager.js.map
  45325. var BABYLON;
  45326. (function (BABYLON) {
  45327. var VRCameraMetrics = (function () {
  45328. function VRCameraMetrics() {
  45329. this.compensateDistortion = true;
  45330. }
  45331. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45332. get: function () {
  45333. return this.hResolution / (2 * this.vResolution);
  45334. },
  45335. enumerable: true,
  45336. configurable: true
  45337. });
  45338. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45339. get: function () {
  45340. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45346. get: function () {
  45347. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45348. var h = (4 * meters) / this.hScreenSize;
  45349. return BABYLON.Matrix.Translation(h, 0, 0);
  45350. },
  45351. enumerable: true,
  45352. configurable: true
  45353. });
  45354. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45355. get: function () {
  45356. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45357. var h = (4 * meters) / this.hScreenSize;
  45358. return BABYLON.Matrix.Translation(-h, 0, 0);
  45359. },
  45360. enumerable: true,
  45361. configurable: true
  45362. });
  45363. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45364. get: function () {
  45365. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45366. },
  45367. enumerable: true,
  45368. configurable: true
  45369. });
  45370. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45371. get: function () {
  45372. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. VRCameraMetrics.GetDefault = function () {
  45378. var result = new VRCameraMetrics();
  45379. result.hResolution = 1280;
  45380. result.vResolution = 800;
  45381. result.hScreenSize = 0.149759993;
  45382. result.vScreenSize = 0.0935999975;
  45383. result.vScreenCenter = 0.0467999987;
  45384. result.eyeToScreenDistance = 0.0410000011;
  45385. result.lensSeparationDistance = 0.0635000020;
  45386. result.interpupillaryDistance = 0.0640000030;
  45387. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45388. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45389. result.postProcessScaleFactor = 1.714605507808412;
  45390. result.lensCenterOffset = 0.151976421;
  45391. return result;
  45392. };
  45393. return VRCameraMetrics;
  45394. }());
  45395. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45396. })(BABYLON || (BABYLON = {}));
  45397. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  45398. var BABYLON;
  45399. (function (BABYLON) {
  45400. var WebVRFreeCamera = (function (_super) {
  45401. __extends(WebVRFreeCamera, _super);
  45402. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  45403. if (compensateDistortion === void 0) { compensateDistortion = false; }
  45404. if (webVROptions === void 0) { webVROptions = {}; }
  45405. var _this = _super.call(this, name, position, scene) || this;
  45406. _this.webVROptions = webVROptions;
  45407. _this._vrDevice = null;
  45408. _this._cacheState = null;
  45409. _this._vrEnabled = false;
  45410. _this._attached = false;
  45411. //using the position provided as the current position offset
  45412. _this._positionOffset = position;
  45413. //enable VR
  45414. _this.getEngine().initWebVR();
  45415. if (!_this.getEngine().vrDisplaysPromise) {
  45416. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  45417. }
  45418. else {
  45419. //TODO get the metrics updated using the device's eye parameters!
  45420. //TODO also check that the device has the right capabilities!
  45421. _this._frameData = new VRFrameData();
  45422. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  45423. if (devices.length > 0) {
  45424. _this._vrEnabled = true;
  45425. if (_this.webVROptions.displayName) {
  45426. var found = devices.some(function (device) {
  45427. if (device.displayName === _this.webVROptions.displayName) {
  45428. _this._vrDevice = device;
  45429. return true;
  45430. }
  45431. else {
  45432. return false;
  45433. }
  45434. });
  45435. if (!found) {
  45436. _this._vrDevice = devices[0];
  45437. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  45438. }
  45439. }
  45440. else {
  45441. //choose the first one
  45442. _this._vrDevice = devices[0];
  45443. }
  45444. //reset the rig parameters.
  45445. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  45446. if (_this._attached) {
  45447. _this.getEngine().enableVR(_this._vrDevice);
  45448. }
  45449. }
  45450. else {
  45451. BABYLON.Tools.Error("No WebVR devices found!");
  45452. }
  45453. });
  45454. }
  45455. _this.rotationQuaternion = new BABYLON.Quaternion();
  45456. _this._quaternionCache = new BABYLON.Quaternion();
  45457. return _this;
  45458. }
  45459. WebVRFreeCamera.prototype._checkInputs = function () {
  45460. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  45461. var currentPost = this._frameData.pose;
  45462. //make sure we have data
  45463. if (currentPost && currentPost.orientation) {
  45464. this._cacheState = currentPost;
  45465. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  45466. if (this.webVROptions.trackPosition && this._cacheState.position) {
  45467. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  45468. //scale the position accordingly
  45469. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  45470. //add the position offset
  45471. this.position.addInPlace(this._positionOffset);
  45472. }
  45473. }
  45474. }
  45475. _super.prototype._checkInputs.call(this);
  45476. };
  45477. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45478. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45479. this._attached = true;
  45480. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45481. if (this._vrEnabled) {
  45482. this.getEngine().enableVR(this._vrDevice);
  45483. }
  45484. };
  45485. WebVRFreeCamera.prototype.detachControl = function (element) {
  45486. _super.prototype.detachControl.call(this, element);
  45487. this._vrEnabled = false;
  45488. this._attached = false;
  45489. this.getEngine().disableVR();
  45490. };
  45491. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45492. //Backwards comp.
  45493. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  45494. //this.getEngine().switchFullscreen(requestPointerlock);
  45495. };
  45496. WebVRFreeCamera.prototype.getClassName = function () {
  45497. return "WebVRFreeCamera";
  45498. };
  45499. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  45500. //uses the vrDisplay's "resetPose()".
  45501. //pitch and roll won't be affected.
  45502. this._vrDevice.resetPose();
  45503. };
  45504. /**
  45505. *
  45506. * Set the position offset of the VR camera
  45507. * The offset will be added to the WebVR pose, after scaling it (if set).
  45508. *
  45509. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  45510. *
  45511. * @memberOf WebVRFreeCamera
  45512. */
  45513. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  45514. if (newPosition) {
  45515. this._positionOffset = newPosition;
  45516. }
  45517. else {
  45518. this._positionOffset.copyFrom(this.position);
  45519. }
  45520. };
  45521. return WebVRFreeCamera;
  45522. }(BABYLON.FreeCamera));
  45523. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45524. })(BABYLON || (BABYLON = {}));
  45525. //# sourceMappingURL=babylon.webVRCamera.js.map
  45526. var BABYLON;
  45527. (function (BABYLON) {
  45528. // Standard optimizations
  45529. var SceneOptimization = (function () {
  45530. function SceneOptimization(priority) {
  45531. if (priority === void 0) { priority = 0; }
  45532. this.priority = priority;
  45533. this.apply = function (scene) {
  45534. return true; // Return true if everything that can be done was applied
  45535. };
  45536. }
  45537. return SceneOptimization;
  45538. }());
  45539. BABYLON.SceneOptimization = SceneOptimization;
  45540. var TextureOptimization = (function (_super) {
  45541. __extends(TextureOptimization, _super);
  45542. function TextureOptimization(priority, maximumSize) {
  45543. if (priority === void 0) { priority = 0; }
  45544. if (maximumSize === void 0) { maximumSize = 1024; }
  45545. var _this = _super.call(this, priority) || this;
  45546. _this.priority = priority;
  45547. _this.maximumSize = maximumSize;
  45548. _this.apply = function (scene) {
  45549. var allDone = true;
  45550. for (var index = 0; index < scene.textures.length; index++) {
  45551. var texture = scene.textures[index];
  45552. if (!texture.canRescale) {
  45553. continue;
  45554. }
  45555. var currentSize = texture.getSize();
  45556. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45557. if (maxDimension > _this.maximumSize) {
  45558. texture.scale(0.5);
  45559. allDone = false;
  45560. }
  45561. }
  45562. return allDone;
  45563. };
  45564. return _this;
  45565. }
  45566. return TextureOptimization;
  45567. }(SceneOptimization));
  45568. BABYLON.TextureOptimization = TextureOptimization;
  45569. var HardwareScalingOptimization = (function (_super) {
  45570. __extends(HardwareScalingOptimization, _super);
  45571. function HardwareScalingOptimization(priority, maximumScale) {
  45572. if (priority === void 0) { priority = 0; }
  45573. if (maximumScale === void 0) { maximumScale = 2; }
  45574. var _this = _super.call(this, priority) || this;
  45575. _this.priority = priority;
  45576. _this.maximumScale = maximumScale;
  45577. _this._currentScale = 1;
  45578. _this.apply = function (scene) {
  45579. _this._currentScale++;
  45580. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45581. return _this._currentScale >= _this.maximumScale;
  45582. };
  45583. return _this;
  45584. }
  45585. return HardwareScalingOptimization;
  45586. }(SceneOptimization));
  45587. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45588. var ShadowsOptimization = (function (_super) {
  45589. __extends(ShadowsOptimization, _super);
  45590. function ShadowsOptimization() {
  45591. var _this = _super.apply(this, arguments) || this;
  45592. _this.apply = function (scene) {
  45593. scene.shadowsEnabled = false;
  45594. return true;
  45595. };
  45596. return _this;
  45597. }
  45598. return ShadowsOptimization;
  45599. }(SceneOptimization));
  45600. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45601. var PostProcessesOptimization = (function (_super) {
  45602. __extends(PostProcessesOptimization, _super);
  45603. function PostProcessesOptimization() {
  45604. var _this = _super.apply(this, arguments) || this;
  45605. _this.apply = function (scene) {
  45606. scene.postProcessesEnabled = false;
  45607. return true;
  45608. };
  45609. return _this;
  45610. }
  45611. return PostProcessesOptimization;
  45612. }(SceneOptimization));
  45613. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45614. var LensFlaresOptimization = (function (_super) {
  45615. __extends(LensFlaresOptimization, _super);
  45616. function LensFlaresOptimization() {
  45617. var _this = _super.apply(this, arguments) || this;
  45618. _this.apply = function (scene) {
  45619. scene.lensFlaresEnabled = false;
  45620. return true;
  45621. };
  45622. return _this;
  45623. }
  45624. return LensFlaresOptimization;
  45625. }(SceneOptimization));
  45626. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45627. var ParticlesOptimization = (function (_super) {
  45628. __extends(ParticlesOptimization, _super);
  45629. function ParticlesOptimization() {
  45630. var _this = _super.apply(this, arguments) || this;
  45631. _this.apply = function (scene) {
  45632. scene.particlesEnabled = false;
  45633. return true;
  45634. };
  45635. return _this;
  45636. }
  45637. return ParticlesOptimization;
  45638. }(SceneOptimization));
  45639. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45640. var RenderTargetsOptimization = (function (_super) {
  45641. __extends(RenderTargetsOptimization, _super);
  45642. function RenderTargetsOptimization() {
  45643. var _this = _super.apply(this, arguments) || this;
  45644. _this.apply = function (scene) {
  45645. scene.renderTargetsEnabled = false;
  45646. return true;
  45647. };
  45648. return _this;
  45649. }
  45650. return RenderTargetsOptimization;
  45651. }(SceneOptimization));
  45652. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45653. var MergeMeshesOptimization = (function (_super) {
  45654. __extends(MergeMeshesOptimization, _super);
  45655. function MergeMeshesOptimization() {
  45656. var _this = _super.apply(this, arguments) || this;
  45657. _this._canBeMerged = function (abstractMesh) {
  45658. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45659. return false;
  45660. }
  45661. var mesh = abstractMesh;
  45662. if (!mesh.isVisible || !mesh.isEnabled()) {
  45663. return false;
  45664. }
  45665. if (mesh.instances.length > 0) {
  45666. return false;
  45667. }
  45668. if (mesh.skeleton || mesh.hasLODLevels) {
  45669. return false;
  45670. }
  45671. if (mesh.parent) {
  45672. return false;
  45673. }
  45674. return true;
  45675. };
  45676. _this.apply = function (scene, updateSelectionTree) {
  45677. var globalPool = scene.meshes.slice(0);
  45678. var globalLength = globalPool.length;
  45679. for (var index = 0; index < globalLength; index++) {
  45680. var currentPool = new Array();
  45681. var current = globalPool[index];
  45682. // Checks
  45683. if (!_this._canBeMerged(current)) {
  45684. continue;
  45685. }
  45686. currentPool.push(current);
  45687. // Find compatible meshes
  45688. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45689. var otherMesh = globalPool[subIndex];
  45690. if (!_this._canBeMerged(otherMesh)) {
  45691. continue;
  45692. }
  45693. if (otherMesh.material !== current.material) {
  45694. continue;
  45695. }
  45696. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45697. continue;
  45698. }
  45699. currentPool.push(otherMesh);
  45700. globalLength--;
  45701. globalPool.splice(subIndex, 1);
  45702. subIndex--;
  45703. }
  45704. if (currentPool.length < 2) {
  45705. continue;
  45706. }
  45707. // Merge meshes
  45708. BABYLON.Mesh.MergeMeshes(currentPool);
  45709. }
  45710. if (updateSelectionTree != undefined) {
  45711. if (updateSelectionTree) {
  45712. scene.createOrUpdateSelectionOctree();
  45713. }
  45714. }
  45715. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45716. scene.createOrUpdateSelectionOctree();
  45717. }
  45718. return true;
  45719. };
  45720. return _this;
  45721. }
  45722. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45723. get: function () {
  45724. return MergeMeshesOptimization._UpdateSelectionTree;
  45725. },
  45726. set: function (value) {
  45727. MergeMeshesOptimization._UpdateSelectionTree = value;
  45728. },
  45729. enumerable: true,
  45730. configurable: true
  45731. });
  45732. return MergeMeshesOptimization;
  45733. }(SceneOptimization));
  45734. MergeMeshesOptimization._UpdateSelectionTree = false;
  45735. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45736. // Options
  45737. var SceneOptimizerOptions = (function () {
  45738. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45739. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45740. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45741. this.targetFrameRate = targetFrameRate;
  45742. this.trackerDuration = trackerDuration;
  45743. this.optimizations = new Array();
  45744. }
  45745. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45746. var result = new SceneOptimizerOptions(targetFrameRate);
  45747. var priority = 0;
  45748. result.optimizations.push(new MergeMeshesOptimization(priority));
  45749. result.optimizations.push(new ShadowsOptimization(priority));
  45750. result.optimizations.push(new LensFlaresOptimization(priority));
  45751. // Next priority
  45752. priority++;
  45753. result.optimizations.push(new PostProcessesOptimization(priority));
  45754. result.optimizations.push(new ParticlesOptimization(priority));
  45755. // Next priority
  45756. priority++;
  45757. result.optimizations.push(new TextureOptimization(priority, 1024));
  45758. return result;
  45759. };
  45760. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45761. var result = new SceneOptimizerOptions(targetFrameRate);
  45762. var priority = 0;
  45763. result.optimizations.push(new MergeMeshesOptimization(priority));
  45764. result.optimizations.push(new ShadowsOptimization(priority));
  45765. result.optimizations.push(new LensFlaresOptimization(priority));
  45766. // Next priority
  45767. priority++;
  45768. result.optimizations.push(new PostProcessesOptimization(priority));
  45769. result.optimizations.push(new ParticlesOptimization(priority));
  45770. // Next priority
  45771. priority++;
  45772. result.optimizations.push(new TextureOptimization(priority, 512));
  45773. // Next priority
  45774. priority++;
  45775. result.optimizations.push(new RenderTargetsOptimization(priority));
  45776. // Next priority
  45777. priority++;
  45778. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45779. return result;
  45780. };
  45781. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45782. var result = new SceneOptimizerOptions(targetFrameRate);
  45783. var priority = 0;
  45784. result.optimizations.push(new MergeMeshesOptimization(priority));
  45785. result.optimizations.push(new ShadowsOptimization(priority));
  45786. result.optimizations.push(new LensFlaresOptimization(priority));
  45787. // Next priority
  45788. priority++;
  45789. result.optimizations.push(new PostProcessesOptimization(priority));
  45790. result.optimizations.push(new ParticlesOptimization(priority));
  45791. // Next priority
  45792. priority++;
  45793. result.optimizations.push(new TextureOptimization(priority, 256));
  45794. // Next priority
  45795. priority++;
  45796. result.optimizations.push(new RenderTargetsOptimization(priority));
  45797. // Next priority
  45798. priority++;
  45799. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45800. return result;
  45801. };
  45802. return SceneOptimizerOptions;
  45803. }());
  45804. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45805. // Scene optimizer tool
  45806. var SceneOptimizer = (function () {
  45807. function SceneOptimizer() {
  45808. }
  45809. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45810. // TODO: add an epsilon
  45811. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45812. if (onSuccess) {
  45813. onSuccess();
  45814. }
  45815. return;
  45816. }
  45817. // Apply current level of optimizations
  45818. var allDone = true;
  45819. var noOptimizationApplied = true;
  45820. for (var index = 0; index < options.optimizations.length; index++) {
  45821. var optimization = options.optimizations[index];
  45822. if (optimization.priority === currentPriorityLevel) {
  45823. noOptimizationApplied = false;
  45824. allDone = allDone && optimization.apply(scene);
  45825. }
  45826. }
  45827. // If no optimization was applied, this is a failure :(
  45828. if (noOptimizationApplied) {
  45829. if (onFailure) {
  45830. onFailure();
  45831. }
  45832. return;
  45833. }
  45834. // If all optimizations were done, move to next level
  45835. if (allDone) {
  45836. currentPriorityLevel++;
  45837. }
  45838. // Let's the system running for a specific amount of time before checking FPS
  45839. scene.executeWhenReady(function () {
  45840. setTimeout(function () {
  45841. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45842. }, options.trackerDuration);
  45843. });
  45844. };
  45845. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45846. if (!options) {
  45847. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45848. }
  45849. // Let's the system running for a specific amount of time before checking FPS
  45850. scene.executeWhenReady(function () {
  45851. setTimeout(function () {
  45852. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45853. }, options.trackerDuration);
  45854. });
  45855. };
  45856. return SceneOptimizer;
  45857. }());
  45858. BABYLON.SceneOptimizer = SceneOptimizer;
  45859. })(BABYLON || (BABYLON = {}));
  45860. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45861. var BABYLON;
  45862. (function (BABYLON) {
  45863. var Internals;
  45864. (function (Internals) {
  45865. var MeshLODLevel = (function () {
  45866. function MeshLODLevel(distance, mesh) {
  45867. this.distance = distance;
  45868. this.mesh = mesh;
  45869. }
  45870. return MeshLODLevel;
  45871. }());
  45872. Internals.MeshLODLevel = MeshLODLevel;
  45873. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45874. })(BABYLON || (BABYLON = {}));
  45875. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45876. var BABYLON;
  45877. (function (BABYLON) {
  45878. var RawTexture = (function (_super) {
  45879. __extends(RawTexture, _super);
  45880. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45881. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45882. if (invertY === void 0) { invertY = false; }
  45883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45884. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45885. _this.format = format;
  45886. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45887. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45888. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45889. return _this;
  45890. }
  45891. RawTexture.prototype.update = function (data) {
  45892. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45893. };
  45894. // Statics
  45895. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45896. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45897. if (invertY === void 0) { invertY = false; }
  45898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45899. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45900. };
  45901. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45902. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45903. if (invertY === void 0) { invertY = false; }
  45904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45905. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45906. };
  45907. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45908. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45909. if (invertY === void 0) { invertY = false; }
  45910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45911. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45912. };
  45913. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45914. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45915. if (invertY === void 0) { invertY = false; }
  45916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45917. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45918. };
  45919. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45920. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45921. if (invertY === void 0) { invertY = false; }
  45922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45923. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45924. };
  45925. return RawTexture;
  45926. }(BABYLON.Texture));
  45927. BABYLON.RawTexture = RawTexture;
  45928. })(BABYLON || (BABYLON = {}));
  45929. //# sourceMappingURL=babylon.rawTexture.js.map
  45930. var BABYLON;
  45931. (function (BABYLON) {
  45932. var IndexedVector2 = (function (_super) {
  45933. __extends(IndexedVector2, _super);
  45934. function IndexedVector2(original, index) {
  45935. var _this = _super.call(this, original.x, original.y) || this;
  45936. _this.index = index;
  45937. return _this;
  45938. }
  45939. return IndexedVector2;
  45940. }(BABYLON.Vector2));
  45941. var PolygonPoints = (function () {
  45942. function PolygonPoints() {
  45943. this.elements = new Array();
  45944. }
  45945. PolygonPoints.prototype.add = function (originalPoints) {
  45946. var _this = this;
  45947. var result = new Array();
  45948. originalPoints.forEach(function (point) {
  45949. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45950. var newPoint = new IndexedVector2(point, _this.elements.length);
  45951. result.push(newPoint);
  45952. _this.elements.push(newPoint);
  45953. }
  45954. });
  45955. return result;
  45956. };
  45957. PolygonPoints.prototype.computeBounds = function () {
  45958. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45959. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45960. this.elements.forEach(function (point) {
  45961. // x
  45962. if (point.x < lmin.x) {
  45963. lmin.x = point.x;
  45964. }
  45965. else if (point.x > lmax.x) {
  45966. lmax.x = point.x;
  45967. }
  45968. // y
  45969. if (point.y < lmin.y) {
  45970. lmin.y = point.y;
  45971. }
  45972. else if (point.y > lmax.y) {
  45973. lmax.y = point.y;
  45974. }
  45975. });
  45976. return {
  45977. min: lmin,
  45978. max: lmax,
  45979. width: lmax.x - lmin.x,
  45980. height: lmax.y - lmin.y
  45981. };
  45982. };
  45983. return PolygonPoints;
  45984. }());
  45985. var Polygon = (function () {
  45986. function Polygon() {
  45987. }
  45988. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45989. return [
  45990. new BABYLON.Vector2(xmin, ymin),
  45991. new BABYLON.Vector2(xmax, ymin),
  45992. new BABYLON.Vector2(xmax, ymax),
  45993. new BABYLON.Vector2(xmin, ymax)
  45994. ];
  45995. };
  45996. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45997. if (cx === void 0) { cx = 0; }
  45998. if (cy === void 0) { cy = 0; }
  45999. if (numberOfSides === void 0) { numberOfSides = 32; }
  46000. var result = new Array();
  46001. var angle = 0;
  46002. var increment = (Math.PI * 2) / numberOfSides;
  46003. for (var i = 0; i < numberOfSides; i++) {
  46004. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  46005. angle -= increment;
  46006. }
  46007. return result;
  46008. };
  46009. Polygon.Parse = function (input) {
  46010. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  46011. var i, result = [];
  46012. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  46013. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  46014. }
  46015. return result;
  46016. };
  46017. Polygon.StartingAt = function (x, y) {
  46018. return BABYLON.Path2.StartingAt(x, y);
  46019. };
  46020. return Polygon;
  46021. }());
  46022. BABYLON.Polygon = Polygon;
  46023. var PolygonMeshBuilder = (function () {
  46024. function PolygonMeshBuilder(name, contours, scene) {
  46025. this._points = new PolygonPoints();
  46026. this._outlinepoints = new PolygonPoints();
  46027. this._holes = [];
  46028. this._epoints = new Array();
  46029. this._eholes = new Array();
  46030. this._name = name;
  46031. this._scene = scene;
  46032. var points;
  46033. if (contours instanceof BABYLON.Path2) {
  46034. points = contours.getPoints();
  46035. }
  46036. else {
  46037. points = contours;
  46038. }
  46039. this._addToepoint(points);
  46040. this._points.add(points);
  46041. this._outlinepoints.add(points);
  46042. }
  46043. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  46044. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  46045. var p = points_1[_i];
  46046. this._epoints.push(p.x, p.y);
  46047. }
  46048. };
  46049. PolygonMeshBuilder.prototype.addHole = function (hole) {
  46050. this._points.add(hole);
  46051. var holepoints = new PolygonPoints();
  46052. holepoints.add(hole);
  46053. this._holes.push(holepoints);
  46054. this._eholes.push(this._epoints.length / 2);
  46055. this._addToepoint(hole);
  46056. return this;
  46057. };
  46058. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  46059. var _this = this;
  46060. if (updatable === void 0) { updatable = false; }
  46061. var result = new BABYLON.Mesh(this._name, this._scene);
  46062. var normals = [];
  46063. var positions = [];
  46064. var uvs = [];
  46065. var bounds = this._points.computeBounds();
  46066. this._points.elements.forEach(function (p) {
  46067. normals.push(0, 1.0, 0);
  46068. positions.push(p.x, 0, p.y);
  46069. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  46070. });
  46071. var indices = [];
  46072. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  46073. for (var i = 0; i < res.length; i++) {
  46074. indices.push(res[i]);
  46075. }
  46076. if (depth > 0) {
  46077. var positionscount = (positions.length / 3); //get the current pointcount
  46078. this._points.elements.forEach(function (p) {
  46079. normals.push(0, -1.0, 0);
  46080. positions.push(p.x, -depth, p.y);
  46081. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  46082. });
  46083. var totalCount = indices.length;
  46084. for (var i = 0; i < totalCount; i += 3) {
  46085. var i0 = indices[i + 0];
  46086. var i1 = indices[i + 1];
  46087. var i2 = indices[i + 2];
  46088. indices.push(i2 + positionscount);
  46089. indices.push(i1 + positionscount);
  46090. indices.push(i0 + positionscount);
  46091. }
  46092. //Add the sides
  46093. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  46094. this._holes.forEach(function (hole) {
  46095. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  46096. });
  46097. }
  46098. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  46099. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  46100. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  46101. result.setIndices(indices);
  46102. return result;
  46103. };
  46104. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  46105. var StartIndex = positions.length / 3;
  46106. var ulength = 0;
  46107. for (var i = 0; i < points.elements.length; i++) {
  46108. var p = points.elements[i];
  46109. var p1;
  46110. if ((i + 1) > points.elements.length - 1) {
  46111. p1 = points.elements[0];
  46112. }
  46113. else {
  46114. p1 = points.elements[i + 1];
  46115. }
  46116. positions.push(p.x, 0, p.y);
  46117. positions.push(p.x, -depth, p.y);
  46118. positions.push(p1.x, 0, p1.y);
  46119. positions.push(p1.x, -depth, p1.y);
  46120. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  46121. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  46122. var v3 = v2.subtract(v1);
  46123. var v4 = new BABYLON.Vector3(0, 1, 0);
  46124. var vn = BABYLON.Vector3.Cross(v3, v4);
  46125. vn = vn.normalize();
  46126. uvs.push(ulength / bounds.width, 0);
  46127. uvs.push(ulength / bounds.width, 1);
  46128. ulength += v3.length();
  46129. uvs.push((ulength / bounds.width), 0);
  46130. uvs.push((ulength / bounds.width), 1);
  46131. if (!flip) {
  46132. normals.push(-vn.x, -vn.y, -vn.z);
  46133. normals.push(-vn.x, -vn.y, -vn.z);
  46134. normals.push(-vn.x, -vn.y, -vn.z);
  46135. normals.push(-vn.x, -vn.y, -vn.z);
  46136. indices.push(StartIndex);
  46137. indices.push(StartIndex + 1);
  46138. indices.push(StartIndex + 2);
  46139. indices.push(StartIndex + 1);
  46140. indices.push(StartIndex + 3);
  46141. indices.push(StartIndex + 2);
  46142. }
  46143. else {
  46144. normals.push(vn.x, vn.y, vn.z);
  46145. normals.push(vn.x, vn.y, vn.z);
  46146. normals.push(vn.x, vn.y, vn.z);
  46147. normals.push(vn.x, vn.y, vn.z);
  46148. indices.push(StartIndex);
  46149. indices.push(StartIndex + 2);
  46150. indices.push(StartIndex + 1);
  46151. indices.push(StartIndex + 1);
  46152. indices.push(StartIndex + 2);
  46153. indices.push(StartIndex + 3);
  46154. }
  46155. StartIndex += 4;
  46156. }
  46157. ;
  46158. };
  46159. return PolygonMeshBuilder;
  46160. }());
  46161. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  46162. })(BABYLON || (BABYLON = {}));
  46163. //# sourceMappingURL=babylon.polygonMesh.js.map
  46164. var BABYLON;
  46165. (function (BABYLON) {
  46166. var Octree = (function () {
  46167. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  46168. if (maxDepth === void 0) { maxDepth = 2; }
  46169. this.maxDepth = maxDepth;
  46170. this.dynamicContent = new Array();
  46171. this._maxBlockCapacity = maxBlockCapacity || 64;
  46172. this._selectionContent = new BABYLON.SmartArray(1024);
  46173. this._creationFunc = creationFunc;
  46174. }
  46175. // Methods
  46176. Octree.prototype.update = function (worldMin, worldMax, entries) {
  46177. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  46178. };
  46179. Octree.prototype.addMesh = function (entry) {
  46180. for (var index = 0; index < this.blocks.length; index++) {
  46181. var block = this.blocks[index];
  46182. block.addEntry(entry);
  46183. }
  46184. };
  46185. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  46186. this._selectionContent.reset();
  46187. for (var index = 0; index < this.blocks.length; index++) {
  46188. var block = this.blocks[index];
  46189. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  46190. }
  46191. if (allowDuplicate) {
  46192. this._selectionContent.concat(this.dynamicContent);
  46193. }
  46194. else {
  46195. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46196. }
  46197. return this._selectionContent;
  46198. };
  46199. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  46200. this._selectionContent.reset();
  46201. for (var index = 0; index < this.blocks.length; index++) {
  46202. var block = this.blocks[index];
  46203. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  46204. }
  46205. if (allowDuplicate) {
  46206. this._selectionContent.concat(this.dynamicContent);
  46207. }
  46208. else {
  46209. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46210. }
  46211. return this._selectionContent;
  46212. };
  46213. Octree.prototype.intersectsRay = function (ray) {
  46214. this._selectionContent.reset();
  46215. for (var index = 0; index < this.blocks.length; index++) {
  46216. var block = this.blocks[index];
  46217. block.intersectsRay(ray, this._selectionContent);
  46218. }
  46219. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46220. return this._selectionContent;
  46221. };
  46222. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  46223. target.blocks = new Array();
  46224. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  46225. // Segmenting space
  46226. for (var x = 0; x < 2; x++) {
  46227. for (var y = 0; y < 2; y++) {
  46228. for (var z = 0; z < 2; z++) {
  46229. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  46230. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  46231. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  46232. block.addEntries(entries);
  46233. target.blocks.push(block);
  46234. }
  46235. }
  46236. }
  46237. };
  46238. return Octree;
  46239. }());
  46240. Octree.CreationFuncForMeshes = function (entry, block) {
  46241. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46242. block.entries.push(entry);
  46243. }
  46244. };
  46245. Octree.CreationFuncForSubMeshes = function (entry, block) {
  46246. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46247. block.entries.push(entry);
  46248. }
  46249. };
  46250. BABYLON.Octree = Octree;
  46251. })(BABYLON || (BABYLON = {}));
  46252. //# sourceMappingURL=babylon.octree.js.map
  46253. var BABYLON;
  46254. (function (BABYLON) {
  46255. var OctreeBlock = (function () {
  46256. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  46257. this.entries = new Array();
  46258. this._boundingVectors = new Array();
  46259. this._capacity = capacity;
  46260. this._depth = depth;
  46261. this._maxDepth = maxDepth;
  46262. this._creationFunc = creationFunc;
  46263. this._minPoint = minPoint;
  46264. this._maxPoint = maxPoint;
  46265. this._boundingVectors.push(minPoint.clone());
  46266. this._boundingVectors.push(maxPoint.clone());
  46267. this._boundingVectors.push(minPoint.clone());
  46268. this._boundingVectors[2].x = maxPoint.x;
  46269. this._boundingVectors.push(minPoint.clone());
  46270. this._boundingVectors[3].y = maxPoint.y;
  46271. this._boundingVectors.push(minPoint.clone());
  46272. this._boundingVectors[4].z = maxPoint.z;
  46273. this._boundingVectors.push(maxPoint.clone());
  46274. this._boundingVectors[5].z = minPoint.z;
  46275. this._boundingVectors.push(maxPoint.clone());
  46276. this._boundingVectors[6].x = minPoint.x;
  46277. this._boundingVectors.push(maxPoint.clone());
  46278. this._boundingVectors[7].y = minPoint.y;
  46279. }
  46280. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  46281. // Property
  46282. get: function () {
  46283. return this._capacity;
  46284. },
  46285. enumerable: true,
  46286. configurable: true
  46287. });
  46288. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  46289. get: function () {
  46290. return this._minPoint;
  46291. },
  46292. enumerable: true,
  46293. configurable: true
  46294. });
  46295. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  46296. get: function () {
  46297. return this._maxPoint;
  46298. },
  46299. enumerable: true,
  46300. configurable: true
  46301. });
  46302. // Methods
  46303. OctreeBlock.prototype.addEntry = function (entry) {
  46304. if (this.blocks) {
  46305. for (var index = 0; index < this.blocks.length; index++) {
  46306. var block = this.blocks[index];
  46307. block.addEntry(entry);
  46308. }
  46309. return;
  46310. }
  46311. this._creationFunc(entry, this);
  46312. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46313. this.createInnerBlocks();
  46314. }
  46315. };
  46316. OctreeBlock.prototype.addEntries = function (entries) {
  46317. for (var index = 0; index < entries.length; index++) {
  46318. var mesh = entries[index];
  46319. this.addEntry(mesh);
  46320. }
  46321. };
  46322. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46323. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46324. if (this.blocks) {
  46325. for (var index = 0; index < this.blocks.length; index++) {
  46326. var block = this.blocks[index];
  46327. block.select(frustumPlanes, selection, allowDuplicate);
  46328. }
  46329. return;
  46330. }
  46331. if (allowDuplicate) {
  46332. selection.concat(this.entries);
  46333. }
  46334. else {
  46335. selection.concatWithNoDuplicate(this.entries);
  46336. }
  46337. }
  46338. };
  46339. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46340. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46341. if (this.blocks) {
  46342. for (var index = 0; index < this.blocks.length; index++) {
  46343. var block = this.blocks[index];
  46344. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46345. }
  46346. return;
  46347. }
  46348. if (allowDuplicate) {
  46349. selection.concat(this.entries);
  46350. }
  46351. else {
  46352. selection.concatWithNoDuplicate(this.entries);
  46353. }
  46354. }
  46355. };
  46356. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46357. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46358. if (this.blocks) {
  46359. for (var index = 0; index < this.blocks.length; index++) {
  46360. var block = this.blocks[index];
  46361. block.intersectsRay(ray, selection);
  46362. }
  46363. return;
  46364. }
  46365. selection.concatWithNoDuplicate(this.entries);
  46366. }
  46367. };
  46368. OctreeBlock.prototype.createInnerBlocks = function () {
  46369. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46370. };
  46371. return OctreeBlock;
  46372. }());
  46373. BABYLON.OctreeBlock = OctreeBlock;
  46374. })(BABYLON || (BABYLON = {}));
  46375. //# sourceMappingURL=babylon.octreeBlock.js.map
  46376. var BABYLON;
  46377. (function (BABYLON) {
  46378. var BlurPostProcess = (function (_super) {
  46379. __extends(BlurPostProcess, _super);
  46380. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46382. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  46383. _this.direction = direction;
  46384. _this.blurWidth = blurWidth;
  46385. _this.onApplyObservable.add(function (effect) {
  46386. effect.setFloat2("screenSize", _this.width, _this.height);
  46387. effect.setVector2("direction", _this.direction);
  46388. effect.setFloat("blurWidth", _this.blurWidth);
  46389. });
  46390. return _this;
  46391. }
  46392. return BlurPostProcess;
  46393. }(BABYLON.PostProcess));
  46394. BABYLON.BlurPostProcess = BlurPostProcess;
  46395. })(BABYLON || (BABYLON = {}));
  46396. //# sourceMappingURL=babylon.blurPostProcess.js.map
  46397. var BABYLON;
  46398. (function (BABYLON) {
  46399. var RefractionPostProcess = (function (_super) {
  46400. __extends(RefractionPostProcess, _super);
  46401. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46402. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  46403. _this.color = color;
  46404. _this.depth = depth;
  46405. _this.colorLevel = colorLevel;
  46406. _this.onActivateObservable.add(function (cam) {
  46407. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46408. });
  46409. _this.onApplyObservable.add(function (effect) {
  46410. effect.setColor3("baseColor", _this.color);
  46411. effect.setFloat("depth", _this.depth);
  46412. effect.setFloat("colorLevel", _this.colorLevel);
  46413. effect.setTexture("refractionSampler", _this._refRexture);
  46414. });
  46415. return _this;
  46416. }
  46417. // Methods
  46418. RefractionPostProcess.prototype.dispose = function (camera) {
  46419. if (this._refRexture) {
  46420. this._refRexture.dispose();
  46421. }
  46422. _super.prototype.dispose.call(this, camera);
  46423. };
  46424. return RefractionPostProcess;
  46425. }(BABYLON.PostProcess));
  46426. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46427. })(BABYLON || (BABYLON = {}));
  46428. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  46429. var BABYLON;
  46430. (function (BABYLON) {
  46431. var BlackAndWhitePostProcess = (function (_super) {
  46432. __extends(BlackAndWhitePostProcess, _super);
  46433. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46434. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  46435. }
  46436. return BlackAndWhitePostProcess;
  46437. }(BABYLON.PostProcess));
  46438. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46439. })(BABYLON || (BABYLON = {}));
  46440. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  46441. var BABYLON;
  46442. (function (BABYLON) {
  46443. var ConvolutionPostProcess = (function (_super) {
  46444. __extends(ConvolutionPostProcess, _super);
  46445. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46446. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46447. _this.kernel = kernel;
  46448. _this.onApply = function (effect) {
  46449. effect.setFloat2("screenSize", _this.width, _this.height);
  46450. effect.setArray("kernel", _this.kernel);
  46451. };
  46452. return _this;
  46453. }
  46454. return ConvolutionPostProcess;
  46455. }(BABYLON.PostProcess));
  46456. // Statics
  46457. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46458. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46459. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46460. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46461. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46462. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46463. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46464. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46465. })(BABYLON || (BABYLON = {}));
  46466. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  46467. var BABYLON;
  46468. (function (BABYLON) {
  46469. var FilterPostProcess = (function (_super) {
  46470. __extends(FilterPostProcess, _super);
  46471. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46472. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  46473. _this.kernelMatrix = kernelMatrix;
  46474. _this.onApply = function (effect) {
  46475. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46476. };
  46477. return _this;
  46478. }
  46479. return FilterPostProcess;
  46480. }(BABYLON.PostProcess));
  46481. BABYLON.FilterPostProcess = FilterPostProcess;
  46482. })(BABYLON || (BABYLON = {}));
  46483. //# sourceMappingURL=babylon.filterPostProcess.js.map
  46484. var BABYLON;
  46485. (function (BABYLON) {
  46486. var FxaaPostProcess = (function (_super) {
  46487. __extends(FxaaPostProcess, _super);
  46488. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46489. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46490. _this.onSizeChangedObservable.add(function () {
  46491. _this.texelWidth = 1.0 / _this.width;
  46492. _this.texelHeight = 1.0 / _this.height;
  46493. });
  46494. _this.onApplyObservable.add(function (effect) {
  46495. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46496. });
  46497. return _this;
  46498. }
  46499. return FxaaPostProcess;
  46500. }(BABYLON.PostProcess));
  46501. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46502. })(BABYLON || (BABYLON = {}));
  46503. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  46504. var BABYLON;
  46505. (function (BABYLON) {
  46506. var StereoscopicInterlacePostProcess = (function (_super) {
  46507. __extends(StereoscopicInterlacePostProcess, _super);
  46508. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46509. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  46510. _this._passedProcess = rigCameras[0]._rigPostProcess;
  46511. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46512. _this.onSizeChangedObservable.add(function () {
  46513. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46514. });
  46515. _this.onApplyObservable.add(function (effect) {
  46516. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46517. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46518. });
  46519. return _this;
  46520. }
  46521. return StereoscopicInterlacePostProcess;
  46522. }(BABYLON.PostProcess));
  46523. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46524. })(BABYLON || (BABYLON = {}));
  46525. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46526. var BABYLON;
  46527. (function (BABYLON) {
  46528. var LensFlare = (function () {
  46529. function LensFlare(size, position, color, imgUrl, system) {
  46530. this.size = size;
  46531. this.position = position;
  46532. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46533. this.dispose = function () {
  46534. if (this.texture) {
  46535. this.texture.dispose();
  46536. }
  46537. // Remove from scene
  46538. var index = this._system.lensFlares.indexOf(this);
  46539. this._system.lensFlares.splice(index, 1);
  46540. };
  46541. this.color = color || new BABYLON.Color3(1, 1, 1);
  46542. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46543. this._system = system;
  46544. system.lensFlares.push(this);
  46545. }
  46546. return LensFlare;
  46547. }());
  46548. BABYLON.LensFlare = LensFlare;
  46549. })(BABYLON || (BABYLON = {}));
  46550. //# sourceMappingURL=babylon.lensFlare.js.map
  46551. var BABYLON;
  46552. (function (BABYLON) {
  46553. var LensFlareSystem = (function () {
  46554. function LensFlareSystem(name, emitter, scene) {
  46555. this.name = name;
  46556. this.lensFlares = new Array();
  46557. this.borderLimit = 300;
  46558. this.viewportBorder = 0;
  46559. this.layerMask = 0x0FFFFFFF;
  46560. this._vertexBuffers = {};
  46561. this._isEnabled = true;
  46562. this._scene = scene;
  46563. this._emitter = emitter;
  46564. this.id = name;
  46565. scene.lensFlareSystems.push(this);
  46566. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46567. var engine = scene.getEngine();
  46568. // VBO
  46569. var vertices = [];
  46570. vertices.push(1, 1);
  46571. vertices.push(-1, 1);
  46572. vertices.push(-1, -1);
  46573. vertices.push(1, -1);
  46574. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46575. // Indices
  46576. var indices = [];
  46577. indices.push(0);
  46578. indices.push(1);
  46579. indices.push(2);
  46580. indices.push(0);
  46581. indices.push(2);
  46582. indices.push(3);
  46583. this._indexBuffer = engine.createIndexBuffer(indices);
  46584. // Effects
  46585. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46586. }
  46587. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46588. get: function () {
  46589. return this._isEnabled;
  46590. },
  46591. set: function (value) {
  46592. this._isEnabled = value;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. LensFlareSystem.prototype.getScene = function () {
  46598. return this._scene;
  46599. };
  46600. LensFlareSystem.prototype.getEmitter = function () {
  46601. return this._emitter;
  46602. };
  46603. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46604. this._emitter = newEmitter;
  46605. };
  46606. LensFlareSystem.prototype.getEmitterPosition = function () {
  46607. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46608. };
  46609. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46610. var position = this.getEmitterPosition();
  46611. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46612. this._positionX = position.x;
  46613. this._positionY = position.y;
  46614. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46615. if (this.viewportBorder > 0) {
  46616. globalViewport.x -= this.viewportBorder;
  46617. globalViewport.y -= this.viewportBorder;
  46618. globalViewport.width += this.viewportBorder * 2;
  46619. globalViewport.height += this.viewportBorder * 2;
  46620. position.x += this.viewportBorder;
  46621. position.y += this.viewportBorder;
  46622. this._positionX += this.viewportBorder;
  46623. this._positionY += this.viewportBorder;
  46624. }
  46625. if (position.z > 0) {
  46626. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46627. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46628. return true;
  46629. }
  46630. return true;
  46631. }
  46632. return false;
  46633. };
  46634. LensFlareSystem.prototype._isVisible = function () {
  46635. if (!this._isEnabled) {
  46636. return false;
  46637. }
  46638. var emitterPosition = this.getEmitterPosition();
  46639. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46640. var distance = direction.length();
  46641. direction.normalize();
  46642. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46643. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46644. return !pickInfo.hit || pickInfo.distance > distance;
  46645. };
  46646. LensFlareSystem.prototype.render = function () {
  46647. if (!this._effect.isReady())
  46648. return false;
  46649. var engine = this._scene.getEngine();
  46650. var viewport = this._scene.activeCamera.viewport;
  46651. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46652. // Position
  46653. if (!this.computeEffectivePosition(globalViewport)) {
  46654. return false;
  46655. }
  46656. // Visibility
  46657. if (!this._isVisible()) {
  46658. return false;
  46659. }
  46660. // Intensity
  46661. var awayX;
  46662. var awayY;
  46663. if (this._positionX < this.borderLimit + globalViewport.x) {
  46664. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46665. }
  46666. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46667. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46668. }
  46669. else {
  46670. awayX = 0;
  46671. }
  46672. if (this._positionY < this.borderLimit + globalViewport.y) {
  46673. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46674. }
  46675. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46676. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46677. }
  46678. else {
  46679. awayY = 0;
  46680. }
  46681. var away = (awayX > awayY) ? awayX : awayY;
  46682. away -= this.viewportBorder;
  46683. if (away > this.borderLimit) {
  46684. away = this.borderLimit;
  46685. }
  46686. var intensity = 1.0 - (away / this.borderLimit);
  46687. if (intensity < 0) {
  46688. return false;
  46689. }
  46690. if (intensity > 1.0) {
  46691. intensity = 1.0;
  46692. }
  46693. if (this.viewportBorder > 0) {
  46694. globalViewport.x += this.viewportBorder;
  46695. globalViewport.y += this.viewportBorder;
  46696. globalViewport.width -= this.viewportBorder * 2;
  46697. globalViewport.height -= this.viewportBorder * 2;
  46698. this._positionX -= this.viewportBorder;
  46699. this._positionY -= this.viewportBorder;
  46700. }
  46701. // Position
  46702. var centerX = globalViewport.x + globalViewport.width / 2;
  46703. var centerY = globalViewport.y + globalViewport.height / 2;
  46704. var distX = centerX - this._positionX;
  46705. var distY = centerY - this._positionY;
  46706. // Effects
  46707. engine.enableEffect(this._effect);
  46708. engine.setState(false);
  46709. engine.setDepthBuffer(false);
  46710. // VBOs
  46711. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46712. // Flares
  46713. for (var index = 0; index < this.lensFlares.length; index++) {
  46714. var flare = this.lensFlares[index];
  46715. engine.setAlphaMode(flare.alphaMode);
  46716. var x = centerX - (distX * flare.position);
  46717. var y = centerY - (distY * flare.position);
  46718. var cw = flare.size;
  46719. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46720. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46721. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46722. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46723. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46724. // Texture
  46725. this._effect.setTexture("textureSampler", flare.texture);
  46726. // Color
  46727. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46728. // Draw order
  46729. engine.draw(true, 0, 6);
  46730. }
  46731. engine.setDepthBuffer(true);
  46732. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46733. return true;
  46734. };
  46735. LensFlareSystem.prototype.dispose = function () {
  46736. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46737. if (vertexBuffer) {
  46738. vertexBuffer.dispose();
  46739. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46740. }
  46741. if (this._indexBuffer) {
  46742. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46743. this._indexBuffer = null;
  46744. }
  46745. while (this.lensFlares.length) {
  46746. this.lensFlares[0].dispose();
  46747. }
  46748. // Remove from scene
  46749. var index = this._scene.lensFlareSystems.indexOf(this);
  46750. this._scene.lensFlareSystems.splice(index, 1);
  46751. };
  46752. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46753. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46754. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46755. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46756. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46757. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46758. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46759. var parsedFlare = parsedLensFlareSystem.flares[index];
  46760. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46761. }
  46762. return lensFlareSystem;
  46763. };
  46764. LensFlareSystem.prototype.serialize = function () {
  46765. var serializationObject = {};
  46766. serializationObject.id = this.id;
  46767. serializationObject.name = this.name;
  46768. serializationObject.emitterId = this.getEmitter().id;
  46769. serializationObject.borderLimit = this.borderLimit;
  46770. serializationObject.flares = [];
  46771. for (var index = 0; index < this.lensFlares.length; index++) {
  46772. var flare = this.lensFlares[index];
  46773. serializationObject.flares.push({
  46774. size: flare.size,
  46775. position: flare.position,
  46776. color: flare.color.asArray(),
  46777. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46778. });
  46779. }
  46780. return serializationObject;
  46781. };
  46782. return LensFlareSystem;
  46783. }());
  46784. BABYLON.LensFlareSystem = LensFlareSystem;
  46785. })(BABYLON || (BABYLON = {}));
  46786. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46787. var BABYLON;
  46788. (function (BABYLON) {
  46789. // We're mainly based on the logic defined into the FreeCamera code
  46790. var DeviceOrientationCamera = (function (_super) {
  46791. __extends(DeviceOrientationCamera, _super);
  46792. function DeviceOrientationCamera(name, position, scene) {
  46793. var _this = _super.call(this, name, position, scene) || this;
  46794. _this._quaternionCache = new BABYLON.Quaternion();
  46795. _this.inputs.addDeviceOrientation();
  46796. return _this;
  46797. }
  46798. DeviceOrientationCamera.prototype.getClassName = function () {
  46799. return "DeviceOrientationCamera";
  46800. };
  46801. DeviceOrientationCamera.prototype._checkInputs = function () {
  46802. _super.prototype._checkInputs.call(this);
  46803. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46804. if (this._initialQuaternion) {
  46805. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46806. }
  46807. };
  46808. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46809. var _this = this;
  46810. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46811. //can only work if this camera has a rotation quaternion already.
  46812. if (!this.rotationQuaternion)
  46813. return;
  46814. if (!this._initialQuaternion) {
  46815. this._initialQuaternion = new BABYLON.Quaternion();
  46816. }
  46817. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46818. ['x', 'y', 'z'].forEach(function (axisName) {
  46819. if (!axis[axisName]) {
  46820. _this._initialQuaternion[axisName] = 0;
  46821. }
  46822. else {
  46823. _this._initialQuaternion[axisName] *= -1;
  46824. }
  46825. });
  46826. this._initialQuaternion.normalize();
  46827. //force rotation update
  46828. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46829. };
  46830. return DeviceOrientationCamera;
  46831. }(BABYLON.FreeCamera));
  46832. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46833. })(BABYLON || (BABYLON = {}));
  46834. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46835. var BABYLON;
  46836. (function (BABYLON) {
  46837. var VRDeviceOrientationFreeCamera = (function (_super) {
  46838. __extends(VRDeviceOrientationFreeCamera, _super);
  46839. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46840. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46841. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46842. var _this = _super.call(this, name, position, scene) || this;
  46843. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46844. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46845. return _this;
  46846. }
  46847. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46848. return "VRDeviceOrientationFreeCamera";
  46849. };
  46850. return VRDeviceOrientationFreeCamera;
  46851. }(BABYLON.DeviceOrientationCamera));
  46852. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46853. var VRDeviceOrientationGamepadCamera = (function (_super) {
  46854. __extends(VRDeviceOrientationGamepadCamera, _super);
  46855. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46856. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46857. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46858. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  46859. _this.inputs.addGamepad();
  46860. return _this;
  46861. }
  46862. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  46863. return "VRDeviceOrientationGamepadCamera";
  46864. };
  46865. return VRDeviceOrientationGamepadCamera;
  46866. }(VRDeviceOrientationFreeCamera));
  46867. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  46868. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46869. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46870. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46871. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46872. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46873. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46874. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46875. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46876. _this.inputs.addVRDeviceOrientation();
  46877. return _this;
  46878. }
  46879. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46880. return "VRDeviceOrientationArcRotateCamera";
  46881. };
  46882. return VRDeviceOrientationArcRotateCamera;
  46883. }(BABYLON.ArcRotateCamera));
  46884. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46885. })(BABYLON || (BABYLON = {}));
  46886. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46887. var BABYLON;
  46888. (function (BABYLON) {
  46889. // We're mainly based on the logic defined into the FreeCamera code
  46890. var UniversalCamera = (function (_super) {
  46891. __extends(UniversalCamera, _super);
  46892. //-- end properties for backward compatibility for inputs
  46893. function UniversalCamera(name, position, scene) {
  46894. var _this = _super.call(this, name, position, scene) || this;
  46895. _this.inputs.addGamepad();
  46896. return _this;
  46897. }
  46898. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46899. //-- Begin properties for backward compatibility for inputs
  46900. get: function () {
  46901. var gamepad = this.inputs.attached["gamepad"];
  46902. if (gamepad)
  46903. return gamepad.gamepadAngularSensibility;
  46904. },
  46905. set: function (value) {
  46906. var gamepad = this.inputs.attached["gamepad"];
  46907. if (gamepad)
  46908. gamepad.gamepadAngularSensibility = value;
  46909. },
  46910. enumerable: true,
  46911. configurable: true
  46912. });
  46913. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46914. get: function () {
  46915. var gamepad = this.inputs.attached["gamepad"];
  46916. if (gamepad)
  46917. return gamepad.gamepadMoveSensibility;
  46918. },
  46919. set: function (value) {
  46920. var gamepad = this.inputs.attached["gamepad"];
  46921. if (gamepad)
  46922. gamepad.gamepadMoveSensibility = value;
  46923. },
  46924. enumerable: true,
  46925. configurable: true
  46926. });
  46927. UniversalCamera.prototype.getClassName = function () {
  46928. return "UniversalCamera";
  46929. };
  46930. return UniversalCamera;
  46931. }(BABYLON.TouchCamera));
  46932. BABYLON.UniversalCamera = UniversalCamera;
  46933. })(BABYLON || (BABYLON = {}));
  46934. //# sourceMappingURL=babylon.universalCamera.js.map
  46935. var BABYLON;
  46936. (function (BABYLON) {
  46937. var Gamepads = (function () {
  46938. function Gamepads(ongamedpadconnected) {
  46939. var _this = this;
  46940. this.babylonGamepads = [];
  46941. this.oneGamepadConnected = false;
  46942. this.isMonitoring = false;
  46943. this.gamepadEventSupported = 'GamepadEvent' in window;
  46944. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46945. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46946. this._callbackGamepadConnected = ongamedpadconnected;
  46947. if (this.gamepadSupportAvailable) {
  46948. // Checking if the gamepad connected event is supported (like in Firefox)
  46949. if (this.gamepadEventSupported) {
  46950. this._onGamepadConnectedEvent = function (evt) {
  46951. _this._onGamepadConnected(evt);
  46952. };
  46953. this._onGamepadDisonnectedEvent = function (evt) {
  46954. _this._onGamepadDisconnected(evt);
  46955. };
  46956. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46957. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46958. }
  46959. else {
  46960. this._startMonitoringGamepads();
  46961. }
  46962. }
  46963. }
  46964. Gamepads.prototype.dispose = function () {
  46965. if (Gamepads.gamepadDOMInfo) {
  46966. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46967. }
  46968. if (this._onGamepadConnectedEvent) {
  46969. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46970. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46971. this._onGamepadConnectedEvent = null;
  46972. this._onGamepadDisonnectedEvent = null;
  46973. }
  46974. };
  46975. Gamepads.prototype._onGamepadConnected = function (evt) {
  46976. var newGamepad = this._addNewGamepad(evt.gamepad);
  46977. if (this._callbackGamepadConnected)
  46978. this._callbackGamepadConnected(newGamepad);
  46979. this._startMonitoringGamepads();
  46980. };
  46981. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46982. if (!this.oneGamepadConnected) {
  46983. this.oneGamepadConnected = true;
  46984. if (Gamepads.gamepadDOMInfo) {
  46985. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46986. Gamepads.gamepadDOMInfo = null;
  46987. }
  46988. }
  46989. var newGamepad;
  46990. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46991. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46992. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46993. }
  46994. else {
  46995. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46996. }
  46997. this.babylonGamepads.push(newGamepad);
  46998. return newGamepad;
  46999. };
  47000. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  47001. // Remove the gamepad from the list of gamepads to monitor.
  47002. for (var i in this.babylonGamepads) {
  47003. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  47004. this.babylonGamepads.splice(+i, 1);
  47005. break;
  47006. }
  47007. }
  47008. // If no gamepads are left, stop the polling loop.
  47009. if (this.babylonGamepads.length == 0) {
  47010. this._stopMonitoringGamepads();
  47011. }
  47012. };
  47013. Gamepads.prototype._startMonitoringGamepads = function () {
  47014. if (!this.isMonitoring) {
  47015. this.isMonitoring = true;
  47016. this._checkGamepadsStatus();
  47017. }
  47018. };
  47019. Gamepads.prototype._stopMonitoringGamepads = function () {
  47020. this.isMonitoring = false;
  47021. };
  47022. Gamepads.prototype._checkGamepadsStatus = function () {
  47023. var _this = this;
  47024. // updating gamepad objects
  47025. this._updateGamepadObjects();
  47026. for (var i in this.babylonGamepads) {
  47027. this.babylonGamepads[i].update();
  47028. }
  47029. if (this.isMonitoring) {
  47030. if (window.requestAnimationFrame) {
  47031. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47032. }
  47033. else if (window.mozRequestAnimationFrame) {
  47034. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47035. }
  47036. else if (window.webkitRequestAnimationFrame) {
  47037. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47038. }
  47039. }
  47040. };
  47041. // This function is called only on Chrome, which does not yet support
  47042. // connection/disconnection events, but requires you to monitor
  47043. // an array for changes.
  47044. Gamepads.prototype._updateGamepadObjects = function () {
  47045. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47046. for (var i = 0; i < gamepads.length; i++) {
  47047. if (gamepads[i]) {
  47048. if (!(gamepads[i].index in this.babylonGamepads)) {
  47049. var newGamepad = this._addNewGamepad(gamepads[i]);
  47050. if (this._callbackGamepadConnected) {
  47051. this._callbackGamepadConnected(newGamepad);
  47052. }
  47053. }
  47054. else {
  47055. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47056. }
  47057. }
  47058. }
  47059. };
  47060. return Gamepads;
  47061. }());
  47062. BABYLON.Gamepads = Gamepads;
  47063. var StickValues = (function () {
  47064. function StickValues(x, y) {
  47065. this.x = x;
  47066. this.y = y;
  47067. }
  47068. return StickValues;
  47069. }());
  47070. BABYLON.StickValues = StickValues;
  47071. var Gamepad = (function () {
  47072. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47073. if (leftStickX === void 0) { leftStickX = 0; }
  47074. if (leftStickY === void 0) { leftStickY = 1; }
  47075. if (rightStickX === void 0) { rightStickX = 2; }
  47076. if (rightStickY === void 0) { rightStickY = 3; }
  47077. this.id = id;
  47078. this.index = index;
  47079. this.browserGamepad = browserGamepad;
  47080. this._leftStickAxisX = leftStickX;
  47081. this._leftStickAxisY = leftStickY;
  47082. this._rightStickAxisX = rightStickX;
  47083. this._rightStickAxisY = rightStickY;
  47084. if (this.browserGamepad.axes.length >= 2) {
  47085. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47086. }
  47087. if (this.browserGamepad.axes.length >= 4) {
  47088. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47089. }
  47090. }
  47091. Gamepad.prototype.onleftstickchanged = function (callback) {
  47092. this._onleftstickchanged = callback;
  47093. };
  47094. Gamepad.prototype.onrightstickchanged = function (callback) {
  47095. this._onrightstickchanged = callback;
  47096. };
  47097. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47098. get: function () {
  47099. return this._leftStick;
  47100. },
  47101. set: function (newValues) {
  47102. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47103. this._onleftstickchanged(newValues);
  47104. }
  47105. this._leftStick = newValues;
  47106. },
  47107. enumerable: true,
  47108. configurable: true
  47109. });
  47110. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47111. get: function () {
  47112. return this._rightStick;
  47113. },
  47114. set: function (newValues) {
  47115. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47116. this._onrightstickchanged(newValues);
  47117. }
  47118. this._rightStick = newValues;
  47119. },
  47120. enumerable: true,
  47121. configurable: true
  47122. });
  47123. Gamepad.prototype.update = function () {
  47124. if (this._leftStick) {
  47125. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47126. }
  47127. if (this._rightStick) {
  47128. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47129. }
  47130. };
  47131. return Gamepad;
  47132. }());
  47133. BABYLON.Gamepad = Gamepad;
  47134. var GenericPad = (function (_super) {
  47135. __extends(GenericPad, _super);
  47136. function GenericPad(id, index, gamepad) {
  47137. var _this = _super.call(this, id, index, gamepad) || this;
  47138. _this.id = id;
  47139. _this.index = index;
  47140. _this.gamepad = gamepad;
  47141. _this._buttons = new Array(gamepad.buttons.length);
  47142. return _this;
  47143. }
  47144. GenericPad.prototype.onbuttondown = function (callback) {
  47145. this._onbuttondown = callback;
  47146. };
  47147. GenericPad.prototype.onbuttonup = function (callback) {
  47148. this._onbuttonup = callback;
  47149. };
  47150. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47151. if (newValue !== currentValue) {
  47152. if (this._onbuttondown && newValue === 1) {
  47153. this._onbuttondown(buttonIndex);
  47154. }
  47155. if (this._onbuttonup && newValue === 0) {
  47156. this._onbuttonup(buttonIndex);
  47157. }
  47158. }
  47159. return newValue;
  47160. };
  47161. GenericPad.prototype.update = function () {
  47162. _super.prototype.update.call(this);
  47163. for (var index = 0; index < this._buttons.length; index++) {
  47164. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47165. }
  47166. };
  47167. return GenericPad;
  47168. }(Gamepad));
  47169. BABYLON.GenericPad = GenericPad;
  47170. var Xbox360Button;
  47171. (function (Xbox360Button) {
  47172. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47173. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47174. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47175. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47176. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47177. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47178. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47179. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47180. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47181. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47182. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47183. var Xbox360Dpad;
  47184. (function (Xbox360Dpad) {
  47185. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47186. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47187. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47188. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47189. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47190. var Xbox360Pad = (function (_super) {
  47191. __extends(Xbox360Pad, _super);
  47192. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47193. if (xboxOne === void 0) { xboxOne = false; }
  47194. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47195. _this._leftTrigger = 0;
  47196. _this._rightTrigger = 0;
  47197. _this._buttonA = 0;
  47198. _this._buttonB = 0;
  47199. _this._buttonX = 0;
  47200. _this._buttonY = 0;
  47201. _this._buttonBack = 0;
  47202. _this._buttonStart = 0;
  47203. _this._buttonLB = 0;
  47204. _this._buttonRB = 0;
  47205. _this._buttonLeftStick = 0;
  47206. _this._buttonRightStick = 0;
  47207. _this._dPadUp = 0;
  47208. _this._dPadDown = 0;
  47209. _this._dPadLeft = 0;
  47210. _this._dPadRight = 0;
  47211. _this._isXboxOnePad = false;
  47212. _this._isXboxOnePad = xboxOne;
  47213. return _this;
  47214. }
  47215. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47216. this._onlefttriggerchanged = callback;
  47217. };
  47218. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47219. this._onrighttriggerchanged = callback;
  47220. };
  47221. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47222. get: function () {
  47223. return this._leftTrigger;
  47224. },
  47225. set: function (newValue) {
  47226. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47227. this._onlefttriggerchanged(newValue);
  47228. }
  47229. this._leftTrigger = newValue;
  47230. },
  47231. enumerable: true,
  47232. configurable: true
  47233. });
  47234. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47235. get: function () {
  47236. return this._rightTrigger;
  47237. },
  47238. set: function (newValue) {
  47239. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47240. this._onrighttriggerchanged(newValue);
  47241. }
  47242. this._rightTrigger = newValue;
  47243. },
  47244. enumerable: true,
  47245. configurable: true
  47246. });
  47247. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47248. this._onbuttondown = callback;
  47249. };
  47250. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47251. this._onbuttonup = callback;
  47252. };
  47253. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47254. this._ondpaddown = callback;
  47255. };
  47256. Xbox360Pad.prototype.ondpadup = function (callback) {
  47257. this._ondpadup = callback;
  47258. };
  47259. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47260. if (newValue !== currentValue) {
  47261. if (this._onbuttondown && newValue === 1) {
  47262. this._onbuttondown(buttonType);
  47263. }
  47264. if (this._onbuttonup && newValue === 0) {
  47265. this._onbuttonup(buttonType);
  47266. }
  47267. }
  47268. return newValue;
  47269. };
  47270. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47271. if (newValue !== currentValue) {
  47272. if (this._ondpaddown && newValue === 1) {
  47273. this._ondpaddown(buttonType);
  47274. }
  47275. if (this._ondpadup && newValue === 0) {
  47276. this._ondpadup(buttonType);
  47277. }
  47278. }
  47279. return newValue;
  47280. };
  47281. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47282. get: function () {
  47283. return this._buttonA;
  47284. },
  47285. set: function (value) {
  47286. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47287. },
  47288. enumerable: true,
  47289. configurable: true
  47290. });
  47291. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47292. get: function () {
  47293. return this._buttonB;
  47294. },
  47295. set: function (value) {
  47296. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47297. },
  47298. enumerable: true,
  47299. configurable: true
  47300. });
  47301. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47302. get: function () {
  47303. return this._buttonX;
  47304. },
  47305. set: function (value) {
  47306. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47307. },
  47308. enumerable: true,
  47309. configurable: true
  47310. });
  47311. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47312. get: function () {
  47313. return this._buttonY;
  47314. },
  47315. set: function (value) {
  47316. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47317. },
  47318. enumerable: true,
  47319. configurable: true
  47320. });
  47321. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47322. get: function () {
  47323. return this._buttonStart;
  47324. },
  47325. set: function (value) {
  47326. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47327. },
  47328. enumerable: true,
  47329. configurable: true
  47330. });
  47331. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47332. get: function () {
  47333. return this._buttonBack;
  47334. },
  47335. set: function (value) {
  47336. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47337. },
  47338. enumerable: true,
  47339. configurable: true
  47340. });
  47341. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47342. get: function () {
  47343. return this._buttonLB;
  47344. },
  47345. set: function (value) {
  47346. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47347. },
  47348. enumerable: true,
  47349. configurable: true
  47350. });
  47351. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47352. get: function () {
  47353. return this._buttonRB;
  47354. },
  47355. set: function (value) {
  47356. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47357. },
  47358. enumerable: true,
  47359. configurable: true
  47360. });
  47361. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47362. get: function () {
  47363. return this._buttonLeftStick;
  47364. },
  47365. set: function (value) {
  47366. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47367. },
  47368. enumerable: true,
  47369. configurable: true
  47370. });
  47371. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47372. get: function () {
  47373. return this._buttonRightStick;
  47374. },
  47375. set: function (value) {
  47376. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47377. },
  47378. enumerable: true,
  47379. configurable: true
  47380. });
  47381. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47382. get: function () {
  47383. return this._dPadUp;
  47384. },
  47385. set: function (value) {
  47386. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47387. },
  47388. enumerable: true,
  47389. configurable: true
  47390. });
  47391. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47392. get: function () {
  47393. return this._dPadDown;
  47394. },
  47395. set: function (value) {
  47396. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47397. },
  47398. enumerable: true,
  47399. configurable: true
  47400. });
  47401. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47402. get: function () {
  47403. return this._dPadLeft;
  47404. },
  47405. set: function (value) {
  47406. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47407. },
  47408. enumerable: true,
  47409. configurable: true
  47410. });
  47411. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47412. get: function () {
  47413. return this._dPadRight;
  47414. },
  47415. set: function (value) {
  47416. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47417. },
  47418. enumerable: true,
  47419. configurable: true
  47420. });
  47421. Xbox360Pad.prototype.update = function () {
  47422. _super.prototype.update.call(this);
  47423. if (this._isXboxOnePad) {
  47424. this.buttonA = this.browserGamepad.buttons[0].value;
  47425. this.buttonB = this.browserGamepad.buttons[1].value;
  47426. this.buttonX = this.browserGamepad.buttons[2].value;
  47427. this.buttonY = this.browserGamepad.buttons[3].value;
  47428. this.buttonLB = this.browserGamepad.buttons[4].value;
  47429. this.buttonRB = this.browserGamepad.buttons[5].value;
  47430. this.leftTrigger = this.browserGamepad.axes[2];
  47431. this.rightTrigger = this.browserGamepad.axes[5];
  47432. this.buttonBack = this.browserGamepad.buttons[9].value;
  47433. this.buttonStart = this.browserGamepad.buttons[8].value;
  47434. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47435. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47436. this.dPadUp = this.browserGamepad.buttons[11].value;
  47437. this.dPadDown = this.browserGamepad.buttons[12].value;
  47438. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47439. this.dPadRight = this.browserGamepad.buttons[14].value;
  47440. }
  47441. else {
  47442. this.buttonA = this.browserGamepad.buttons[0].value;
  47443. this.buttonB = this.browserGamepad.buttons[1].value;
  47444. this.buttonX = this.browserGamepad.buttons[2].value;
  47445. this.buttonY = this.browserGamepad.buttons[3].value;
  47446. this.buttonLB = this.browserGamepad.buttons[4].value;
  47447. this.buttonRB = this.browserGamepad.buttons[5].value;
  47448. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47449. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47450. this.buttonBack = this.browserGamepad.buttons[8].value;
  47451. this.buttonStart = this.browserGamepad.buttons[9].value;
  47452. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47453. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47454. this.dPadUp = this.browserGamepad.buttons[12].value;
  47455. this.dPadDown = this.browserGamepad.buttons[13].value;
  47456. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47457. this.dPadRight = this.browserGamepad.buttons[15].value;
  47458. }
  47459. };
  47460. return Xbox360Pad;
  47461. }(Gamepad));
  47462. BABYLON.Xbox360Pad = Xbox360Pad;
  47463. })(BABYLON || (BABYLON = {}));
  47464. //# sourceMappingURL=babylon.gamepads.js.map
  47465. var BABYLON;
  47466. (function (BABYLON) {
  47467. // We're mainly based on the logic defined into the FreeCamera code
  47468. var GamepadCamera = (function (_super) {
  47469. __extends(GamepadCamera, _super);
  47470. //-- end properties for backward compatibility for inputs
  47471. function GamepadCamera(name, position, scene) {
  47472. var _this;
  47473. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47474. _this = _super.call(this, name, position, scene) || this;
  47475. return _this;
  47476. }
  47477. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47478. //-- Begin properties for backward compatibility for inputs
  47479. get: function () {
  47480. var gamepad = this.inputs.attached["gamepad"];
  47481. if (gamepad)
  47482. return gamepad.gamepadAngularSensibility;
  47483. },
  47484. set: function (value) {
  47485. var gamepad = this.inputs.attached["gamepad"];
  47486. if (gamepad)
  47487. gamepad.gamepadAngularSensibility = value;
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47493. get: function () {
  47494. var gamepad = this.inputs.attached["gamepad"];
  47495. if (gamepad)
  47496. return gamepad.gamepadMoveSensibility;
  47497. },
  47498. set: function (value) {
  47499. var gamepad = this.inputs.attached["gamepad"];
  47500. if (gamepad)
  47501. gamepad.gamepadMoveSensibility = value;
  47502. },
  47503. enumerable: true,
  47504. configurable: true
  47505. });
  47506. GamepadCamera.prototype.getClassName = function () {
  47507. return "GamepadCamera";
  47508. };
  47509. return GamepadCamera;
  47510. }(BABYLON.UniversalCamera));
  47511. BABYLON.GamepadCamera = GamepadCamera;
  47512. })(BABYLON || (BABYLON = {}));
  47513. //# sourceMappingURL=babylon.gamepadCamera.js.map
  47514. var BABYLON;
  47515. (function (BABYLON) {
  47516. var Analyser = (function () {
  47517. function Analyser(scene) {
  47518. this.SMOOTHING = 0.75;
  47519. this.FFT_SIZE = 512;
  47520. this.BARGRAPHAMPLITUDE = 256;
  47521. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47522. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47523. this._scene = scene;
  47524. this._audioEngine = BABYLON.Engine.audioEngine;
  47525. if (this._audioEngine.canUseWebAudio) {
  47526. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47527. this._webAudioAnalyser.minDecibels = -140;
  47528. this._webAudioAnalyser.maxDecibels = 0;
  47529. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47530. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47531. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47532. }
  47533. }
  47534. Analyser.prototype.getFrequencyBinCount = function () {
  47535. if (this._audioEngine.canUseWebAudio) {
  47536. return this._webAudioAnalyser.frequencyBinCount;
  47537. }
  47538. else {
  47539. return 0;
  47540. }
  47541. };
  47542. Analyser.prototype.getByteFrequencyData = function () {
  47543. if (this._audioEngine.canUseWebAudio) {
  47544. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47545. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47546. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47547. }
  47548. return this._byteFreqs;
  47549. };
  47550. Analyser.prototype.getByteTimeDomainData = function () {
  47551. if (this._audioEngine.canUseWebAudio) {
  47552. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47553. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47554. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47555. }
  47556. return this._byteTime;
  47557. };
  47558. Analyser.prototype.getFloatFrequencyData = function () {
  47559. if (this._audioEngine.canUseWebAudio) {
  47560. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47561. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47562. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47563. }
  47564. return this._floatFreqs;
  47565. };
  47566. Analyser.prototype.drawDebugCanvas = function () {
  47567. var _this = this;
  47568. if (this._audioEngine.canUseWebAudio) {
  47569. if (!this._debugCanvas) {
  47570. this._debugCanvas = document.createElement("canvas");
  47571. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47572. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47573. this._debugCanvas.style.position = "absolute";
  47574. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47575. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47576. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47577. document.body.appendChild(this._debugCanvas);
  47578. this._registerFunc = function () {
  47579. _this.drawDebugCanvas();
  47580. };
  47581. this._scene.registerBeforeRender(this._registerFunc);
  47582. }
  47583. if (this._registerFunc) {
  47584. var workingArray = this.getByteFrequencyData();
  47585. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47586. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47587. // Draw the frequency domain chart.
  47588. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47589. var value = workingArray[i];
  47590. var percent = value / this.BARGRAPHAMPLITUDE;
  47591. var height = this.DEBUGCANVASSIZE.height * percent;
  47592. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47593. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47594. var hue = i / this.getFrequencyBinCount() * 360;
  47595. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47596. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47597. }
  47598. }
  47599. }
  47600. };
  47601. Analyser.prototype.stopDebugCanvas = function () {
  47602. if (this._debugCanvas) {
  47603. this._scene.unregisterBeforeRender(this._registerFunc);
  47604. this._registerFunc = null;
  47605. document.body.removeChild(this._debugCanvas);
  47606. this._debugCanvas = null;
  47607. this._debugCanvasContext = null;
  47608. }
  47609. };
  47610. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47611. if (this._audioEngine.canUseWebAudio) {
  47612. inputAudioNode.connect(this._webAudioAnalyser);
  47613. this._webAudioAnalyser.connect(outputAudioNode);
  47614. }
  47615. };
  47616. Analyser.prototype.dispose = function () {
  47617. if (this._audioEngine.canUseWebAudio) {
  47618. this._webAudioAnalyser.disconnect();
  47619. }
  47620. };
  47621. return Analyser;
  47622. }());
  47623. BABYLON.Analyser = Analyser;
  47624. })(BABYLON || (BABYLON = {}));
  47625. //# sourceMappingURL=babylon.analyser.js.map
  47626. var BABYLON;
  47627. (function (BABYLON) {
  47628. var DepthRenderer = (function () {
  47629. function DepthRenderer(scene, type) {
  47630. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47631. var _this = this;
  47632. this._viewMatrix = BABYLON.Matrix.Zero();
  47633. this._projectionMatrix = BABYLON.Matrix.Zero();
  47634. this._transformMatrix = BABYLON.Matrix.Zero();
  47635. this._worldViewProjection = BABYLON.Matrix.Zero();
  47636. this._scene = scene;
  47637. var engine = scene.getEngine();
  47638. // Render target
  47639. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47640. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47641. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47642. this._depthMap.refreshRate = 1;
  47643. this._depthMap.renderParticles = false;
  47644. this._depthMap.renderList = null;
  47645. // set default depth value to 1.0 (far away)
  47646. this._depthMap.onClearObservable.add(function (engine) {
  47647. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47648. });
  47649. // Custom render function
  47650. var renderSubMesh = function (subMesh) {
  47651. var mesh = subMesh.getRenderingMesh();
  47652. var scene = _this._scene;
  47653. var engine = scene.getEngine();
  47654. // Culling
  47655. engine.setState(subMesh.getMaterial().backFaceCulling);
  47656. // Managing instances
  47657. var batch = mesh._getInstancesRenderList(subMesh._id);
  47658. if (batch.mustReturn) {
  47659. return;
  47660. }
  47661. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47662. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47663. engine.enableEffect(_this._effect);
  47664. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47665. var material = subMesh.getMaterial();
  47666. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47667. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47668. // Alpha test
  47669. if (material && material.needAlphaTesting()) {
  47670. var alphaTexture = material.getAlphaTestTexture();
  47671. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47672. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47673. }
  47674. // Bones
  47675. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47676. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47677. }
  47678. // Draw
  47679. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47680. }
  47681. };
  47682. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47683. var index;
  47684. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47685. renderSubMesh(opaqueSubMeshes.data[index]);
  47686. }
  47687. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47688. renderSubMesh(alphaTestSubMeshes.data[index]);
  47689. }
  47690. };
  47691. }
  47692. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47693. var material = subMesh.getMaterial();
  47694. if (material.disableDepthWrite) {
  47695. return false;
  47696. }
  47697. var defines = [];
  47698. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47699. var mesh = subMesh.getMesh();
  47700. var scene = mesh.getScene();
  47701. // Alpha test
  47702. if (material && material.needAlphaTesting()) {
  47703. defines.push("#define ALPHATEST");
  47704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47705. attribs.push(BABYLON.VertexBuffer.UVKind);
  47706. defines.push("#define UV1");
  47707. }
  47708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47710. defines.push("#define UV2");
  47711. }
  47712. }
  47713. // Bones
  47714. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47717. if (mesh.numBoneInfluencers > 4) {
  47718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47720. }
  47721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47722. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47723. }
  47724. else {
  47725. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47726. }
  47727. // Instances
  47728. if (useInstances) {
  47729. defines.push("#define INSTANCES");
  47730. attribs.push("world0");
  47731. attribs.push("world1");
  47732. attribs.push("world2");
  47733. attribs.push("world3");
  47734. }
  47735. // Get correct effect
  47736. var join = defines.join("\n");
  47737. if (this._cachedDefines !== join) {
  47738. this._cachedDefines = join;
  47739. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47740. }
  47741. return this._effect.isReady();
  47742. };
  47743. DepthRenderer.prototype.getDepthMap = function () {
  47744. return this._depthMap;
  47745. };
  47746. // Methods
  47747. DepthRenderer.prototype.dispose = function () {
  47748. this._depthMap.dispose();
  47749. };
  47750. return DepthRenderer;
  47751. }());
  47752. BABYLON.DepthRenderer = DepthRenderer;
  47753. })(BABYLON || (BABYLON = {}));
  47754. //# sourceMappingURL=babylon.depthRenderer.js.map
  47755. var BABYLON;
  47756. (function (BABYLON) {
  47757. var SSAORenderingPipeline = (function (_super) {
  47758. __extends(SSAORenderingPipeline, _super);
  47759. /**
  47760. * @constructor
  47761. * @param {string} name - The rendering pipeline name
  47762. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47763. * @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 }
  47764. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47765. */
  47766. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47767. var _this = _super.call(this, scene.getEngine(), name) || this;
  47768. // Members
  47769. /**
  47770. * The PassPostProcess id in the pipeline that contains the original scene color
  47771. * @type {string}
  47772. */
  47773. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47774. /**
  47775. * The SSAO PostProcess id in the pipeline
  47776. * @type {string}
  47777. */
  47778. _this.SSAORenderEffect = "SSAORenderEffect";
  47779. /**
  47780. * The horizontal blur PostProcess id in the pipeline
  47781. * @type {string}
  47782. */
  47783. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47784. /**
  47785. * The vertical blur PostProcess id in the pipeline
  47786. * @type {string}
  47787. */
  47788. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47789. /**
  47790. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47791. * @type {string}
  47792. */
  47793. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47794. /**
  47795. * The output strength of the SSAO post-process. Default value is 1.0.
  47796. * @type {number}
  47797. */
  47798. _this.totalStrength = 1.0;
  47799. /**
  47800. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47801. * @type {number}
  47802. */
  47803. _this.radius = 0.0001;
  47804. /**
  47805. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47806. * Must not be equal to fallOff and superior to fallOff.
  47807. * Default value is 0.975
  47808. * @type {number}
  47809. */
  47810. _this.area = 0.0075;
  47811. /**
  47812. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47813. * Must not be equal to area and inferior to area.
  47814. * Default value is 0.0
  47815. * @type {number}
  47816. */
  47817. _this.fallOff = 0.000001;
  47818. /**
  47819. * The base color of the SSAO post-process
  47820. * The final result is "base + ssao" between [0, 1]
  47821. * @type {number}
  47822. */
  47823. _this.base = 0.5;
  47824. _this._firstUpdate = true;
  47825. _this._scene = scene;
  47826. // Set up assets
  47827. _this._createRandomTexture();
  47828. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47829. var ssaoRatio = ratio.ssaoRatio || ratio;
  47830. var combineRatio = ratio.combineRatio || ratio;
  47831. _this._ratio = {
  47832. ssaoRatio: ssaoRatio,
  47833. combineRatio: combineRatio
  47834. };
  47835. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47836. _this._createSSAOPostProcess(ssaoRatio);
  47837. _this._createBlurPostProcess(ssaoRatio);
  47838. _this._createSSAOCombinePostProcess(combineRatio);
  47839. // Set up pipeline
  47840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47843. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47844. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47845. // Finish
  47846. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47847. if (cameras)
  47848. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47849. return _this;
  47850. }
  47851. // Public Methods
  47852. /**
  47853. * Returns the horizontal blur PostProcess
  47854. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47855. */
  47856. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47857. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47858. return null;
  47859. };
  47860. /**
  47861. * Returns the vertical blur PostProcess
  47862. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47863. */
  47864. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47865. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47866. return null;
  47867. };
  47868. /**
  47869. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47870. */
  47871. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47872. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47873. for (var i = 0; i < this._scene.cameras.length; i++) {
  47874. var camera = this._scene.cameras[i];
  47875. this._originalColorPostProcess.dispose(camera);
  47876. this._ssaoPostProcess.dispose(camera);
  47877. this._blurHPostProcess.dispose(camera);
  47878. this._blurVPostProcess.dispose(camera);
  47879. this._ssaoCombinePostProcess.dispose(camera);
  47880. }
  47881. this._randomTexture.dispose();
  47882. if (disableDepthRender)
  47883. this._scene.disableDepthRenderer();
  47884. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47885. _super.prototype.dispose.call(this);
  47886. };
  47887. // Private Methods
  47888. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47889. var _this = this;
  47890. /*
  47891. var samplerOffsets = [
  47892. -8.0, -6.0, -4.0, -2.0,
  47893. 0.0,
  47894. 2.0, 4.0, 6.0, 8.0
  47895. ];
  47896. */
  47897. var samples = 16;
  47898. var samplerOffsets = [];
  47899. for (var i = -8; i < 8; i++) {
  47900. samplerOffsets.push(i * 2);
  47901. }
  47902. 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");
  47903. this._blurHPostProcess.onApply = function (effect) {
  47904. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47905. effect.setTexture("depthSampler", _this._depthTexture);
  47906. if (_this._firstUpdate) {
  47907. effect.setArray("samplerOffsets", samplerOffsets);
  47908. }
  47909. };
  47910. 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");
  47911. this._blurVPostProcess.onApply = function (effect) {
  47912. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47913. effect.setTexture("depthSampler", _this._depthTexture);
  47914. if (_this._firstUpdate) {
  47915. effect.setArray("samplerOffsets", samplerOffsets);
  47916. _this._firstUpdate = false;
  47917. }
  47918. };
  47919. };
  47920. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47921. var _this = this;
  47922. var numSamples = 16;
  47923. var sampleSphere = [
  47924. 0.5381, 0.1856, -0.4319,
  47925. 0.1379, 0.2486, 0.4430,
  47926. 0.3371, 0.5679, -0.0057,
  47927. -0.6999, -0.0451, -0.0019,
  47928. 0.0689, -0.1598, -0.8547,
  47929. 0.0560, 0.0069, -0.1843,
  47930. -0.0146, 0.1402, 0.0762,
  47931. 0.0100, -0.1924, -0.0344,
  47932. -0.3577, -0.5301, -0.4358,
  47933. -0.3169, 0.1063, 0.0158,
  47934. 0.0103, -0.5869, 0.0046,
  47935. -0.0897, -0.4940, 0.3287,
  47936. 0.7119, -0.0154, -0.0918,
  47937. -0.0533, 0.0596, -0.5411,
  47938. 0.0352, -0.0631, 0.5460,
  47939. -0.4776, 0.2847, -0.0271
  47940. ];
  47941. var samplesFactor = 1.0 / numSamples;
  47942. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47943. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47944. "area", "fallOff", "base", "range", "viewport"
  47945. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47946. var viewport = new BABYLON.Vector2(0, 0);
  47947. this._ssaoPostProcess.onApply = function (effect) {
  47948. if (_this._firstUpdate) {
  47949. effect.setArray3("sampleSphere", sampleSphere);
  47950. effect.setFloat("samplesFactor", samplesFactor);
  47951. effect.setFloat("randTextureTiles", 4.0);
  47952. }
  47953. effect.setFloat("totalStrength", _this.totalStrength);
  47954. effect.setFloat("radius", _this.radius);
  47955. effect.setFloat("area", _this.area);
  47956. effect.setFloat("fallOff", _this.fallOff);
  47957. effect.setFloat("base", _this.base);
  47958. effect.setTexture("textureSampler", _this._depthTexture);
  47959. effect.setTexture("randomSampler", _this._randomTexture);
  47960. };
  47961. };
  47962. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47963. var _this = this;
  47964. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47965. this._ssaoCombinePostProcess.onApply = function (effect) {
  47966. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47967. };
  47968. };
  47969. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47970. var size = 512;
  47971. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47972. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47973. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47974. var context = this._randomTexture.getContext();
  47975. var rand = function (min, max) {
  47976. return Math.random() * (max - min) + min;
  47977. };
  47978. var randVector = BABYLON.Vector3.Zero();
  47979. for (var x = 0; x < size; x++) {
  47980. for (var y = 0; y < size; y++) {
  47981. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47982. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47983. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47984. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47985. context.fillRect(x, y, 1, 1);
  47986. }
  47987. }
  47988. this._randomTexture.update(false);
  47989. };
  47990. return SSAORenderingPipeline;
  47991. }(BABYLON.PostProcessRenderPipeline));
  47992. __decorate([
  47993. BABYLON.serialize()
  47994. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47995. __decorate([
  47996. BABYLON.serialize()
  47997. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47998. __decorate([
  47999. BABYLON.serialize()
  48000. ], SSAORenderingPipeline.prototype, "area", void 0);
  48001. __decorate([
  48002. BABYLON.serialize()
  48003. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  48004. __decorate([
  48005. BABYLON.serialize()
  48006. ], SSAORenderingPipeline.prototype, "base", void 0);
  48007. __decorate([
  48008. BABYLON.serialize()
  48009. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  48010. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  48011. })(BABYLON || (BABYLON = {}));
  48012. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  48013. var BABYLON;
  48014. (function (BABYLON) {
  48015. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48016. var VolumetricLightScatteringPostProcess = (function (_super) {
  48017. __extends(VolumetricLightScatteringPostProcess, _super);
  48018. /**
  48019. * @constructor
  48020. * @param {string} name - The post-process name
  48021. * @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)
  48022. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48023. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48024. * @param {number} samples - The post-process quality, default 100
  48025. * @param {number} samplingMode - The post-process filtering mode
  48026. * @param {BABYLON.Engine} engine - The babylon engine
  48027. * @param {boolean} reusable - If the post-process is reusable
  48028. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48029. */
  48030. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48031. if (samples === void 0) { samples = 100; }
  48032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48033. 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;
  48034. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48035. /**
  48036. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48037. * @type {Vector3}
  48038. */
  48039. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48040. /**
  48041. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48042. * @type {boolean}
  48043. */
  48044. _this.useCustomMeshPosition = false;
  48045. /**
  48046. * If the post-process should inverse the light scattering direction
  48047. * @type {boolean}
  48048. */
  48049. _this.invert = true;
  48050. /**
  48051. * Array containing the excluded meshes not rendered in the internal pass
  48052. */
  48053. _this.excludedMeshes = new Array();
  48054. /**
  48055. * Controls the overall intensity of the post-process
  48056. * @type {number}
  48057. */
  48058. _this.exposure = 0.3;
  48059. /**
  48060. * Dissipates each sample's contribution in range [0, 1]
  48061. * @type {number}
  48062. */
  48063. _this.decay = 0.96815;
  48064. /**
  48065. * Controls the overall intensity of each sample
  48066. * @type {number}
  48067. */
  48068. _this.weight = 0.58767;
  48069. /**
  48070. * Controls the density of each sample
  48071. * @type {number}
  48072. */
  48073. _this.density = 0.926;
  48074. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48075. var engine = scene.getEngine();
  48076. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48077. // Configure mesh
  48078. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48079. // Configure
  48080. _this._createPass(scene, ratio.passRatio || ratio);
  48081. _this.onActivate = function (camera) {
  48082. if (!_this.isSupported) {
  48083. _this.dispose(camera);
  48084. }
  48085. _this.onActivate = null;
  48086. };
  48087. _this.onApplyObservable.add(function (effect) {
  48088. _this._updateMeshScreenCoordinates(scene);
  48089. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48090. effect.setFloat("exposure", _this.exposure);
  48091. effect.setFloat("decay", _this.decay);
  48092. effect.setFloat("weight", _this.weight);
  48093. effect.setFloat("density", _this.density);
  48094. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48095. });
  48096. return _this;
  48097. }
  48098. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48099. get: function () {
  48100. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48101. return false;
  48102. },
  48103. set: function (useDiffuseColor) {
  48104. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48105. },
  48106. enumerable: true,
  48107. configurable: true
  48108. });
  48109. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48110. var mesh = subMesh.getMesh();
  48111. // Render this.mesh as default
  48112. if (mesh === this.mesh) {
  48113. return mesh.material.isReady(mesh);
  48114. }
  48115. var defines = [];
  48116. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48117. var material = subMesh.getMaterial();
  48118. var needUV = false;
  48119. // Alpha test
  48120. if (material) {
  48121. if (material.needAlphaTesting()) {
  48122. defines.push("#define ALPHATEST");
  48123. }
  48124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48125. attribs.push(BABYLON.VertexBuffer.UVKind);
  48126. defines.push("#define UV1");
  48127. }
  48128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48129. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48130. defines.push("#define UV2");
  48131. }
  48132. }
  48133. // Bones
  48134. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48135. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48136. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48137. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48138. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48139. }
  48140. else {
  48141. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48142. }
  48143. // Instances
  48144. if (useInstances) {
  48145. defines.push("#define INSTANCES");
  48146. attribs.push("world0");
  48147. attribs.push("world1");
  48148. attribs.push("world2");
  48149. attribs.push("world3");
  48150. }
  48151. // Get correct effect
  48152. var join = defines.join("\n");
  48153. if (this._cachedDefines !== join) {
  48154. this._cachedDefines = join;
  48155. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48156. }
  48157. return this._volumetricLightScatteringPass.isReady();
  48158. };
  48159. /**
  48160. * Sets the new light position for light scattering effect
  48161. * @param {BABYLON.Vector3} The new custom light position
  48162. */
  48163. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48164. this.customMeshPosition = position;
  48165. };
  48166. /**
  48167. * Returns the light position for light scattering effect
  48168. * @return {BABYLON.Vector3} The custom light position
  48169. */
  48170. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48171. return this.customMeshPosition;
  48172. };
  48173. /**
  48174. * Disposes the internal assets and detaches the post-process from the camera
  48175. */
  48176. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48177. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48178. if (rttIndex !== -1) {
  48179. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48180. }
  48181. this._volumetricLightScatteringRTT.dispose();
  48182. _super.prototype.dispose.call(this, camera);
  48183. };
  48184. /**
  48185. * Returns the render target texture used by the post-process
  48186. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48187. */
  48188. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48189. return this._volumetricLightScatteringRTT;
  48190. };
  48191. // Private methods
  48192. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48193. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48194. return true;
  48195. }
  48196. return false;
  48197. };
  48198. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48199. var _this = this;
  48200. var engine = scene.getEngine();
  48201. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48202. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48203. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48204. this._volumetricLightScatteringRTT.renderList = null;
  48205. this._volumetricLightScatteringRTT.renderParticles = false;
  48206. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48207. // Custom render function for submeshes
  48208. var renderSubMesh = function (subMesh) {
  48209. var mesh = subMesh.getRenderingMesh();
  48210. if (_this._meshExcluded(mesh)) {
  48211. return;
  48212. }
  48213. var scene = mesh.getScene();
  48214. var engine = scene.getEngine();
  48215. // Culling
  48216. engine.setState(subMesh.getMaterial().backFaceCulling);
  48217. // Managing instances
  48218. var batch = mesh._getInstancesRenderList(subMesh._id);
  48219. if (batch.mustReturn) {
  48220. return;
  48221. }
  48222. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48223. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48224. var effect = _this._volumetricLightScatteringPass;
  48225. if (mesh === _this.mesh) {
  48226. effect = subMesh.getMaterial().getEffect();
  48227. }
  48228. engine.enableEffect(effect);
  48229. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48230. if (mesh === _this.mesh) {
  48231. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48232. }
  48233. else {
  48234. var material = subMesh.getMaterial();
  48235. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48236. // Alpha test
  48237. if (material && material.needAlphaTesting()) {
  48238. var alphaTexture = material.getAlphaTestTexture();
  48239. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48240. if (alphaTexture) {
  48241. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48242. }
  48243. }
  48244. // Bones
  48245. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48246. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48247. }
  48248. }
  48249. // Draw
  48250. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48251. }
  48252. };
  48253. // Render target texture callbacks
  48254. var savedSceneClearColor;
  48255. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48256. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48257. savedSceneClearColor = scene.clearColor;
  48258. scene.clearColor = sceneClearColor;
  48259. });
  48260. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48261. scene.clearColor = savedSceneClearColor;
  48262. });
  48263. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48264. var engine = scene.getEngine();
  48265. var index;
  48266. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48267. renderSubMesh(opaqueSubMeshes.data[index]);
  48268. }
  48269. engine.setAlphaTesting(true);
  48270. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48271. renderSubMesh(alphaTestSubMeshes.data[index]);
  48272. }
  48273. engine.setAlphaTesting(false);
  48274. if (transparentSubMeshes.length) {
  48275. // Sort sub meshes
  48276. for (index = 0; index < transparentSubMeshes.length; index++) {
  48277. var submesh = transparentSubMeshes.data[index];
  48278. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48279. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48280. }
  48281. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48282. sortedArray.sort(function (a, b) {
  48283. // Alpha index first
  48284. if (a._alphaIndex > b._alphaIndex) {
  48285. return 1;
  48286. }
  48287. if (a._alphaIndex < b._alphaIndex) {
  48288. return -1;
  48289. }
  48290. // Then distance to camera
  48291. if (a._distanceToCamera < b._distanceToCamera) {
  48292. return 1;
  48293. }
  48294. if (a._distanceToCamera > b._distanceToCamera) {
  48295. return -1;
  48296. }
  48297. return 0;
  48298. });
  48299. // Render sub meshes
  48300. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48301. for (index = 0; index < sortedArray.length; index++) {
  48302. renderSubMesh(sortedArray[index]);
  48303. }
  48304. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48305. }
  48306. };
  48307. };
  48308. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48309. var transform = scene.getTransformMatrix();
  48310. var meshPosition;
  48311. if (this.useCustomMeshPosition) {
  48312. meshPosition = this.customMeshPosition;
  48313. }
  48314. else if (this.attachedNode) {
  48315. meshPosition = this.attachedNode.position;
  48316. }
  48317. else {
  48318. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48319. }
  48320. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48321. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48322. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48323. if (this.invert)
  48324. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48325. };
  48326. // Static methods
  48327. /**
  48328. * Creates a default mesh for the Volumeric Light Scattering post-process
  48329. * @param {string} The mesh name
  48330. * @param {BABYLON.Scene} The scene where to create the mesh
  48331. * @return {BABYLON.Mesh} the default mesh
  48332. */
  48333. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48334. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48335. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48336. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48337. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48338. mesh.material = material;
  48339. return mesh;
  48340. };
  48341. return VolumetricLightScatteringPostProcess;
  48342. }(BABYLON.PostProcess));
  48343. __decorate([
  48344. BABYLON.serializeAsVector3()
  48345. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48346. __decorate([
  48347. BABYLON.serialize()
  48348. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48349. __decorate([
  48350. BABYLON.serialize()
  48351. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48352. __decorate([
  48353. BABYLON.serializeAsMeshReference()
  48354. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48355. __decorate([
  48356. BABYLON.serialize()
  48357. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48358. __decorate([
  48359. BABYLON.serialize()
  48360. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48361. __decorate([
  48362. BABYLON.serialize()
  48363. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48367. __decorate([
  48368. BABYLON.serialize()
  48369. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48370. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48371. })(BABYLON || (BABYLON = {}));
  48372. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48373. // BABYLON.JS Chromatic Aberration GLSL Shader
  48374. // Author: Olivier Guyot
  48375. // Separates very slightly R, G and B colors on the edges of the screen
  48376. // Inspired by Francois Tarlier & Martins Upitis
  48377. var BABYLON;
  48378. (function (BABYLON) {
  48379. var LensRenderingPipeline = (function (_super) {
  48380. __extends(LensRenderingPipeline, _super);
  48381. /**
  48382. * @constructor
  48383. *
  48384. * Effect parameters are as follow:
  48385. * {
  48386. * chromatic_aberration: number; // from 0 to x (1 for realism)
  48387. * edge_blur: number; // from 0 to x (1 for realism)
  48388. * distortion: number; // from 0 to x (1 for realism)
  48389. * grain_amount: number; // from 0 to 1
  48390. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  48391. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  48392. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  48393. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  48394. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  48395. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  48396. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  48397. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  48398. * }
  48399. * Note: if an effect parameter is unset, effect is disabled
  48400. *
  48401. * @param {string} name - The rendering pipeline name
  48402. * @param {object} parameters - An object containing all parameters (see above)
  48403. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48404. * @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)
  48405. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48406. */
  48407. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  48408. if (ratio === void 0) { ratio = 1.0; }
  48409. var _this = _super.call(this, scene.getEngine(), name) || this;
  48410. // Lens effects can be of the following:
  48411. // - chromatic aberration (slight shift of RGB colors)
  48412. // - blur on the edge of the lens
  48413. // - lens distortion
  48414. // - depth-of-field blur & highlights enhancing
  48415. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48416. // - grain effect (noise or custom texture)
  48417. // Two additional texture samplers are needed:
  48418. // - depth map (for depth-of-field)
  48419. // - grain texture
  48420. /**
  48421. * The chromatic aberration PostProcess id in the pipeline
  48422. * @type {string}
  48423. */
  48424. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48425. /**
  48426. * The highlights enhancing PostProcess id in the pipeline
  48427. * @type {string}
  48428. */
  48429. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48430. /**
  48431. * The depth-of-field PostProcess id in the pipeline
  48432. * @type {string}
  48433. */
  48434. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48435. _this._scene = scene;
  48436. // Fetch texture samplers
  48437. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48438. if (parameters.grain_texture) {
  48439. _this._grainTexture = parameters.grain_texture;
  48440. }
  48441. else {
  48442. _this._createGrainTexture();
  48443. }
  48444. // save parameters
  48445. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48446. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48447. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48448. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  48449. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48450. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48451. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48452. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48453. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48454. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48455. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48456. // Create effects
  48457. _this._createChromaticAberrationPostProcess(ratio);
  48458. _this._createHighlightsPostProcess(ratio);
  48459. _this._createDepthOfFieldPostProcess(ratio / 4);
  48460. // Set up pipeline
  48461. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48462. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48463. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48464. if (_this._highlightsGain === -1) {
  48465. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  48466. }
  48467. // Finish
  48468. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48469. if (cameras) {
  48470. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48471. }
  48472. return _this;
  48473. }
  48474. // public methods (self explanatory)
  48475. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48476. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48477. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48478. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48479. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48480. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48481. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48482. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48483. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48484. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48485. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48486. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48487. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48488. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48489. };
  48490. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48491. this._highlightsPostProcess.updateEffect();
  48492. };
  48493. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48494. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48495. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48496. this._highlightsGain = amount;
  48497. };
  48498. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48499. if (this._highlightsGain === -1) {
  48500. this._highlightsGain = 1.0;
  48501. }
  48502. this._highlightsThreshold = amount;
  48503. };
  48504. LensRenderingPipeline.prototype.disableHighlights = function () {
  48505. this._highlightsGain = -1;
  48506. };
  48507. /**
  48508. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48509. */
  48510. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48511. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48512. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48513. this._chromaticAberrationPostProcess = undefined;
  48514. this._highlightsPostProcess = undefined;
  48515. this._depthOfFieldPostProcess = undefined;
  48516. this._grainTexture.dispose();
  48517. if (disableDepthRender)
  48518. this._scene.disableDepthRenderer();
  48519. };
  48520. // colors shifting and distortion
  48521. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48522. var _this = this;
  48523. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48524. [], // samplers
  48525. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48526. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48527. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48528. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48529. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48530. };
  48531. };
  48532. // highlights enhancing
  48533. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48534. var _this = this;
  48535. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48536. [], // samplers
  48537. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48538. this._highlightsPostProcess.onApply = function (effect) {
  48539. effect.setFloat('gain', _this._highlightsGain);
  48540. effect.setFloat('threshold', _this._highlightsThreshold);
  48541. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48542. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48543. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48544. };
  48545. };
  48546. // colors shifting and distortion
  48547. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48548. var _this = this;
  48549. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48550. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48551. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48552. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48553. this._depthOfFieldPostProcess.onApply = function (effect) {
  48554. effect.setTexture("depthSampler", _this._depthTexture);
  48555. effect.setTexture("grainSampler", _this._grainTexture);
  48556. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48557. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48558. effect.setFloat('grain_amount', _this._grainAmount);
  48559. effect.setBool('blur_noise', _this._blurNoise);
  48560. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48561. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48562. effect.setFloat('distortion', _this._distortion);
  48563. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48564. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48565. effect.setFloat('aperture', _this._dofAperture);
  48566. effect.setFloat('darken', _this._dofDarken);
  48567. effect.setFloat('edge_blur', _this._edgeBlur);
  48568. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48569. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48570. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48571. };
  48572. };
  48573. // creates a black and white random noise texture, 512x512
  48574. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48575. var size = 512;
  48576. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48577. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48578. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48579. var context = this._grainTexture.getContext();
  48580. var rand = function (min, max) {
  48581. return Math.random() * (max - min) + min;
  48582. };
  48583. var value;
  48584. for (var x = 0; x < size; x++) {
  48585. for (var y = 0; y < size; y++) {
  48586. value = Math.floor(rand(0.42, 0.58) * 255);
  48587. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48588. context.fillRect(x, y, 1, 1);
  48589. }
  48590. }
  48591. this._grainTexture.update(false);
  48592. };
  48593. return LensRenderingPipeline;
  48594. }(BABYLON.PostProcessRenderPipeline));
  48595. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48596. })(BABYLON || (BABYLON = {}));
  48597. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48598. //
  48599. // This post-process allows the modification of rendered colors by using
  48600. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48601. //
  48602. // The object needs to be provided an url to a texture containing the color
  48603. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48604. // Use an image editing software to tweak the LUT to match your needs.
  48605. //
  48606. // For an example of a color LUT, see here:
  48607. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48608. // For explanations on color grading, see here:
  48609. // http://udn.epicgames.com/Three/ColorGrading.html
  48610. //
  48611. var BABYLON;
  48612. (function (BABYLON) {
  48613. var ColorCorrectionPostProcess = (function (_super) {
  48614. __extends(ColorCorrectionPostProcess, _super);
  48615. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48616. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48617. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48618. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48619. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48620. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48621. _this.onApply = function (effect) {
  48622. effect.setTexture("colorTable", _this._colorTableTexture);
  48623. };
  48624. return _this;
  48625. }
  48626. return ColorCorrectionPostProcess;
  48627. }(BABYLON.PostProcess));
  48628. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48629. })(BABYLON || (BABYLON = {}));
  48630. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48631. var BABYLON;
  48632. (function (BABYLON) {
  48633. var AnaglyphFreeCamera = (function (_super) {
  48634. __extends(AnaglyphFreeCamera, _super);
  48635. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48636. var _this = _super.call(this, name, position, scene) || this;
  48637. _this.interaxialDistance = interaxialDistance;
  48638. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48639. return _this;
  48640. }
  48641. AnaglyphFreeCamera.prototype.getClassName = function () {
  48642. return "AnaglyphFreeCamera";
  48643. };
  48644. return AnaglyphFreeCamera;
  48645. }(BABYLON.FreeCamera));
  48646. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48647. var AnaglyphArcRotateCamera = (function (_super) {
  48648. __extends(AnaglyphArcRotateCamera, _super);
  48649. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48650. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48651. _this.interaxialDistance = interaxialDistance;
  48652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48653. return _this;
  48654. }
  48655. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48656. return "AnaglyphArcRotateCamera";
  48657. };
  48658. return AnaglyphArcRotateCamera;
  48659. }(BABYLON.ArcRotateCamera));
  48660. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48661. var AnaglyphGamepadCamera = (function (_super) {
  48662. __extends(AnaglyphGamepadCamera, _super);
  48663. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48664. var _this = _super.call(this, name, position, scene) || this;
  48665. _this.interaxialDistance = interaxialDistance;
  48666. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48667. return _this;
  48668. }
  48669. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48670. return "AnaglyphGamepadCamera";
  48671. };
  48672. return AnaglyphGamepadCamera;
  48673. }(BABYLON.GamepadCamera));
  48674. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48675. var AnaglyphUniversalCamera = (function (_super) {
  48676. __extends(AnaglyphUniversalCamera, _super);
  48677. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48678. var _this = _super.call(this, name, position, scene) || this;
  48679. _this.interaxialDistance = interaxialDistance;
  48680. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48681. return _this;
  48682. }
  48683. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48684. return "AnaglyphUniversalCamera";
  48685. };
  48686. return AnaglyphUniversalCamera;
  48687. }(BABYLON.UniversalCamera));
  48688. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48689. var StereoscopicFreeCamera = (function (_super) {
  48690. __extends(StereoscopicFreeCamera, _super);
  48691. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48692. var _this = _super.call(this, name, position, scene) || this;
  48693. _this.interaxialDistance = interaxialDistance;
  48694. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48695. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48696. return _this;
  48697. }
  48698. StereoscopicFreeCamera.prototype.getClassName = function () {
  48699. return "StereoscopicFreeCamera";
  48700. };
  48701. return StereoscopicFreeCamera;
  48702. }(BABYLON.FreeCamera));
  48703. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48704. var StereoscopicArcRotateCamera = (function (_super) {
  48705. __extends(StereoscopicArcRotateCamera, _super);
  48706. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48707. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48708. _this.interaxialDistance = interaxialDistance;
  48709. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48710. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48711. return _this;
  48712. }
  48713. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48714. return "StereoscopicArcRotateCamera";
  48715. };
  48716. return StereoscopicArcRotateCamera;
  48717. }(BABYLON.ArcRotateCamera));
  48718. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48719. var StereoscopicGamepadCamera = (function (_super) {
  48720. __extends(StereoscopicGamepadCamera, _super);
  48721. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48722. var _this = _super.call(this, name, position, scene) || this;
  48723. _this.interaxialDistance = interaxialDistance;
  48724. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48725. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48726. return _this;
  48727. }
  48728. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48729. return "StereoscopicGamepadCamera";
  48730. };
  48731. return StereoscopicGamepadCamera;
  48732. }(BABYLON.GamepadCamera));
  48733. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48734. var StereoscopicUniversalCamera = (function (_super) {
  48735. __extends(StereoscopicUniversalCamera, _super);
  48736. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48737. var _this = _super.call(this, name, position, scene) || this;
  48738. _this.interaxialDistance = interaxialDistance;
  48739. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48740. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48741. return _this;
  48742. }
  48743. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48744. return "StereoscopicUniversalCamera";
  48745. };
  48746. return StereoscopicUniversalCamera;
  48747. }(BABYLON.UniversalCamera));
  48748. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48749. })(BABYLON || (BABYLON = {}));
  48750. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48751. var BABYLON;
  48752. (function (BABYLON) {
  48753. var HolographicCamera = (function (_super) {
  48754. __extends(HolographicCamera, _super);
  48755. function HolographicCamera(name, scene) {
  48756. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48757. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  48758. _this._holographicViewMatrix = new BABYLON.Matrix();
  48759. _this._identityProjection = BABYLON.Matrix.Identity();
  48760. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  48761. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  48762. _this.fov = 30;
  48763. _this.minZ = 1.0;
  48764. _this.maxZ = 20;
  48765. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  48766. _this.isIntermediate = false;
  48767. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  48768. _this.layerMask = 0x0FFFFFFF;
  48769. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  48770. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  48771. var self = _this;
  48772. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  48773. self._holographicViewMatrix.m = window.getViewMatrix();
  48774. self.setViewMatrix(self._holographicViewMatrix);
  48775. var position = window.getCameraPositionVector();
  48776. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  48777. });
  48778. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  48779. if (scene.frustumPlanes) {
  48780. self.getFrustumPlanesToRef(scene.frustumPlanes);
  48781. }
  48782. });
  48783. scene.addCamera(_this);
  48784. if (!scene.activeCamera) {
  48785. scene.activeCamera = _this;
  48786. }
  48787. return _this;
  48788. }
  48789. HolographicCamera.prototype.getTypeName = function () {
  48790. return "HolographicCamera";
  48791. };
  48792. ;
  48793. HolographicCamera.prototype.getProjectionMatrix = function () {
  48794. return this._identityProjection;
  48795. };
  48796. ;
  48797. HolographicCamera.prototype.getViewMatrix = function () {
  48798. return this._holographicViewMatrix;
  48799. };
  48800. ;
  48801. HolographicCamera.prototype.setViewMatrix = function (view) {
  48802. this._holographicViewMatrix = view;
  48803. view.m[0] = -view.m[0];
  48804. view.m[1] = -view.m[1];
  48805. view.m[2] = -view.m[2];
  48806. view.m[3] = -view.m[3];
  48807. view.m[8] = -view.m[8];
  48808. view.m[9] = -view.m[9];
  48809. view.m[10] = -view.m[10];
  48810. view.m[11] = -view.m[11];
  48811. };
  48812. ;
  48813. HolographicCamera.prototype._initCache = function () { };
  48814. ;
  48815. HolographicCamera.prototype._updateCache = function () { };
  48816. ;
  48817. HolographicCamera.prototype._updateFromScene = function () { };
  48818. ;
  48819. // Synchronized
  48820. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  48821. return true;
  48822. };
  48823. ;
  48824. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  48825. return true;
  48826. };
  48827. ;
  48828. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  48829. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  48830. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  48831. return result;
  48832. };
  48833. ;
  48834. HolographicCamera.prototype.dispose = function () {
  48835. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48836. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  48837. _super.prototype.dispose.call(this);
  48838. };
  48839. return HolographicCamera;
  48840. }(BABYLON.Camera));
  48841. BABYLON.HolographicCamera = HolographicCamera;
  48842. })(BABYLON || (BABYLON = {}));
  48843. //# sourceMappingURL=babylon.holographicCamera.js.map
  48844. var BABYLON;
  48845. (function (BABYLON) {
  48846. var HDRRenderingPipeline = (function (_super) {
  48847. __extends(HDRRenderingPipeline, _super);
  48848. /**
  48849. * @constructor
  48850. * @param {string} name - The rendering pipeline name
  48851. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48852. * @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)
  48853. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48854. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48855. */
  48856. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48857. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48858. var _this = _super.call(this, scene.getEngine(), name) || this;
  48859. /**
  48860. * Public members
  48861. */
  48862. // Gaussian Blur
  48863. /**
  48864. * Gaussian blur coefficient
  48865. * @type {number}
  48866. */
  48867. _this.gaussCoeff = 0.3;
  48868. /**
  48869. * Gaussian blur mean
  48870. * @type {number}
  48871. */
  48872. _this.gaussMean = 1.0;
  48873. /**
  48874. * Gaussian blur standard deviation
  48875. * @type {number}
  48876. */
  48877. _this.gaussStandDev = 0.8;
  48878. /**
  48879. * Gaussian blur multiplier. Multiplies the blur effect
  48880. * @type {number}
  48881. */
  48882. _this.gaussMultiplier = 4.0;
  48883. // HDR
  48884. /**
  48885. * Exposure, controls the overall intensity of the pipeline
  48886. * @type {number}
  48887. */
  48888. _this.exposure = 1.0;
  48889. /**
  48890. * Minimum luminance that the post-process can output. Luminance is >= 0
  48891. * @type {number}
  48892. */
  48893. _this.minimumLuminance = 1.0;
  48894. /**
  48895. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48896. * @type {number}
  48897. */
  48898. _this.maximumLuminance = 1e20;
  48899. /**
  48900. * Increase rate for luminance: eye adaptation speed to dark
  48901. * @type {number}
  48902. */
  48903. _this.luminanceIncreaserate = 0.5;
  48904. /**
  48905. * Decrease rate for luminance: eye adaptation speed to bright
  48906. * @type {number}
  48907. */
  48908. _this.luminanceDecreaseRate = 0.5;
  48909. // Bright pass
  48910. /**
  48911. * Minimum luminance needed to compute HDR
  48912. * @type {number}
  48913. */
  48914. _this.brightThreshold = 0.8;
  48915. _this._needUpdate = true;
  48916. _this._scene = scene;
  48917. // Bright pass
  48918. _this._createBrightPassPostProcess(scene, ratio);
  48919. // Down sample X4
  48920. _this._createDownSampleX4PostProcess(scene, ratio);
  48921. // Create gaussian blur post-processes
  48922. _this._createGaussianBlurPostProcess(scene, ratio);
  48923. // Texture adder
  48924. _this._createTextureAdderPostProcess(scene, ratio);
  48925. // Luminance generator
  48926. _this._createLuminanceGeneratorPostProcess(scene);
  48927. // HDR
  48928. _this._createHDRPostProcess(scene, ratio);
  48929. // Pass postprocess
  48930. if (originalPostProcess === null) {
  48931. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48932. }
  48933. else {
  48934. _this._originalPostProcess = originalPostProcess;
  48935. }
  48936. // Configure pipeline
  48937. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48938. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48943. var addDownSamplerPostProcess = function (id) {
  48944. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48945. };
  48946. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48947. addDownSamplerPostProcess(i);
  48948. }
  48949. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48950. // Finish
  48951. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48952. if (cameras !== null) {
  48953. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48954. }
  48955. _this.update();
  48956. return _this;
  48957. }
  48958. /**
  48959. * Tells the pipeline to update its post-processes
  48960. */
  48961. HDRRenderingPipeline.prototype.update = function () {
  48962. this._needUpdate = true;
  48963. };
  48964. /**
  48965. * Returns the current calculated luminance
  48966. */
  48967. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48968. return this._hdrCurrentLuminance;
  48969. };
  48970. /**
  48971. * Returns the currently drawn luminance
  48972. */
  48973. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48974. return this._hdrOutputLuminance;
  48975. };
  48976. /**
  48977. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48978. */
  48979. HDRRenderingPipeline.prototype.dispose = function () {
  48980. for (var i = 0; i < this._scene.cameras.length; i++) {
  48981. var camera = this._scene.cameras[i];
  48982. this._originalPostProcess.dispose(camera);
  48983. this._brightPassPostProcess.dispose(camera);
  48984. this._downSampleX4PostProcess.dispose(camera);
  48985. this._guassianBlurHPostProcess.dispose(camera);
  48986. this._guassianBlurVPostProcess.dispose(camera);
  48987. this._textureAdderPostProcess.dispose(camera);
  48988. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  48989. this._downSamplePostProcesses[j].dispose(camera);
  48990. }
  48991. this._hdrPostProcess.dispose(camera);
  48992. }
  48993. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48994. _super.prototype.dispose.call(this);
  48995. };
  48996. /**
  48997. * Creates the HDR post-process and computes the luminance adaptation
  48998. */
  48999. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  49000. var _this = this;
  49001. var hdrLastLuminance = 0.0;
  49002. this._hdrOutputLuminance = -1.0;
  49003. this._hdrCurrentLuminance = 1.0;
  49004. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  49005. this._hdrPostProcess.onApply = function (effect) {
  49006. if (_this._hdrOutputLuminance < 0.0) {
  49007. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49008. }
  49009. else {
  49010. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  49011. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  49012. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  49013. }
  49014. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  49015. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  49016. }
  49017. else {
  49018. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49019. }
  49020. }
  49021. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  49022. hdrLastLuminance += scene.getEngine().getDeltaTime();
  49023. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49024. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49025. effect.setFloat("exposure", _this.exposure);
  49026. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  49027. _this._needUpdate = false;
  49028. };
  49029. };
  49030. /**
  49031. * Texture Adder post-process
  49032. */
  49033. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49034. var _this = this;
  49035. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  49036. this._textureAdderPostProcess.onApply = function (effect) {
  49037. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49038. };
  49039. };
  49040. /**
  49041. * Down sample X4 post-process
  49042. */
  49043. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49044. var _this = this;
  49045. var downSampleX4Offsets = new Array(32);
  49046. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  49047. this._downSampleX4PostProcess.onApply = function (effect) {
  49048. if (_this._needUpdate) {
  49049. var id = 0;
  49050. for (var i = -2; i < 2; i++) {
  49051. for (var j = -2; j < 2; j++) {
  49052. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  49053. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  49054. id += 2;
  49055. }
  49056. }
  49057. }
  49058. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49059. };
  49060. };
  49061. /**
  49062. * Bright pass post-process
  49063. */
  49064. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49065. var _this = this;
  49066. var brightOffsets = new Array(8);
  49067. var brightPassCallback = function (effect) {
  49068. if (_this._needUpdate) {
  49069. var sU = (1.0 / _this._brightPassPostProcess.width);
  49070. var sV = (1.0 / _this._brightPassPostProcess.height);
  49071. brightOffsets[0] = -0.5 * sU;
  49072. brightOffsets[1] = 0.5 * sV;
  49073. brightOffsets[2] = 0.5 * sU;
  49074. brightOffsets[3] = 0.5 * sV;
  49075. brightOffsets[4] = -0.5 * sU;
  49076. brightOffsets[5] = -0.5 * sV;
  49077. brightOffsets[6] = 0.5 * sU;
  49078. brightOffsets[7] = -0.5 * sV;
  49079. }
  49080. effect.setArray2("dsOffsets", brightOffsets);
  49081. effect.setFloat("brightThreshold", _this.brightThreshold);
  49082. };
  49083. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  49084. this._brightPassPostProcess.onApply = brightPassCallback;
  49085. };
  49086. /**
  49087. * Luminance generator. Creates the luminance post-process and down sample post-processes
  49088. */
  49089. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  49090. var _this = this;
  49091. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  49092. var luminanceOffsets = new Array(8);
  49093. var downSampleOffsets = new Array(18);
  49094. var halfDestPixelSize;
  49095. this._downSamplePostProcesses = new Array(lumSteps);
  49096. // Utils for luminance
  49097. var luminanceUpdateSourceOffsets = function (width, height) {
  49098. var sU = (1.0 / width);
  49099. var sV = (1.0 / height);
  49100. luminanceOffsets[0] = -0.5 * sU;
  49101. luminanceOffsets[1] = 0.5 * sV;
  49102. luminanceOffsets[2] = 0.5 * sU;
  49103. luminanceOffsets[3] = 0.5 * sV;
  49104. luminanceOffsets[4] = -0.5 * sU;
  49105. luminanceOffsets[5] = -0.5 * sV;
  49106. luminanceOffsets[6] = 0.5 * sU;
  49107. luminanceOffsets[7] = -0.5 * sV;
  49108. };
  49109. var luminanceUpdateDestOffsets = function (width, height) {
  49110. var id = 0;
  49111. for (var x = -1; x < 2; x++) {
  49112. for (var y = -1; y < 2; y++) {
  49113. downSampleOffsets[id] = (x) / width;
  49114. downSampleOffsets[id + 1] = (y) / height;
  49115. id += 2;
  49116. }
  49117. }
  49118. };
  49119. // Luminance callback
  49120. var luminanceCallback = function (effect) {
  49121. if (_this._needUpdate) {
  49122. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  49123. }
  49124. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49125. effect.setArray2("lumOffsets", luminanceOffsets);
  49126. };
  49127. // Down sample callbacks
  49128. var downSampleCallback = function (indice) {
  49129. var i = indice;
  49130. return function (effect) {
  49131. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49132. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49133. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  49134. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  49135. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  49136. effect.setArray2("dsOffsets", downSampleOffsets);
  49137. };
  49138. };
  49139. var downSampleAfterRenderCallback = function (effect) {
  49140. // Unpack result
  49141. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49142. 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);
  49143. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49144. };
  49145. // Create luminance post-process
  49146. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  49147. 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);
  49148. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  49149. // Create down sample post-processes
  49150. for (var i = lumSteps - 2; i >= 0; i--) {
  49151. var length = Math.pow(3, i);
  49152. ratio = { width: length, height: length };
  49153. var defines = "#define DOWN_SAMPLE\n";
  49154. if (i === 0) {
  49155. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  49156. }
  49157. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  49158. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  49159. if (i === 0) {
  49160. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  49161. }
  49162. }
  49163. };
  49164. /**
  49165. * Gaussian blur post-processes. Horizontal and Vertical
  49166. */
  49167. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  49168. var _this = this;
  49169. var blurOffsetsW = new Array(9);
  49170. var blurOffsetsH = new Array(9);
  49171. var blurWeights = new Array(9);
  49172. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  49173. // Utils for gaussian blur
  49174. var calculateBlurOffsets = function (height) {
  49175. var lastOutputDimensions = {
  49176. width: scene.getEngine().getRenderWidth(),
  49177. height: scene.getEngine().getRenderHeight()
  49178. };
  49179. for (var i = 0; i < 9; i++) {
  49180. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49181. if (height) {
  49182. blurOffsetsH[i] = value;
  49183. }
  49184. else {
  49185. blurOffsetsW[i] = value;
  49186. }
  49187. }
  49188. };
  49189. var calculateWeights = function () {
  49190. var x = 0.0;
  49191. for (var i = 0; i < 9; i++) {
  49192. x = (i - 4.0) / 4.0;
  49193. 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));
  49194. }
  49195. };
  49196. // Callback
  49197. var gaussianBlurCallback = function (height) {
  49198. return function (effect) {
  49199. if (_this._needUpdate) {
  49200. calculateWeights();
  49201. calculateBlurOffsets(height);
  49202. }
  49203. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  49204. effect.setArray("blurWeights", blurWeights);
  49205. effect.setFloat("multiplier", _this.gaussMultiplier);
  49206. };
  49207. };
  49208. // Create horizontal gaussian blur post-processes
  49209. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  49210. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  49211. // Create vertical gaussian blur post-process
  49212. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  49213. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  49214. };
  49215. return HDRRenderingPipeline;
  49216. }(BABYLON.PostProcessRenderPipeline));
  49217. // Luminance generator
  49218. HDRRenderingPipeline.LUM_STEPS = 6;
  49219. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  49220. })(BABYLON || (BABYLON = {}));
  49221. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  49222. var BABYLON;
  49223. (function (BABYLON) {
  49224. var FaceAdjacencies = (function () {
  49225. function FaceAdjacencies() {
  49226. this.edges = new Array();
  49227. this.edgesConnectedCount = 0;
  49228. }
  49229. return FaceAdjacencies;
  49230. }());
  49231. var EdgesRenderer = (function () {
  49232. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  49233. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  49234. if (epsilon === void 0) { epsilon = 0.95; }
  49235. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  49236. this.edgesWidthScalerForOrthographic = 1000.0;
  49237. this.edgesWidthScalerForPerspective = 50.0;
  49238. this._linesPositions = new Array();
  49239. this._linesNormals = new Array();
  49240. this._linesIndices = new Array();
  49241. this._buffers = {};
  49242. this._checkVerticesInsteadOfIndices = false;
  49243. this._source = source;
  49244. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  49245. this._epsilon = epsilon;
  49246. this._prepareRessources();
  49247. this._generateEdgesLines();
  49248. }
  49249. EdgesRenderer.prototype._prepareRessources = function () {
  49250. if (this._lineShader) {
  49251. return;
  49252. }
  49253. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  49254. attributes: ["position", "normal"],
  49255. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  49256. });
  49257. this._lineShader.disableDepthWrite = true;
  49258. this._lineShader.backFaceCulling = false;
  49259. };
  49260. EdgesRenderer.prototype.dispose = function () {
  49261. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  49262. if (buffer) {
  49263. buffer.dispose();
  49264. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  49265. }
  49266. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  49267. if (buffer) {
  49268. buffer.dispose();
  49269. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  49270. }
  49271. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  49272. this._lineShader.dispose();
  49273. };
  49274. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  49275. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  49276. return 0;
  49277. }
  49278. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  49279. return 1;
  49280. }
  49281. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  49282. return 2;
  49283. }
  49284. return -1;
  49285. };
  49286. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  49287. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  49288. return 0;
  49289. }
  49290. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  49291. return 1;
  49292. }
  49293. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  49294. return 2;
  49295. }
  49296. return -1;
  49297. };
  49298. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  49299. var needToCreateLine;
  49300. if (edge === undefined) {
  49301. needToCreateLine = true;
  49302. }
  49303. else {
  49304. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  49305. needToCreateLine = dotProduct < this._epsilon;
  49306. }
  49307. if (needToCreateLine) {
  49308. var offset = this._linesPositions.length / 3;
  49309. var normal = p0.subtract(p1);
  49310. normal.normalize();
  49311. // Positions
  49312. this._linesPositions.push(p0.x);
  49313. this._linesPositions.push(p0.y);
  49314. this._linesPositions.push(p0.z);
  49315. this._linesPositions.push(p0.x);
  49316. this._linesPositions.push(p0.y);
  49317. this._linesPositions.push(p0.z);
  49318. this._linesPositions.push(p1.x);
  49319. this._linesPositions.push(p1.y);
  49320. this._linesPositions.push(p1.z);
  49321. this._linesPositions.push(p1.x);
  49322. this._linesPositions.push(p1.y);
  49323. this._linesPositions.push(p1.z);
  49324. // Normals
  49325. this._linesNormals.push(p1.x);
  49326. this._linesNormals.push(p1.y);
  49327. this._linesNormals.push(p1.z);
  49328. this._linesNormals.push(-1);
  49329. this._linesNormals.push(p1.x);
  49330. this._linesNormals.push(p1.y);
  49331. this._linesNormals.push(p1.z);
  49332. this._linesNormals.push(1);
  49333. this._linesNormals.push(p0.x);
  49334. this._linesNormals.push(p0.y);
  49335. this._linesNormals.push(p0.z);
  49336. this._linesNormals.push(-1);
  49337. this._linesNormals.push(p0.x);
  49338. this._linesNormals.push(p0.y);
  49339. this._linesNormals.push(p0.z);
  49340. this._linesNormals.push(1);
  49341. // Indices
  49342. this._linesIndices.push(offset);
  49343. this._linesIndices.push(offset + 1);
  49344. this._linesIndices.push(offset + 2);
  49345. this._linesIndices.push(offset);
  49346. this._linesIndices.push(offset + 2);
  49347. this._linesIndices.push(offset + 3);
  49348. }
  49349. };
  49350. EdgesRenderer.prototype._generateEdgesLines = function () {
  49351. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49352. var indices = this._source.getIndices();
  49353. // First let's find adjacencies
  49354. var adjacencies = new Array();
  49355. var faceNormals = new Array();
  49356. var index;
  49357. var faceAdjacencies;
  49358. // Prepare faces
  49359. for (index = 0; index < indices.length; index += 3) {
  49360. faceAdjacencies = new FaceAdjacencies();
  49361. var p0Index = indices[index];
  49362. var p1Index = indices[index + 1];
  49363. var p2Index = indices[index + 2];
  49364. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  49365. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  49366. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  49367. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  49368. faceNormal.normalize();
  49369. faceNormals.push(faceNormal);
  49370. adjacencies.push(faceAdjacencies);
  49371. }
  49372. // Scan
  49373. for (index = 0; index < adjacencies.length; index++) {
  49374. faceAdjacencies = adjacencies[index];
  49375. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  49376. var otherFaceAdjacencies = adjacencies[otherIndex];
  49377. if (faceAdjacencies.edgesConnectedCount === 3) {
  49378. break;
  49379. }
  49380. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  49381. continue;
  49382. }
  49383. var otherP0 = indices[otherIndex * 3];
  49384. var otherP1 = indices[otherIndex * 3 + 1];
  49385. var otherP2 = indices[otherIndex * 3 + 2];
  49386. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  49387. var otherEdgeIndex;
  49388. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  49389. continue;
  49390. }
  49391. switch (edgeIndex) {
  49392. case 0:
  49393. if (this._checkVerticesInsteadOfIndices) {
  49394. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49395. }
  49396. else {
  49397. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  49398. }
  49399. break;
  49400. case 1:
  49401. if (this._checkVerticesInsteadOfIndices) {
  49402. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49403. }
  49404. else {
  49405. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  49406. }
  49407. break;
  49408. case 2:
  49409. if (this._checkVerticesInsteadOfIndices) {
  49410. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49411. }
  49412. else {
  49413. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  49414. }
  49415. break;
  49416. }
  49417. if (otherEdgeIndex === -1) {
  49418. continue;
  49419. }
  49420. faceAdjacencies.edges[edgeIndex] = otherIndex;
  49421. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  49422. faceAdjacencies.edgesConnectedCount++;
  49423. otherFaceAdjacencies.edgesConnectedCount++;
  49424. if (faceAdjacencies.edgesConnectedCount === 3) {
  49425. break;
  49426. }
  49427. }
  49428. }
  49429. }
  49430. // Create lines
  49431. for (index = 0; index < adjacencies.length; index++) {
  49432. // 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
  49433. var current = adjacencies[index];
  49434. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  49435. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  49436. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  49437. }
  49438. // Merge into a single mesh
  49439. var engine = this._source.getScene().getEngine();
  49440. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  49441. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  49442. this._ib = engine.createIndexBuffer(this._linesIndices);
  49443. this._indicesCount = this._linesIndices.length;
  49444. };
  49445. EdgesRenderer.prototype.render = function () {
  49446. if (!this._lineShader.isReady()) {
  49447. return;
  49448. }
  49449. var scene = this._source.getScene();
  49450. var engine = scene.getEngine();
  49451. this._lineShader._preBind();
  49452. // VBOs
  49453. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  49454. scene.resetCachedMaterial();
  49455. this._lineShader.setColor4("color", this._source.edgesColor);
  49456. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  49457. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  49458. }
  49459. else {
  49460. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  49461. }
  49462. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  49463. this._lineShader.bind(this._source.getWorldMatrix());
  49464. // Draw order
  49465. engine.draw(true, 0, this._indicesCount);
  49466. this._lineShader.unbind();
  49467. engine.setDepthWrite(true);
  49468. };
  49469. return EdgesRenderer;
  49470. }());
  49471. BABYLON.EdgesRenderer = EdgesRenderer;
  49472. })(BABYLON || (BABYLON = {}));
  49473. //# sourceMappingURL=babylon.edgesRenderer.js.map
  49474. var BABYLON;
  49475. (function (BABYLON) {
  49476. var TonemappingOperator;
  49477. (function (TonemappingOperator) {
  49478. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49479. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49480. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49481. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49482. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49483. ;
  49484. var TonemapPostProcess = (function (_super) {
  49485. __extends(TonemapPostProcess, _super);
  49486. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49488. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49489. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49490. _this._operator = _operator;
  49491. _this.exposureAdjustment = exposureAdjustment;
  49492. var defines = "#define ";
  49493. if (_this._operator === TonemappingOperator.Hable)
  49494. defines += "HABLE_TONEMAPPING";
  49495. else if (_this._operator === TonemappingOperator.Reinhard)
  49496. defines += "REINHARD_TONEMAPPING";
  49497. else if (_this._operator === TonemappingOperator.HejiDawson)
  49498. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49499. else if (_this._operator === TonemappingOperator.Photographic)
  49500. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49501. //sadly a second call to create the effect.
  49502. _this.updateEffect(defines);
  49503. _this.onApply = function (effect) {
  49504. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49505. };
  49506. return _this;
  49507. }
  49508. return TonemapPostProcess;
  49509. }(BABYLON.PostProcess));
  49510. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49511. })(BABYLON || (BABYLON = {}));
  49512. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49513. var BABYLON;
  49514. (function (BABYLON) {
  49515. var ReflectionProbe = (function () {
  49516. function ReflectionProbe(name, size, scene, generateMipMaps) {
  49517. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49518. var _this = this;
  49519. this.name = name;
  49520. this._viewMatrix = BABYLON.Matrix.Identity();
  49521. this._target = BABYLON.Vector3.Zero();
  49522. this._add = BABYLON.Vector3.Zero();
  49523. this.invertYAxis = false;
  49524. this.position = BABYLON.Vector3.Zero();
  49525. this._scene = scene;
  49526. this._scene.reflectionProbes.push(this);
  49527. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49528. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49529. switch (faceIndex) {
  49530. case 0:
  49531. _this._add.copyFromFloats(1, 0, 0);
  49532. break;
  49533. case 1:
  49534. _this._add.copyFromFloats(-1, 0, 0);
  49535. break;
  49536. case 2:
  49537. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49538. break;
  49539. case 3:
  49540. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49541. break;
  49542. case 4:
  49543. _this._add.copyFromFloats(0, 0, 1);
  49544. break;
  49545. case 5:
  49546. _this._add.copyFromFloats(0, 0, -1);
  49547. break;
  49548. }
  49549. if (_this._attachedMesh) {
  49550. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49551. }
  49552. _this.position.addToRef(_this._add, _this._target);
  49553. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49554. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49555. });
  49556. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49557. scene.updateTransformMatrix(true);
  49558. });
  49559. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49560. }
  49561. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49562. get: function () {
  49563. return this._renderTargetTexture.refreshRate;
  49564. },
  49565. set: function (value) {
  49566. this._renderTargetTexture.refreshRate = value;
  49567. },
  49568. enumerable: true,
  49569. configurable: true
  49570. });
  49571. ReflectionProbe.prototype.getScene = function () {
  49572. return this._scene;
  49573. };
  49574. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49575. get: function () {
  49576. return this._renderTargetTexture;
  49577. },
  49578. enumerable: true,
  49579. configurable: true
  49580. });
  49581. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49582. get: function () {
  49583. return this._renderTargetTexture.renderList;
  49584. },
  49585. enumerable: true,
  49586. configurable: true
  49587. });
  49588. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49589. this._attachedMesh = mesh;
  49590. };
  49591. ReflectionProbe.prototype.dispose = function () {
  49592. var index = this._scene.reflectionProbes.indexOf(this);
  49593. if (index !== -1) {
  49594. // Remove from the scene if found
  49595. this._scene.reflectionProbes.splice(index, 1);
  49596. }
  49597. if (this._renderTargetTexture) {
  49598. this._renderTargetTexture.dispose();
  49599. this._renderTargetTexture = null;
  49600. }
  49601. };
  49602. return ReflectionProbe;
  49603. }());
  49604. BABYLON.ReflectionProbe = ReflectionProbe;
  49605. })(BABYLON || (BABYLON = {}));
  49606. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49607. var BABYLON;
  49608. (function (BABYLON) {
  49609. var SolidParticle = (function () {
  49610. /**
  49611. * Creates a Solid Particle object.
  49612. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49613. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49614. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49615. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49616. * `shapeId` (integer) is the model shape identifier in the SPS.
  49617. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49618. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49619. */
  49620. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49621. this.idx = 0; // particle global index
  49622. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49623. this.position = BABYLON.Vector3.Zero(); // position
  49624. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49625. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49626. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49627. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49628. this.alive = true; // alive
  49629. this.isVisible = true; // visibility
  49630. this._pos = 0; // index of this particle in the global "positions" array
  49631. this.shapeId = 0; // model shape id
  49632. this.idxInShape = 0; // index of the particle in its shape id
  49633. this.idx = particleIndex;
  49634. this._pos = positionIndex;
  49635. this._model = model;
  49636. this.shapeId = shapeId;
  49637. this.idxInShape = idxInShape;
  49638. this._sps = sps;
  49639. if (modelBoundingInfo) {
  49640. this._modelBoundingInfo = modelBoundingInfo;
  49641. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49642. }
  49643. }
  49644. Object.defineProperty(SolidParticle.prototype, "scale", {
  49645. /**
  49646. * legacy support, changed scale to scaling
  49647. */
  49648. get: function () {
  49649. return this.scaling;
  49650. },
  49651. set: function (scale) {
  49652. this.scaling = scale;
  49653. },
  49654. enumerable: true,
  49655. configurable: true
  49656. });
  49657. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49658. /**
  49659. * legacy support, changed quaternion to rotationQuaternion
  49660. */
  49661. get: function () {
  49662. return this.rotationQuaternion;
  49663. },
  49664. set: function (q) {
  49665. this.rotationQuaternion = q;
  49666. },
  49667. enumerable: true,
  49668. configurable: true
  49669. });
  49670. /**
  49671. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49672. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49673. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49674. */
  49675. SolidParticle.prototype.intersectsMesh = function (target) {
  49676. if (!this._boundingInfo || !target._boundingInfo) {
  49677. return false;
  49678. }
  49679. if (this._sps._bSphereOnly) {
  49680. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49681. }
  49682. return this._boundingInfo.intersects(target._boundingInfo, false);
  49683. };
  49684. return SolidParticle;
  49685. }());
  49686. BABYLON.SolidParticle = SolidParticle;
  49687. var ModelShape = (function () {
  49688. /**
  49689. * 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.
  49690. * SPS internal tool, don't use it manually.
  49691. */
  49692. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49693. this.shapeID = id;
  49694. this._shape = shape;
  49695. this._shapeUV = shapeUV;
  49696. this._positionFunction = posFunction;
  49697. this._vertexFunction = vtxFunction;
  49698. }
  49699. return ModelShape;
  49700. }());
  49701. BABYLON.ModelShape = ModelShape;
  49702. })(BABYLON || (BABYLON = {}));
  49703. //# sourceMappingURL=babylon.solidParticle.js.map
  49704. var BABYLON;
  49705. (function (BABYLON) {
  49706. /**
  49707. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49708. */
  49709. var SolidParticleSystem = (function () {
  49710. /**
  49711. * Creates a SPS (Solid Particle System) object.
  49712. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49713. * `scene` (Scene) is the scene in which the SPS is added.
  49714. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49715. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49716. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49717. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49718. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49719. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49720. */
  49721. function SolidParticleSystem(name, scene, options) {
  49722. // public members
  49723. /**
  49724. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49725. * Example : var p = SPS.particles[i];
  49726. */
  49727. this.particles = new Array();
  49728. /**
  49729. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49730. */
  49731. this.nbParticles = 0;
  49732. /**
  49733. * If the particles must ever face the camera (default false). Useful for planar particles.
  49734. */
  49735. this.billboard = false;
  49736. /**
  49737. * Recompute normals when adding a shape
  49738. */
  49739. this.recomputeNormals = true;
  49740. /**
  49741. * This a counter ofr your own usage. It's not set by any SPS functions.
  49742. */
  49743. this.counter = 0;
  49744. /**
  49745. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49746. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49747. */
  49748. this.vars = {};
  49749. this._positions = new Array();
  49750. this._indices = new Array();
  49751. this._normals = new Array();
  49752. this._colors = new Array();
  49753. this._uvs = new Array();
  49754. this._index = 0; // indices index
  49755. this._updatable = true;
  49756. this._pickable = false;
  49757. this._isVisibilityBoxLocked = false;
  49758. this._alwaysVisible = false;
  49759. this._shapeCounter = 0;
  49760. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49761. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49762. this._computeParticleColor = true;
  49763. this._computeParticleTexture = true;
  49764. this._computeParticleRotation = true;
  49765. this._computeParticleVertex = false;
  49766. this._computeBoundingBox = false;
  49767. this._cam_axisZ = BABYLON.Vector3.Zero();
  49768. this._cam_axisY = BABYLON.Vector3.Zero();
  49769. this._cam_axisX = BABYLON.Vector3.Zero();
  49770. this._axisX = BABYLON.Axis.X;
  49771. this._axisY = BABYLON.Axis.Y;
  49772. this._axisZ = BABYLON.Axis.Z;
  49773. this._camDir = BABYLON.Vector3.Zero();
  49774. this._rotMatrix = new BABYLON.Matrix();
  49775. this._invertMatrix = new BABYLON.Matrix();
  49776. this._rotated = BABYLON.Vector3.Zero();
  49777. this._quaternion = new BABYLON.Quaternion();
  49778. this._vertex = BABYLON.Vector3.Zero();
  49779. this._normal = BABYLON.Vector3.Zero();
  49780. this._yaw = 0.0;
  49781. this._pitch = 0.0;
  49782. this._roll = 0.0;
  49783. this._halfroll = 0.0;
  49784. this._halfpitch = 0.0;
  49785. this._halfyaw = 0.0;
  49786. this._sinRoll = 0.0;
  49787. this._cosRoll = 0.0;
  49788. this._sinPitch = 0.0;
  49789. this._cosPitch = 0.0;
  49790. this._sinYaw = 0.0;
  49791. this._cosYaw = 0.0;
  49792. this._w = 0.0;
  49793. this._minimum = BABYLON.Tmp.Vector3[0];
  49794. this._maximum = BABYLON.Tmp.Vector3[1];
  49795. this._scale = BABYLON.Tmp.Vector3[2];
  49796. this._translation = BABYLON.Tmp.Vector3[3];
  49797. this._minBbox = BABYLON.Tmp.Vector3[4];
  49798. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49799. this._particlesIntersect = false;
  49800. this._bSphereOnly = false;
  49801. this._bSphereRadiusFactor = 1.0;
  49802. this.name = name;
  49803. this._scene = scene;
  49804. this._camera = scene.activeCamera;
  49805. this._pickable = options ? options.isPickable : false;
  49806. this._particlesIntersect = options ? options.particleIntersection : false;
  49807. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49808. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49809. if (options && options.updatable) {
  49810. this._updatable = options.updatable;
  49811. }
  49812. else {
  49813. this._updatable = true;
  49814. }
  49815. if (this._pickable) {
  49816. this.pickedParticles = [];
  49817. }
  49818. }
  49819. /**
  49820. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49821. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49822. */
  49823. SolidParticleSystem.prototype.buildMesh = function () {
  49824. if (this.nbParticles === 0) {
  49825. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49826. this.addShape(triangle, 1);
  49827. triangle.dispose();
  49828. }
  49829. this._positions32 = new Float32Array(this._positions);
  49830. this._uvs32 = new Float32Array(this._uvs);
  49831. this._colors32 = new Float32Array(this._colors);
  49832. if (this.recomputeNormals) {
  49833. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49834. }
  49835. this._normals32 = new Float32Array(this._normals);
  49836. this._fixedNormal32 = new Float32Array(this._normals);
  49837. var vertexData = new BABYLON.VertexData();
  49838. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49839. vertexData.indices = this._indices;
  49840. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49841. if (this._uvs32) {
  49842. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49843. ;
  49844. }
  49845. if (this._colors32) {
  49846. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49847. }
  49848. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49849. vertexData.applyToMesh(mesh, this._updatable);
  49850. this.mesh = mesh;
  49851. this.mesh.isPickable = this._pickable;
  49852. // free memory
  49853. this._positions = null;
  49854. this._normals = null;
  49855. this._uvs = null;
  49856. this._colors = null;
  49857. if (!this._updatable) {
  49858. this.particles.length = 0;
  49859. }
  49860. return mesh;
  49861. };
  49862. /**
  49863. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49864. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49865. * Thus the particles generated from `digest()` have their property `position` set yet.
  49866. * `mesh` ( Mesh ) is the mesh to be digested
  49867. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49868. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49869. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49870. */
  49871. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49872. var size = (options && options.facetNb) || 1;
  49873. var number = (options && options.number);
  49874. var delta = (options && options.delta) || 0;
  49875. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49876. var meshInd = mesh.getIndices();
  49877. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49878. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49879. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49880. var f = 0; // facet counter
  49881. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49882. // compute size from number
  49883. if (number) {
  49884. number = (number > totalFacets) ? totalFacets : number;
  49885. size = Math.round(totalFacets / number);
  49886. delta = 0;
  49887. }
  49888. else {
  49889. size = (size > totalFacets) ? totalFacets : size;
  49890. }
  49891. var facetPos = []; // submesh positions
  49892. var facetInd = []; // submesh indices
  49893. var facetUV = []; // submesh UV
  49894. var facetCol = []; // submesh colors
  49895. var barycenter = BABYLON.Tmp.Vector3[0];
  49896. var rand;
  49897. var sizeO = size;
  49898. while (f < totalFacets) {
  49899. size = sizeO + Math.floor((1 + delta) * Math.random());
  49900. if (f > totalFacets - size) {
  49901. size = totalFacets - f;
  49902. }
  49903. // reset temp arrays
  49904. facetPos.length = 0;
  49905. facetInd.length = 0;
  49906. facetUV.length = 0;
  49907. facetCol.length = 0;
  49908. // iterate over "size" facets
  49909. var fi = 0;
  49910. for (var j = f * 3; j < (f + size) * 3; j++) {
  49911. facetInd.push(fi);
  49912. var i = meshInd[j];
  49913. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49914. if (meshUV) {
  49915. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49916. }
  49917. if (meshCol) {
  49918. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49919. }
  49920. fi++;
  49921. }
  49922. // create a model shape for each single particle
  49923. var idx = this.nbParticles;
  49924. var shape = this._posToShape(facetPos);
  49925. var shapeUV = this._uvsToShapeUV(facetUV);
  49926. // compute the barycenter of the shape
  49927. var v;
  49928. for (v = 0; v < shape.length; v++) {
  49929. barycenter.addInPlace(shape[v]);
  49930. }
  49931. barycenter.scaleInPlace(1 / shape.length);
  49932. // shift the shape from its barycenter to the origin
  49933. for (v = 0; v < shape.length; v++) {
  49934. shape[v].subtractInPlace(barycenter);
  49935. }
  49936. var bInfo;
  49937. if (this._particlesIntersect) {
  49938. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49939. }
  49940. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49941. // add the particle in the SPS
  49942. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49943. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49944. // initialize the particle position
  49945. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49946. this._index += shape.length;
  49947. idx++;
  49948. this.nbParticles++;
  49949. this._shapeCounter++;
  49950. f += size;
  49951. }
  49952. return this;
  49953. };
  49954. //reset copy
  49955. SolidParticleSystem.prototype._resetCopy = function () {
  49956. this._copy.position.x = 0;
  49957. this._copy.position.y = 0;
  49958. this._copy.position.z = 0;
  49959. this._copy.rotation.x = 0;
  49960. this._copy.rotation.y = 0;
  49961. this._copy.rotation.z = 0;
  49962. this._copy.rotationQuaternion = null;
  49963. this._copy.scaling.x = 1;
  49964. this._copy.scaling.y = 1;
  49965. this._copy.scaling.z = 1;
  49966. this._copy.uvs.x = 0;
  49967. this._copy.uvs.y = 0;
  49968. this._copy.uvs.z = 1;
  49969. this._copy.uvs.w = 1;
  49970. this._copy.color = null;
  49971. };
  49972. // _meshBuilder : inserts the shape model in the global SPS mesh
  49973. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49974. var i;
  49975. var u = 0;
  49976. var c = 0;
  49977. var n = 0;
  49978. this._resetCopy();
  49979. if (options && options.positionFunction) {
  49980. options.positionFunction(this._copy, idx, idxInShape);
  49981. }
  49982. if (this._copy.rotationQuaternion) {
  49983. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49984. }
  49985. else {
  49986. this._yaw = this._copy.rotation.y;
  49987. this._pitch = this._copy.rotation.x;
  49988. this._roll = this._copy.rotation.z;
  49989. this._quaternionRotationYPR();
  49990. }
  49991. this._quaternionToRotationMatrix();
  49992. for (i = 0; i < shape.length; i++) {
  49993. this._vertex.x = shape[i].x;
  49994. this._vertex.y = shape[i].y;
  49995. this._vertex.z = shape[i].z;
  49996. if (options && options.vertexFunction) {
  49997. options.vertexFunction(this._copy, this._vertex, i);
  49998. }
  49999. this._vertex.x *= this._copy.scaling.x;
  50000. this._vertex.y *= this._copy.scaling.y;
  50001. this._vertex.z *= this._copy.scaling.z;
  50002. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50003. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50004. if (meshUV) {
  50005. 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);
  50006. u += 2;
  50007. }
  50008. if (this._copy.color) {
  50009. this._color = this._copy.color;
  50010. }
  50011. else if (meshCol && meshCol[c] !== undefined) {
  50012. this._color.r = meshCol[c];
  50013. this._color.g = meshCol[c + 1];
  50014. this._color.b = meshCol[c + 2];
  50015. this._color.a = meshCol[c + 3];
  50016. }
  50017. else {
  50018. this._color.r = 1;
  50019. this._color.g = 1;
  50020. this._color.b = 1;
  50021. this._color.a = 1;
  50022. }
  50023. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50024. c += 4;
  50025. if (!this.recomputeNormals && meshNor) {
  50026. this._normal.x = meshNor[n];
  50027. this._normal.y = meshNor[n + 1];
  50028. this._normal.z = meshNor[n + 2];
  50029. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  50030. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50031. n += 3;
  50032. }
  50033. }
  50034. for (i = 0; i < meshInd.length; i++) {
  50035. indices.push(p + meshInd[i]);
  50036. }
  50037. if (this._pickable) {
  50038. var nbfaces = meshInd.length / 3;
  50039. for (i = 0; i < nbfaces; i++) {
  50040. this.pickedParticles.push({ idx: idx, faceId: i });
  50041. }
  50042. }
  50043. };
  50044. // returns a shape array from positions array
  50045. SolidParticleSystem.prototype._posToShape = function (positions) {
  50046. var shape = [];
  50047. for (var i = 0; i < positions.length; i += 3) {
  50048. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50049. }
  50050. return shape;
  50051. };
  50052. // returns a shapeUV array from a Vector4 uvs
  50053. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50054. var shapeUV = [];
  50055. if (uvs) {
  50056. for (var i = 0; i < uvs.length; i++)
  50057. shapeUV.push(uvs[i]);
  50058. }
  50059. return shapeUV;
  50060. };
  50061. // adds a new particle object in the particles array
  50062. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  50063. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  50064. };
  50065. /**
  50066. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50067. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50068. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  50069. * `nb` (positive integer) the number of particles to be created from this model
  50070. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  50071. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  50072. */
  50073. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50074. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50075. var meshInd = mesh.getIndices();
  50076. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50077. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50078. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50079. var bbInfo;
  50080. if (this._particlesIntersect) {
  50081. bbInfo = mesh.getBoundingInfo();
  50082. }
  50083. var shape = this._posToShape(meshPos);
  50084. var shapeUV = this._uvsToShapeUV(meshUV);
  50085. var posfunc = options ? options.positionFunction : null;
  50086. var vtxfunc = options ? options.vertexFunction : null;
  50087. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  50088. // particles
  50089. var idx = this.nbParticles;
  50090. for (var i = 0; i < nb; i++) {
  50091. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50092. if (this._updatable) {
  50093. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  50094. }
  50095. this._index += shape.length;
  50096. idx++;
  50097. }
  50098. this.nbParticles += nb;
  50099. this._shapeCounter++;
  50100. return this._shapeCounter - 1;
  50101. };
  50102. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50103. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50104. this._resetCopy();
  50105. if (particle._model._positionFunction) {
  50106. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50107. }
  50108. if (this._copy.rotationQuaternion) {
  50109. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50110. }
  50111. else {
  50112. this._yaw = this._copy.rotation.y;
  50113. this._pitch = this._copy.rotation.x;
  50114. this._roll = this._copy.rotation.z;
  50115. this._quaternionRotationYPR();
  50116. }
  50117. this._quaternionToRotationMatrix();
  50118. this._shape = particle._model._shape;
  50119. for (var pt = 0; pt < this._shape.length; pt++) {
  50120. this._vertex.x = this._shape[pt].x;
  50121. this._vertex.y = this._shape[pt].y;
  50122. this._vertex.z = this._shape[pt].z;
  50123. if (particle._model._vertexFunction) {
  50124. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50125. }
  50126. this._vertex.x *= this._copy.scaling.x;
  50127. this._vertex.y *= this._copy.scaling.y;
  50128. this._vertex.z *= this._copy.scaling.z;
  50129. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50130. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50131. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50132. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50133. }
  50134. particle.position.x = 0.0;
  50135. particle.position.y = 0.0;
  50136. particle.position.z = 0.0;
  50137. particle.rotation.x = 0.0;
  50138. particle.rotation.y = 0.0;
  50139. particle.rotation.z = 0.0;
  50140. particle.rotationQuaternion = null;
  50141. particle.scaling.x = 1.0;
  50142. particle.scaling.y = 1.0;
  50143. particle.scaling.z = 1.0;
  50144. };
  50145. /**
  50146. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50147. */
  50148. SolidParticleSystem.prototype.rebuildMesh = function () {
  50149. for (var p = 0; p < this.particles.length; p++) {
  50150. this._rebuildParticle(this.particles[p]);
  50151. }
  50152. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50153. };
  50154. /**
  50155. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50156. * This method calls `updateParticle()` for each particle of the SPS.
  50157. * For an animated SPS, it is usually called within the render loop.
  50158. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50159. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50160. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50161. */
  50162. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50163. if (start === void 0) { start = 0; }
  50164. if (end === void 0) { end = this.nbParticles - 1; }
  50165. if (update === void 0) { update = true; }
  50166. if (!this._updatable) {
  50167. return;
  50168. }
  50169. // custom beforeUpdate
  50170. this.beforeUpdateParticles(start, end, update);
  50171. this._cam_axisX.x = 1.0;
  50172. this._cam_axisX.y = 0.0;
  50173. this._cam_axisX.z = 0.0;
  50174. this._cam_axisY.x = 0.0;
  50175. this._cam_axisY.y = 1.0;
  50176. this._cam_axisY.z = 0.0;
  50177. this._cam_axisZ.x = 0.0;
  50178. this._cam_axisZ.y = 0.0;
  50179. this._cam_axisZ.z = 1.0;
  50180. // if the particles will always face the camera
  50181. if (this.billboard) {
  50182. // compute the camera position and un-rotate it by the current mesh rotation
  50183. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  50184. this._quaternionToRotationMatrix();
  50185. this._rotMatrix.invertToRef(this._invertMatrix);
  50186. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  50187. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50188. this._cam_axisZ.normalize();
  50189. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  50190. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  50191. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50192. this._cam_axisY.normalize();
  50193. this._cam_axisX.normalize();
  50194. }
  50195. }
  50196. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50197. var idx = 0; // current position index in the global array positions32
  50198. var index = 0; // position start index in the global array positions32 of the current particle
  50199. var colidx = 0; // current color index in the global array colors32
  50200. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50201. var uvidx = 0; // current uv index in the global array uvs32
  50202. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50203. var pt = 0; // current index in the particle model shape
  50204. if (this.mesh.isFacetDataEnabled) {
  50205. this._computeBoundingBox = true;
  50206. }
  50207. if (this._computeBoundingBox) {
  50208. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50209. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50210. }
  50211. // particle loop
  50212. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  50213. for (var p = start; p <= end; p++) {
  50214. this._particle = this.particles[p];
  50215. this._shape = this._particle._model._shape;
  50216. this._shapeUV = this._particle._model._shapeUV;
  50217. // call to custom user function to update the particle properties
  50218. this.updateParticle(this._particle);
  50219. if (this._particle.isVisible) {
  50220. // particle rotation matrix
  50221. if (this.billboard) {
  50222. this._particle.rotation.x = 0.0;
  50223. this._particle.rotation.y = 0.0;
  50224. }
  50225. if (this._computeParticleRotation || this.billboard) {
  50226. if (this._particle.rotationQuaternion) {
  50227. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50228. }
  50229. else {
  50230. this._yaw = this._particle.rotation.y;
  50231. this._pitch = this._particle.rotation.x;
  50232. this._roll = this._particle.rotation.z;
  50233. this._quaternionRotationYPR();
  50234. }
  50235. this._quaternionToRotationMatrix();
  50236. }
  50237. // particle vertex loop
  50238. for (pt = 0; pt < this._shape.length; pt++) {
  50239. idx = index + pt * 3;
  50240. colidx = colorIndex + pt * 4;
  50241. uvidx = uvIndex + pt * 2;
  50242. this._vertex.x = this._shape[pt].x;
  50243. this._vertex.y = this._shape[pt].y;
  50244. this._vertex.z = this._shape[pt].z;
  50245. if (this._computeParticleVertex) {
  50246. this.updateParticleVertex(this._particle, this._vertex, pt);
  50247. }
  50248. // positions
  50249. this._vertex.x *= this._particle.scaling.x;
  50250. this._vertex.y *= this._particle.scaling.y;
  50251. this._vertex.z *= this._particle.scaling.z;
  50252. 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];
  50253. 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;
  50254. 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;
  50255. 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;
  50256. 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;
  50257. 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;
  50258. 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;
  50259. if (this._computeBoundingBox) {
  50260. if (this._positions32[idx] < this._minimum.x) {
  50261. this._minimum.x = this._positions32[idx];
  50262. }
  50263. if (this._positions32[idx] > this._maximum.x) {
  50264. this._maximum.x = this._positions32[idx];
  50265. }
  50266. if (this._positions32[idx + 1] < this._minimum.y) {
  50267. this._minimum.y = this._positions32[idx + 1];
  50268. }
  50269. if (this._positions32[idx + 1] > this._maximum.y) {
  50270. this._maximum.y = this._positions32[idx + 1];
  50271. }
  50272. if (this._positions32[idx + 2] < this._minimum.z) {
  50273. this._minimum.z = this._positions32[idx + 2];
  50274. }
  50275. if (this._positions32[idx + 2] > this._maximum.z) {
  50276. this._maximum.z = this._positions32[idx + 2];
  50277. }
  50278. }
  50279. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50280. if (!this._computeParticleVertex) {
  50281. this._normal.x = this._fixedNormal32[idx];
  50282. this._normal.y = this._fixedNormal32[idx + 1];
  50283. this._normal.z = this._fixedNormal32[idx + 2];
  50284. 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]);
  50285. 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]);
  50286. 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]);
  50287. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50288. 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;
  50289. 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;
  50290. }
  50291. if (this._computeParticleColor) {
  50292. this._colors32[colidx] = this._particle.color.r;
  50293. this._colors32[colidx + 1] = this._particle.color.g;
  50294. this._colors32[colidx + 2] = this._particle.color.b;
  50295. this._colors32[colidx + 3] = this._particle.color.a;
  50296. }
  50297. if (this._computeParticleTexture) {
  50298. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50299. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50300. }
  50301. }
  50302. }
  50303. else {
  50304. for (pt = 0; pt < this._shape.length; pt++) {
  50305. idx = index + pt * 3;
  50306. colidx = colorIndex + pt * 4;
  50307. uvidx = uvIndex + pt * 2;
  50308. this._positions32[idx] = this._camera.position.x;
  50309. this._positions32[idx + 1] = this._camera.position.y;
  50310. this._positions32[idx + 2] = this._camera.position.z;
  50311. this._normals32[idx] = 0.0;
  50312. this._normals32[idx + 1] = 0.0;
  50313. this._normals32[idx + 2] = 0.0;
  50314. if (this._computeParticleColor) {
  50315. this._colors32[colidx] = this._particle.color.r;
  50316. this._colors32[colidx + 1] = this._particle.color.g;
  50317. this._colors32[colidx + 2] = this._particle.color.b;
  50318. this._colors32[colidx + 3] = this._particle.color.a;
  50319. }
  50320. if (this._computeParticleTexture) {
  50321. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50322. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50323. }
  50324. }
  50325. }
  50326. // if the particle intersections must be computed : update the bbInfo
  50327. if (this._particlesIntersect) {
  50328. var bInfo = this._particle._boundingInfo;
  50329. var bBox = bInfo.boundingBox;
  50330. var bSphere = bInfo.boundingSphere;
  50331. if (!this._bSphereOnly) {
  50332. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50333. for (var b = 0; b < bBox.vectors.length; b++) {
  50334. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50335. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50336. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50337. 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];
  50338. 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;
  50339. 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;
  50340. 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;
  50341. 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;
  50342. 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;
  50343. 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;
  50344. }
  50345. bBox._update(this.mesh._worldMatrix);
  50346. }
  50347. // place and scale the particle bouding sphere in the SPS local system, then update it
  50348. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50349. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50350. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50351. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50352. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50353. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50354. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50355. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50356. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50357. 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));
  50358. bSphere._update(this.mesh._worldMatrix);
  50359. }
  50360. // increment indexes for the next particle
  50361. index = idx + 3;
  50362. colorIndex = colidx + 4;
  50363. uvIndex = uvidx + 2;
  50364. }
  50365. // if the VBO must be updated
  50366. if (update) {
  50367. if (this._computeParticleColor) {
  50368. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50369. }
  50370. if (this._computeParticleTexture) {
  50371. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50372. }
  50373. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50374. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50375. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50376. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50377. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50378. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  50379. for (var i = 0; i < this._normals32.length; i++) {
  50380. this._fixedNormal32[i] = this._normals32[i];
  50381. }
  50382. }
  50383. if (!this.mesh.areNormalsFrozen) {
  50384. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50385. }
  50386. }
  50387. }
  50388. if (this._computeBoundingBox) {
  50389. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50390. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50391. }
  50392. this.afterUpdateParticles(start, end, update);
  50393. };
  50394. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50395. this._halfroll = this._roll * 0.5;
  50396. this._halfpitch = this._pitch * 0.5;
  50397. this._halfyaw = this._yaw * 0.5;
  50398. this._sinRoll = Math.sin(this._halfroll);
  50399. this._cosRoll = Math.cos(this._halfroll);
  50400. this._sinPitch = Math.sin(this._halfpitch);
  50401. this._cosPitch = Math.cos(this._halfpitch);
  50402. this._sinYaw = Math.sin(this._halfyaw);
  50403. this._cosYaw = Math.cos(this._halfyaw);
  50404. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  50405. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  50406. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  50407. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  50408. };
  50409. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50410. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50411. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50412. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50413. this._rotMatrix.m[3] = 0;
  50414. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50415. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50416. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50417. this._rotMatrix.m[7] = 0;
  50418. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50419. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50420. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50421. this._rotMatrix.m[11] = 0;
  50422. this._rotMatrix.m[12] = 0;
  50423. this._rotMatrix.m[13] = 0;
  50424. this._rotMatrix.m[14] = 0;
  50425. this._rotMatrix.m[15] = 1.0;
  50426. };
  50427. /**
  50428. * Disposes the SPS
  50429. */
  50430. SolidParticleSystem.prototype.dispose = function () {
  50431. this.mesh.dispose();
  50432. this.vars = null;
  50433. // drop references to internal big arrays for the GC
  50434. this._positions = null;
  50435. this._indices = null;
  50436. this._normals = null;
  50437. this._uvs = null;
  50438. this._colors = null;
  50439. this._positions32 = null;
  50440. this._normals32 = null;
  50441. this._fixedNormal32 = null;
  50442. this._uvs32 = null;
  50443. this._colors32 = null;
  50444. this.pickedParticles = null;
  50445. };
  50446. /**
  50447. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50448. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50449. */
  50450. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50451. if (!this._isVisibilityBoxLocked) {
  50452. this.mesh.refreshBoundingInfo();
  50453. }
  50454. };
  50455. /**
  50456. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50457. * @param size the size (float) of the visibility box
  50458. * note : this doesn't lock the SPS mesh bounding box.
  50459. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50460. */
  50461. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50462. var vis = size / 2;
  50463. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50464. };
  50465. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50466. // getter and setter
  50467. get: function () {
  50468. return this._alwaysVisible;
  50469. },
  50470. /**
  50471. * Sets the SPS as always visible or not
  50472. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50473. */
  50474. set: function (val) {
  50475. this._alwaysVisible = val;
  50476. this.mesh.alwaysSelectAsActiveMesh = val;
  50477. },
  50478. enumerable: true,
  50479. configurable: true
  50480. });
  50481. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50482. get: function () {
  50483. return this._isVisibilityBoxLocked;
  50484. },
  50485. /**
  50486. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50487. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50488. */
  50489. set: function (val) {
  50490. this._isVisibilityBoxLocked = val;
  50491. this.mesh.getBoundingInfo().isLocked = val;
  50492. },
  50493. enumerable: true,
  50494. configurable: true
  50495. });
  50496. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50497. // getters
  50498. get: function () {
  50499. return this._computeParticleRotation;
  50500. },
  50501. // Optimizer setters
  50502. /**
  50503. * Tells to `setParticles()` to compute the particle rotations or not.
  50504. * Default value : true. The SPS is faster when it's set to false.
  50505. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50506. */
  50507. set: function (val) {
  50508. this._computeParticleRotation = val;
  50509. },
  50510. enumerable: true,
  50511. configurable: true
  50512. });
  50513. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50514. get: function () {
  50515. return this._computeParticleColor;
  50516. },
  50517. /**
  50518. * Tells to `setParticles()` to compute the particle colors or not.
  50519. * Default value : true. The SPS is faster when it's set to false.
  50520. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50521. */
  50522. set: function (val) {
  50523. this._computeParticleColor = val;
  50524. },
  50525. enumerable: true,
  50526. configurable: true
  50527. });
  50528. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50529. get: function () {
  50530. return this._computeParticleTexture;
  50531. },
  50532. /**
  50533. * Tells to `setParticles()` to compute the particle textures or not.
  50534. * Default value : true. The SPS is faster when it's set to false.
  50535. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50536. */
  50537. set: function (val) {
  50538. this._computeParticleTexture = val;
  50539. },
  50540. enumerable: true,
  50541. configurable: true
  50542. });
  50543. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50544. get: function () {
  50545. return this._computeParticleVertex;
  50546. },
  50547. /**
  50548. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50549. * Default value : false. The SPS is faster when it's set to false.
  50550. * Note : the particle custom vertex positions aren't stored values.
  50551. */
  50552. set: function (val) {
  50553. this._computeParticleVertex = val;
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50559. get: function () {
  50560. return this._computeBoundingBox;
  50561. },
  50562. /**
  50563. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50564. */
  50565. set: function (val) {
  50566. this._computeBoundingBox = val;
  50567. },
  50568. enumerable: true,
  50569. configurable: true
  50570. });
  50571. // =======================================================================
  50572. // Particle behavior logic
  50573. // these following methods may be overwritten by the user to fit his needs
  50574. /**
  50575. * This function does nothing. It may be overwritten to set all the particle first values.
  50576. * The SPS doesn't call this function, you may have to call it by your own.
  50577. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50578. */
  50579. SolidParticleSystem.prototype.initParticles = function () {
  50580. };
  50581. /**
  50582. * This function does nothing. It may be overwritten to recycle a particle.
  50583. * The SPS doesn't call this function, you may have to call it by your own.
  50584. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50585. */
  50586. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50587. return particle;
  50588. };
  50589. /**
  50590. * Updates a particle : this function should be overwritten by the user.
  50591. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50592. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50593. * ex : just set a particle position or velocity and recycle conditions
  50594. */
  50595. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50596. return particle;
  50597. };
  50598. /**
  50599. * Updates a vertex of a particle : it can be overwritten by the user.
  50600. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50601. * @param particle the current particle
  50602. * @param vertex the current index of the current particle
  50603. * @param pt the index of the current vertex in the particle shape
  50604. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50605. * ex : just set a vertex particle position
  50606. */
  50607. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50608. return vertex;
  50609. };
  50610. /**
  50611. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50612. * This does nothing and may be overwritten by the user.
  50613. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50614. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50615. * @param update the boolean update value actually passed to setParticles()
  50616. */
  50617. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50618. };
  50619. /**
  50620. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50621. * This will be passed three parameters.
  50622. * This does nothing and may be overwritten by the user.
  50623. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50624. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50625. * @param update the boolean update value actually passed to setParticles()
  50626. */
  50627. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50628. };
  50629. return SolidParticleSystem;
  50630. }());
  50631. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50632. })(BABYLON || (BABYLON = {}));
  50633. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50634. var BABYLON;
  50635. (function (BABYLON) {
  50636. var Internals;
  50637. (function (Internals) {
  50638. var FileFaceOrientation = (function () {
  50639. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50640. this.name = name;
  50641. this.worldAxisForNormal = worldAxisForNormal;
  50642. this.worldAxisForFileX = worldAxisForFileX;
  50643. this.worldAxisForFileY = worldAxisForFileY;
  50644. }
  50645. return FileFaceOrientation;
  50646. }());
  50647. ;
  50648. /**
  50649. * Helper class dealing with the extraction of spherical polynomial dataArray
  50650. * from a cube map.
  50651. */
  50652. var CubeMapToSphericalPolynomialTools = (function () {
  50653. function CubeMapToSphericalPolynomialTools() {
  50654. }
  50655. /**
  50656. * Converts a cubemap to the according Spherical Polynomial data.
  50657. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50658. *
  50659. * @param cubeInfo The Cube map to extract the information from.
  50660. * @return The Spherical Polynomial data.
  50661. */
  50662. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50663. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50664. var totalSolidAngle = 0.0;
  50665. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50666. var du = 2.0 / cubeInfo.size;
  50667. var dv = du;
  50668. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50669. var minUV = du * 0.5 - 1.0;
  50670. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50671. var fileFace = this.FileFaces[faceIndex];
  50672. var dataArray = cubeInfo[fileFace.name];
  50673. var v = minUV;
  50674. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50675. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50676. // Because SP is still linear, so summation is fine in that basis.
  50677. for (var y = 0; y < cubeInfo.size; y++) {
  50678. var u = minUV;
  50679. for (var x = 0; x < cubeInfo.size; x++) {
  50680. // World direction (not normalised)
  50681. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50682. worldDirection.normalize();
  50683. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50684. if (1) {
  50685. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50686. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50687. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50688. var color = new BABYLON.Color3(r, g, b);
  50689. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50690. }
  50691. else {
  50692. if (faceIndex == 0) {
  50693. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50694. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50695. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50696. }
  50697. else if (faceIndex == 1) {
  50698. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50699. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50700. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50701. }
  50702. else if (faceIndex == 2) {
  50703. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50704. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50705. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50706. }
  50707. else if (faceIndex == 3) {
  50708. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50709. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50710. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50711. }
  50712. else if (faceIndex == 4) {
  50713. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50714. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50715. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50716. }
  50717. else if (faceIndex == 5) {
  50718. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50719. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50720. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50721. }
  50722. 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]);
  50723. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50724. }
  50725. totalSolidAngle += deltaSolidAngle;
  50726. u += du;
  50727. }
  50728. v += dv;
  50729. }
  50730. }
  50731. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50732. var correction = correctSolidAngle / totalSolidAngle;
  50733. sphericalHarmonics.scale(correction);
  50734. // Additionally scale by pi -- audit needed
  50735. sphericalHarmonics.scale(1.0 / Math.PI);
  50736. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50737. };
  50738. return CubeMapToSphericalPolynomialTools;
  50739. }());
  50740. CubeMapToSphericalPolynomialTools.FileFaces = [
  50741. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50742. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50743. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50744. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50745. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50746. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50747. ];
  50748. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50749. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50750. })(BABYLON || (BABYLON = {}));
  50751. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50752. var BABYLON;
  50753. (function (BABYLON) {
  50754. var Internals;
  50755. (function (Internals) {
  50756. /**
  50757. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50758. */
  50759. var PanoramaToCubeMapTools = (function () {
  50760. function PanoramaToCubeMapTools() {
  50761. }
  50762. /**
  50763. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50764. *
  50765. * @param float32Array The source data.
  50766. * @param inputWidth The width of the input panorama.
  50767. * @param inputhHeight The height of the input panorama.
  50768. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50769. * @return The cubemap data
  50770. */
  50771. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50772. if (!float32Array) {
  50773. throw "ConvertPanoramaToCubemap: input cannot be null";
  50774. }
  50775. if (float32Array.length != inputWidth * inputHeight * 3) {
  50776. throw "ConvertPanoramaToCubemap: input size is wrong";
  50777. }
  50778. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50779. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50780. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50781. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50782. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50783. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50784. return {
  50785. front: textureFront,
  50786. back: textureBack,
  50787. left: textureLeft,
  50788. right: textureRight,
  50789. up: textureUp,
  50790. down: textureDown,
  50791. size: size
  50792. };
  50793. };
  50794. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50795. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50796. var textureArray = new Float32Array(buffer);
  50797. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50798. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50799. var dy = 1 / texSize;
  50800. var fy = 0;
  50801. for (var y = 0; y < texSize; y++) {
  50802. var xv1 = faceData[0];
  50803. var xv2 = faceData[2];
  50804. for (var x = 0; x < texSize; x++) {
  50805. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50806. v.normalize();
  50807. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50808. // 3 channels per pixels
  50809. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50810. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50811. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50812. xv1 = xv1.add(rotDX1);
  50813. xv2 = xv2.add(rotDX2);
  50814. }
  50815. fy += dy;
  50816. }
  50817. return textureArray;
  50818. };
  50819. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50820. var theta = Math.atan2(vDir.z, vDir.x);
  50821. var phi = Math.acos(vDir.y);
  50822. while (theta < -Math.PI)
  50823. theta += 2 * Math.PI;
  50824. while (theta > Math.PI)
  50825. theta -= 2 * Math.PI;
  50826. var dx = theta / Math.PI;
  50827. var dy = phi / Math.PI;
  50828. // recenter.
  50829. dx = dx * 0.5 + 0.5;
  50830. var px = Math.round(dx * inputWidth);
  50831. if (px < 0)
  50832. px = 0;
  50833. else if (px >= inputWidth)
  50834. px = inputWidth - 1;
  50835. var py = Math.round(dy * inputHeight);
  50836. if (py < 0)
  50837. py = 0;
  50838. else if (py >= inputHeight)
  50839. py = inputHeight - 1;
  50840. var inputY = (inputHeight - py - 1);
  50841. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50842. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50843. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50844. return {
  50845. r: r,
  50846. g: g,
  50847. b: b
  50848. };
  50849. };
  50850. return PanoramaToCubeMapTools;
  50851. }());
  50852. PanoramaToCubeMapTools.FACE_FRONT = [
  50853. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50854. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50855. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50856. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50857. ];
  50858. PanoramaToCubeMapTools.FACE_BACK = [
  50859. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50860. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50861. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50862. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50863. ];
  50864. PanoramaToCubeMapTools.FACE_RIGHT = [
  50865. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50866. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50867. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50868. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50869. ];
  50870. PanoramaToCubeMapTools.FACE_LEFT = [
  50871. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50872. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50873. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50874. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50875. ];
  50876. PanoramaToCubeMapTools.FACE_DOWN = [
  50877. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50878. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50879. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50880. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50881. ];
  50882. PanoramaToCubeMapTools.FACE_UP = [
  50883. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50884. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50885. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50886. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50887. ];
  50888. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50889. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50890. })(BABYLON || (BABYLON = {}));
  50891. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50892. var BABYLON;
  50893. (function (BABYLON) {
  50894. var Internals;
  50895. (function (Internals) {
  50896. ;
  50897. /**
  50898. * This groups tools to convert HDR texture to native colors array.
  50899. */
  50900. var HDRTools = (function () {
  50901. function HDRTools() {
  50902. }
  50903. HDRTools.Ldexp = function (mantissa, exponent) {
  50904. if (exponent > 1023) {
  50905. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50906. }
  50907. if (exponent < -1074) {
  50908. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50909. }
  50910. return mantissa * Math.pow(2, exponent);
  50911. };
  50912. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50913. if (exponent > 0) {
  50914. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50915. float32array[index + 0] = red * exponent;
  50916. float32array[index + 1] = green * exponent;
  50917. float32array[index + 2] = blue * exponent;
  50918. }
  50919. else {
  50920. float32array[index + 0] = 0;
  50921. float32array[index + 1] = 0;
  50922. float32array[index + 2] = 0;
  50923. }
  50924. };
  50925. HDRTools.readStringLine = function (uint8array, startIndex) {
  50926. var line = "";
  50927. var character = "";
  50928. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50929. character = String.fromCharCode(uint8array[i]);
  50930. if (character == "\n") {
  50931. break;
  50932. }
  50933. line += character;
  50934. }
  50935. return line;
  50936. };
  50937. /**
  50938. * Reads header information from an RGBE texture stored in a native array.
  50939. * More information on this format are available here:
  50940. * https://en.wikipedia.org/wiki/RGBE_image_format
  50941. *
  50942. * @param uint8array The binary file stored in native array.
  50943. * @return The header information.
  50944. */
  50945. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50946. var height = 0;
  50947. var width = 0;
  50948. var line = this.readStringLine(uint8array, 0);
  50949. if (line[0] != '#' || line[1] != '?') {
  50950. throw "Bad HDR Format.";
  50951. }
  50952. var endOfHeader = false;
  50953. var findFormat = false;
  50954. var lineIndex = 0;
  50955. do {
  50956. lineIndex += (line.length + 1);
  50957. line = this.readStringLine(uint8array, lineIndex);
  50958. if (line == "FORMAT=32-bit_rle_rgbe") {
  50959. findFormat = true;
  50960. }
  50961. else if (line.length == 0) {
  50962. endOfHeader = true;
  50963. }
  50964. } while (!endOfHeader);
  50965. if (!findFormat) {
  50966. throw "HDR Bad header format, unsupported FORMAT";
  50967. }
  50968. lineIndex += (line.length + 1);
  50969. line = this.readStringLine(uint8array, lineIndex);
  50970. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50971. var match = sizeRegexp.exec(line);
  50972. // TODO. Support +Y and -X if needed.
  50973. if (match.length < 3) {
  50974. throw "HDR Bad header format, no size";
  50975. }
  50976. width = parseInt(match[2]);
  50977. height = parseInt(match[1]);
  50978. if (width < 8 || width > 0x7fff) {
  50979. throw "HDR Bad header format, unsupported size";
  50980. }
  50981. lineIndex += (line.length + 1);
  50982. return {
  50983. height: height,
  50984. width: width,
  50985. dataPosition: lineIndex
  50986. };
  50987. };
  50988. /**
  50989. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50990. * This RGBE texture needs to store the information as a panorama.
  50991. *
  50992. * More information on this format are available here:
  50993. * https://en.wikipedia.org/wiki/RGBE_image_format
  50994. *
  50995. * @param buffer The binary file stored in an array buffer.
  50996. * @param size The expected size of the extracted cubemap.
  50997. * @return The Cube Map information.
  50998. */
  50999. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51000. var uint8array = new Uint8Array(buffer);
  51001. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51002. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51003. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51004. return cubeMapData;
  51005. };
  51006. /**
  51007. * Returns the pixels data extracted from an RGBE texture.
  51008. * This pixels will be stored left to right up to down in the R G B order in one array.
  51009. *
  51010. * More information on this format are available here:
  51011. * https://en.wikipedia.org/wiki/RGBE_image_format
  51012. *
  51013. * @param uint8array The binary file stored in an array buffer.
  51014. * @param hdrInfo The header information of the file.
  51015. * @return The pixels data in RGB right to left up to down order.
  51016. */
  51017. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51018. // Keep for multi format supports.
  51019. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51020. };
  51021. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51022. var num_scanlines = hdrInfo.height;
  51023. var scanline_width = hdrInfo.width;
  51024. var a, b, c, d, count;
  51025. var dataIndex = hdrInfo.dataPosition;
  51026. var index = 0, endIndex = 0, i = 0;
  51027. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51028. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51029. // 3 channels of 4 bytes per pixel in float.
  51030. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51031. var resultArray = new Float32Array(resultBuffer);
  51032. // read in each successive scanline
  51033. while (num_scanlines > 0) {
  51034. a = uint8array[dataIndex++];
  51035. b = uint8array[dataIndex++];
  51036. c = uint8array[dataIndex++];
  51037. d = uint8array[dataIndex++];
  51038. if (a != 2 || b != 2 || (c & 0x80)) {
  51039. // this file is not run length encoded
  51040. throw "HDR Bad header format, not RLE";
  51041. }
  51042. if (((c << 8) | d) != scanline_width) {
  51043. throw "HDR Bad header format, wrong scan line width";
  51044. }
  51045. index = 0;
  51046. // read each of the four channels for the scanline into the buffer
  51047. for (i = 0; i < 4; i++) {
  51048. endIndex = (i + 1) * scanline_width;
  51049. while (index < endIndex) {
  51050. a = uint8array[dataIndex++];
  51051. b = uint8array[dataIndex++];
  51052. if (a > 128) {
  51053. // a run of the same value
  51054. count = a - 128;
  51055. if ((count == 0) || (count > endIndex - index)) {
  51056. throw "HDR Bad Format, bad scanline data (run)";
  51057. }
  51058. while (count-- > 0) {
  51059. scanLineArray[index++] = b;
  51060. }
  51061. }
  51062. else {
  51063. // a non-run
  51064. count = a;
  51065. if ((count == 0) || (count > endIndex - index)) {
  51066. throw "HDR Bad Format, bad scanline data (non-run)";
  51067. }
  51068. scanLineArray[index++] = b;
  51069. if (--count > 0) {
  51070. for (var j = 0; j < count; j++) {
  51071. scanLineArray[index++] = uint8array[dataIndex++];
  51072. }
  51073. }
  51074. }
  51075. }
  51076. }
  51077. // now convert data from buffer into floats
  51078. for (i = 0; i < scanline_width; i++) {
  51079. a = scanLineArray[i];
  51080. b = scanLineArray[i + scanline_width];
  51081. c = scanLineArray[i + 2 * scanline_width];
  51082. d = scanLineArray[i + 3 * scanline_width];
  51083. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51084. }
  51085. num_scanlines--;
  51086. }
  51087. return resultArray;
  51088. };
  51089. return HDRTools;
  51090. }());
  51091. Internals.HDRTools = HDRTools;
  51092. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51093. })(BABYLON || (BABYLON = {}));
  51094. //# sourceMappingURL=babylon.tools.hdr.js.map
  51095. //_______________________________________________________________
  51096. // Extracted from CubeMapGen:
  51097. // https://code.google.com/archive/p/cubemapgen/
  51098. //
  51099. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51100. //_______________________________________________________________
  51101. var BABYLON;
  51102. (function (BABYLON) {
  51103. var Internals;
  51104. (function (Internals) {
  51105. /**
  51106. * The bounding box information used during the conversion process.
  51107. */
  51108. var CMGBoundinBox = (function () {
  51109. function CMGBoundinBox() {
  51110. this.min = new BABYLON.Vector3(0, 0, 0);
  51111. this.max = new BABYLON.Vector3(0, 0, 0);
  51112. this.clear();
  51113. }
  51114. CMGBoundinBox.prototype.clear = function () {
  51115. this.min.x = CMGBoundinBox.MAX;
  51116. this.min.y = CMGBoundinBox.MAX;
  51117. this.min.z = CMGBoundinBox.MAX;
  51118. this.max.x = CMGBoundinBox.MIN;
  51119. this.max.y = CMGBoundinBox.MIN;
  51120. this.max.z = CMGBoundinBox.MIN;
  51121. };
  51122. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51123. this.min.x = Math.min(this.min.x, x);
  51124. this.min.y = Math.min(this.min.y, y);
  51125. this.min.z = Math.min(this.min.z, z);
  51126. this.max.x = Math.max(this.max.x, x);
  51127. this.max.y = Math.max(this.max.y, y);
  51128. this.max.z = Math.max(this.max.z, z);
  51129. };
  51130. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51131. this.min.x = Math.max(this.min.x, x);
  51132. this.min.y = Math.max(this.min.y, y);
  51133. this.min.z = Math.max(this.min.z, z);
  51134. };
  51135. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51136. this.max.x = Math.min(this.max.x, x);
  51137. this.max.y = Math.min(this.max.y, y);
  51138. this.max.z = Math.min(this.max.z, z);
  51139. };
  51140. CMGBoundinBox.prototype.empty = function () {
  51141. if ((this.min.x > this.max.y) ||
  51142. (this.min.y > this.max.y) ||
  51143. (this.min.z > this.max.y)) {
  51144. return true;
  51145. }
  51146. else {
  51147. return false;
  51148. }
  51149. };
  51150. return CMGBoundinBox;
  51151. }());
  51152. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51153. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51154. /**
  51155. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51156. * required by the glossinees of a material.
  51157. *
  51158. * This only supports the cosine drop power as well as Warp fixup generation method.
  51159. *
  51160. * This is using the process from CubeMapGen described here:
  51161. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51162. */
  51163. var PMREMGenerator = (function () {
  51164. /**
  51165. * Constructor of the generator.
  51166. *
  51167. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51168. * @param inputSize The size of the cubemap faces
  51169. * @param outputSize The size of the output cubemap faces
  51170. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51171. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51172. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51173. * @param specularPower The max specular level of the desired cubemap
  51174. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51175. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51176. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51177. */
  51178. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51179. this.input = input;
  51180. this.inputSize = inputSize;
  51181. this.outputSize = outputSize;
  51182. this.maxNumMipLevels = maxNumMipLevels;
  51183. this.numChannels = numChannels;
  51184. this.isFloat = isFloat;
  51185. this.specularPower = specularPower;
  51186. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51187. this.excludeBase = excludeBase;
  51188. this.fixup = fixup;
  51189. this._outputSurface = [];
  51190. this._numMipLevels = 0;
  51191. }
  51192. /**
  51193. * Launches the filter process and return the result.
  51194. *
  51195. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51196. */
  51197. PMREMGenerator.prototype.filterCubeMap = function () {
  51198. // Init cubemap processor
  51199. this.init();
  51200. // Filters the cubemap
  51201. this.filterCubeMapMipChain();
  51202. // Returns the filtered mips.
  51203. return this._outputSurface;
  51204. };
  51205. PMREMGenerator.prototype.init = function () {
  51206. var i;
  51207. var j;
  51208. var mipLevelSize;
  51209. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51210. if (this.maxNumMipLevels == 0) {
  51211. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51212. }
  51213. //first miplevel size
  51214. mipLevelSize = this.outputSize;
  51215. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51216. for (j = 0; j < this.maxNumMipLevels; j++) {
  51217. this._outputSurface.length++;
  51218. this._outputSurface[j] = [];
  51219. //Iterate over faces for output images
  51220. for (i = 0; i < 6; i++) {
  51221. this._outputSurface[j].length++;
  51222. // Initializes a new array for the output.
  51223. if (this.isFloat) {
  51224. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51225. }
  51226. else {
  51227. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51228. }
  51229. }
  51230. //next mip level is half size
  51231. mipLevelSize >>= 1;
  51232. this._numMipLevels++;
  51233. //terminate if mip chain becomes too small
  51234. if (mipLevelSize == 0) {
  51235. this.maxNumMipLevels = j;
  51236. return;
  51237. }
  51238. }
  51239. };
  51240. //--------------------------------------------------------------------------------------
  51241. //Cube map filtering and mip chain generation.
  51242. // the cube map filtereing is specified using a number of parameters:
  51243. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51244. // indicates the region of the hemisphere to filter over for each tap.
  51245. //
  51246. // Note that the top mip level is also a filtered version of the original input images
  51247. // as well in order to create mip chains for diffuse environment illumination.
  51248. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51249. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51250. //
  51251. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51252. // is a_InitialMipAngle
  51253. //
  51254. // The angle for the subsequent levels of the mip chain are specified by their parents
  51255. // filtering angle and a per-level scale and bias
  51256. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51257. //
  51258. //--------------------------------------------------------------------------------------
  51259. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51260. // First, take count of the lighting model to modify SpecularPower
  51261. // 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;
  51262. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51263. //Cone angle start (for generating subsequent mip levels)
  51264. var currentSpecularPower = this.specularPower;
  51265. //Build filter lookup tables based on the source miplevel size
  51266. this.precomputeFilterLookupTables(this.inputSize);
  51267. // Note that we need to filter the first level before generating mipmap
  51268. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51269. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51270. // TODO : Write a function to copy and scale the base mipmap in output
  51271. // I am just lazy here and just put a high specular power value, and do some if.
  51272. if (this.excludeBase && (levelIndex == 0)) {
  51273. // 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).
  51274. currentSpecularPower = 100000.0;
  51275. }
  51276. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51277. var srcCubeImage = this.input;
  51278. var dstCubeImage = this._outputSurface[levelIndex];
  51279. var dstSize = this.outputSize >> levelIndex;
  51280. // Compute required angle.
  51281. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51282. // filter cube surfaces
  51283. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51284. // fix seams
  51285. if (this.fixup) {
  51286. this.fixupCubeEdges(dstCubeImage, dstSize);
  51287. }
  51288. // Decrease the specular power to generate the mipmap chain
  51289. // TODO : Use another method for Exclude (see first comment at start of the function
  51290. if (this.excludeBase && (levelIndex == 0)) {
  51291. currentSpecularPower = this.specularPower;
  51292. }
  51293. currentSpecularPower *= this.cosinePowerDropPerMip;
  51294. }
  51295. };
  51296. //--------------------------------------------------------------------------------------
  51297. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51298. // It allow to optimize the texel to access base on the specular power.
  51299. //--------------------------------------------------------------------------------------
  51300. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51301. // We want to find the alpha such that:
  51302. // cos(alpha)^cosinePower = epsilon
  51303. // That's: acos(epsilon^(1/cosinePower))
  51304. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51305. var angle = 180.0;
  51306. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51307. angle *= 180.0 / Math.PI; // Convert to degree
  51308. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51309. return angle;
  51310. };
  51311. //--------------------------------------------------------------------------------------
  51312. //Builds the following lookup tables prior to filtering:
  51313. // -normalizer cube map
  51314. // -tap weight lookup table
  51315. //
  51316. //--------------------------------------------------------------------------------------
  51317. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51318. var srcTexelAngle;
  51319. var iCubeFace;
  51320. //clear pre-existing normalizer cube map
  51321. this._normCubeMap = [];
  51322. //Normalized vectors per cubeface and per-texel solid angle
  51323. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51324. };
  51325. //--------------------------------------------------------------------------------------
  51326. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51327. //
  51328. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51329. //
  51330. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51331. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51332. // below
  51333. //--------------------------------------------------------------------------------------
  51334. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51335. var iCubeFace;
  51336. var u;
  51337. var v;
  51338. //iterate over cube faces
  51339. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51340. //First three channels for norm cube, and last channel for solid angle
  51341. this._normCubeMap.push(new Float32Array(size * size * 4));
  51342. //fast texture walk, build normalizer cube map
  51343. var facesData = this.input[iCubeFace];
  51344. for (v = 0; v < size; v++) {
  51345. for (u = 0; u < size; u++) {
  51346. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51347. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51348. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51349. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51350. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51351. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51352. }
  51353. }
  51354. }
  51355. };
  51356. //--------------------------------------------------------------------------------------
  51357. // Convert cubemap face texel coordinates and face idx to 3D vector
  51358. // note the U and V coords are integer coords and range from 0 to size-1
  51359. // this routine can be used to generate a normalizer cube map
  51360. //--------------------------------------------------------------------------------------
  51361. // SL BEGIN
  51362. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51363. var nvcU;
  51364. var nvcV;
  51365. var tempVec;
  51366. // Change from original AMD code
  51367. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51368. // + 0.5f is for texel center addressing
  51369. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51370. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51371. // warp fixup
  51372. if (fixup && size > 1) {
  51373. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51374. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51375. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51376. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51377. }
  51378. // Get current vector
  51379. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51380. // U contribution
  51381. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51382. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51383. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51384. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51385. // V contribution and Sum
  51386. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51387. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51388. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51389. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51390. //add face axis
  51391. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51392. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51393. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51394. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51395. //normalize vector
  51396. PMREMGenerator._vectorTemp.normalize();
  51397. return PMREMGenerator._vectorTemp;
  51398. };
  51399. //--------------------------------------------------------------------------------------
  51400. // Convert 3D vector to cubemap face texel coordinates and face idx
  51401. // note the U and V coords are integer coords and range from 0 to size-1
  51402. // this routine can be used to generate a normalizer cube map
  51403. //
  51404. // returns face IDX and texel coords
  51405. //--------------------------------------------------------------------------------------
  51406. // SL BEGIN
  51407. /*
  51408. Mapping Texture Coordinates to Cube Map Faces
  51409. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51410. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51411. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51412. map arrangement in Pixar's RenderMan package.
  51413. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51414. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51415. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51416. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51417. the major axis direction). The target column in the table below explains how the major axis direction
  51418. maps to the 2D image of a particular cube map target.
  51419. major axis
  51420. direction target sc tc ma
  51421. ---------- --------------------------------- --- --- ---
  51422. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51423. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51424. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51425. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51426. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51427. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51428. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51429. an updated (s,t) is calculated as follows
  51430. s = ( sc/|ma| + 1 ) / 2
  51431. t = ( tc/|ma| + 1 ) / 2
  51432. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51433. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51434. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51435. */
  51436. // Note this method return U and V in range from 0 to size-1
  51437. // SL END
  51438. // Store the information in vector3 for convenience (faceindex, u, v)
  51439. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51440. var maxCoord;
  51441. var faceIdx;
  51442. //absolute value 3
  51443. var absX = Math.abs(x);
  51444. var absY = Math.abs(y);
  51445. var absZ = Math.abs(z);
  51446. if (absX >= absY && absX >= absZ) {
  51447. maxCoord = absX;
  51448. if (x >= 0) {
  51449. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51450. }
  51451. else {
  51452. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51453. }
  51454. }
  51455. else if (absY >= absX && absY >= absZ) {
  51456. maxCoord = absY;
  51457. if (y >= 0) {
  51458. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51459. }
  51460. else {
  51461. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51462. }
  51463. }
  51464. else {
  51465. maxCoord = absZ;
  51466. if (z >= 0) {
  51467. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51468. }
  51469. else {
  51470. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51471. }
  51472. }
  51473. //divide through by max coord so face vector lies on cube face
  51474. var scale = 1 / maxCoord;
  51475. x *= scale;
  51476. y *= scale;
  51477. z *= scale;
  51478. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51479. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51480. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51481. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51482. // Modify original AMD code to return value from 0 to Size - 1
  51483. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51484. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51485. PMREMGenerator._vectorTemp.x = faceIdx;
  51486. PMREMGenerator._vectorTemp.y = u;
  51487. PMREMGenerator._vectorTemp.z = v;
  51488. return PMREMGenerator._vectorTemp;
  51489. };
  51490. //--------------------------------------------------------------------------------------
  51491. //Original code from Ignacio CastaÒo
  51492. // This formula is from Manne ÷hrstrˆm's thesis.
  51493. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51494. // cube face and return the area of the projection of that portion on the
  51495. // surface of the sphere.
  51496. //--------------------------------------------------------------------------------------
  51497. PMREMGenerator.prototype.areaElement = function (x, y) {
  51498. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51499. };
  51500. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51501. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51502. // (+ 0.5f is for texel center addressing)
  51503. u = (2.0 * (u + 0.5) / size) - 1.0;
  51504. v = (2.0 * (v + 0.5) / size) - 1.0;
  51505. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51506. var invResolution = 1.0 / size;
  51507. // U and V are the -1..1 texture coordinate on the current face.
  51508. // Get projected area for this texel
  51509. var x0 = u - invResolution;
  51510. var y0 = v - invResolution;
  51511. var x1 = u + invResolution;
  51512. var y1 = v + invResolution;
  51513. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51514. return solidAngle;
  51515. };
  51516. //--------------------------------------------------------------------------------------
  51517. //The key to the speed of these filtering routines is to quickly define a per-face
  51518. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51519. // Later these pixels are selectively processed based on their dot products to see if
  51520. // they reside within the filtering cone.
  51521. //
  51522. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51523. // of the number of texels needed to be covered in width and height order to filter the
  51524. // region. the bounding box for the center taps face is defined first, and if the
  51525. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51526. // defined next
  51527. //--------------------------------------------------------------------------------------
  51528. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51529. // note that pixels within these regions may be rejected
  51530. // based on the anlge
  51531. var iCubeFace;
  51532. var u;
  51533. var v;
  51534. // bounding box per face to specify region to process
  51535. var filterExtents = [];
  51536. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51537. filterExtents.push(new CMGBoundinBox());
  51538. }
  51539. // min angle a src texel can cover (in degrees)
  51540. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51541. // angle about center tap to define filter cone
  51542. // filter angle is 1/2 the cone angle
  51543. var filterAngle = filterConeAngle / 2.0;
  51544. //ensure filter angle is larger than a texel
  51545. if (filterAngle < srcTexelAngle) {
  51546. filterAngle = srcTexelAngle;
  51547. }
  51548. //ensure filter cone is always smaller than the hemisphere
  51549. if (filterAngle > 90.0) {
  51550. filterAngle = 90.0;
  51551. }
  51552. // the maximum number of texels in 1D the filter cone angle will cover
  51553. // used to determine bounding box size for filter extents
  51554. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51555. // ensure conservative region always covers at least one texel
  51556. if (filterSize < 1) {
  51557. filterSize = 1;
  51558. }
  51559. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51560. // reside within the cone angle
  51561. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51562. // process required faces
  51563. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51564. //iterate over dst cube map face texel
  51565. for (v = 0; v < dstSize; v++) {
  51566. for (u = 0; u < dstSize; u++) {
  51567. //get center tap direction
  51568. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51569. //clear old per-face filter extents
  51570. this.clearFilterExtents(filterExtents);
  51571. //define per-face filter extents
  51572. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51573. //perform filtering of src faces using filter extents
  51574. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51575. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51576. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51577. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51578. }
  51579. }
  51580. }
  51581. };
  51582. //--------------------------------------------------------------------------------------
  51583. //Clear filter extents for the 6 cube map faces
  51584. //--------------------------------------------------------------------------------------
  51585. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51586. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51587. filterExtents[iCubeFaces].clear();
  51588. }
  51589. };
  51590. //--------------------------------------------------------------------------------------
  51591. //Define per-face bounding box filter extents
  51592. //
  51593. // These define conservative texel regions in each of the faces the filter can possibly
  51594. // process. When the pixels in the regions are actually processed, the dot product
  51595. // between the tap vector and the center tap vector is used to determine the weight of
  51596. // the tap and whether or not the tap is within the cone.
  51597. //
  51598. //--------------------------------------------------------------------------------------
  51599. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51600. //neighboring face and bleed over amount, and width of BBOX for
  51601. // left, right, top, and bottom edges of this face
  51602. var bleedOverAmount = [0, 0, 0, 0];
  51603. var bleedOverBBoxMin = [0, 0, 0, 0];
  51604. var bleedOverBBoxMax = [0, 0, 0, 0];
  51605. var neighborFace;
  51606. var neighborEdge;
  51607. var oppositeFaceIdx;
  51608. //get face idx, and u, v info from center tap dir
  51609. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51610. var faceIdx = result.x;
  51611. var u = result.y;
  51612. var v = result.z;
  51613. //define bbox size within face
  51614. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51615. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51616. filterExtents[faceIdx].clampMin(0, 0, 0);
  51617. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51618. //u and v extent in face corresponding to center tap
  51619. var minU = filterExtents[faceIdx].min.x;
  51620. var minV = filterExtents[faceIdx].min.y;
  51621. var maxU = filterExtents[faceIdx].max.x;
  51622. var maxV = filterExtents[faceIdx].max.y;
  51623. //bleed over amounts for face across u=0 edge (left)
  51624. bleedOverAmount[0] = (bboxSize - u);
  51625. bleedOverBBoxMin[0] = minV;
  51626. bleedOverBBoxMax[0] = maxV;
  51627. //bleed over amounts for face across u=1 edge (right)
  51628. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51629. bleedOverBBoxMin[1] = minV;
  51630. bleedOverBBoxMax[1] = maxV;
  51631. //bleed over to face across v=0 edge (up)
  51632. bleedOverAmount[2] = (bboxSize - v);
  51633. bleedOverBBoxMin[2] = minU;
  51634. bleedOverBBoxMax[2] = maxU;
  51635. //bleed over to face across v=1 edge (down)
  51636. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51637. bleedOverBBoxMin[3] = minU;
  51638. bleedOverBBoxMax[3] = maxU;
  51639. //compute bleed over regions in neighboring faces
  51640. for (var i = 0; i < 4; i++) {
  51641. if (bleedOverAmount[i] > 0) {
  51642. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51643. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51644. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51645. // be flipped: the cases are
  51646. // if a left edge mates with a left or bottom edge on the neighbor
  51647. // if a top edge mates with a top or right edge on the neighbor
  51648. // if a right edge mates with a right or top edge on the neighbor
  51649. // if a bottom edge mates with a bottom or left edge on the neighbor
  51650. //Seeing as the edges are enumerated as follows
  51651. // left =0
  51652. // right =1
  51653. // top =2
  51654. // bottom =3
  51655. //
  51656. // so if the edge enums are the same, or the sum of the enums == 3,
  51657. // the bbox needs to be flipped
  51658. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51659. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51660. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51661. }
  51662. //The way the bounding box is extended onto the neighboring face
  51663. // depends on which edge of neighboring face abuts with this one
  51664. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51665. case PMREMGenerator.CP_EDGE_LEFT:
  51666. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51667. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51668. break;
  51669. case PMREMGenerator.CP_EDGE_RIGHT:
  51670. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51671. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51672. break;
  51673. case PMREMGenerator.CP_EDGE_TOP:
  51674. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51675. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51676. break;
  51677. case PMREMGenerator.CP_EDGE_BOTTOM:
  51678. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51679. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51680. break;
  51681. }
  51682. //clamp filter extents in non-center tap faces to remain within surface
  51683. filterExtents[neighborFace].clampMin(0, 0, 0);
  51684. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51685. }
  51686. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51687. // from the center tap face, then process the opposite face entirely for now.
  51688. //Note that the cases in which this happens, what usually happens is that
  51689. // more than one edge bleeds onto the opposite face, and the bounding box
  51690. // encompasses the entire cube map face.
  51691. if (bleedOverAmount[i] > srcSize) {
  51692. //determine opposite face
  51693. switch (faceIdx) {
  51694. case PMREMGenerator.CP_FACE_X_POS:
  51695. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51696. break;
  51697. case PMREMGenerator.CP_FACE_X_NEG:
  51698. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51699. break;
  51700. case PMREMGenerator.CP_FACE_Y_POS:
  51701. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51702. break;
  51703. case PMREMGenerator.CP_FACE_Y_NEG:
  51704. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51705. break;
  51706. case PMREMGenerator.CP_FACE_Z_POS:
  51707. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51708. break;
  51709. case PMREMGenerator.CP_FACE_Z_NEG:
  51710. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51711. break;
  51712. default:
  51713. break;
  51714. }
  51715. //just encompass entire face for now
  51716. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51717. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51718. }
  51719. }
  51720. };
  51721. //--------------------------------------------------------------------------------------
  51722. //ProcessFilterExtents
  51723. // Process bounding box in each cube face
  51724. //
  51725. //--------------------------------------------------------------------------------------
  51726. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51727. //accumulators are 64-bit floats in order to have the precision needed
  51728. // over a summation of a large number of pixels
  51729. var dstAccum = [0, 0, 0, 0];
  51730. var weightAccum = 0;
  51731. var k = 0;
  51732. var nSrcChannels = this.numChannels;
  51733. // norm cube map and srcCubeMap have same face width
  51734. var faceWidth = srcSize;
  51735. //amount to add to pointer to move to next scanline in images
  51736. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51737. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51738. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51739. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51740. // iterate over cubefaces
  51741. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51742. //if bbox is non empty
  51743. if (!filterExtents[iFaceIdx].empty()) {
  51744. var uStart = filterExtents[iFaceIdx].min.x;
  51745. var vStart = filterExtents[iFaceIdx].min.y;
  51746. var uEnd = filterExtents[iFaceIdx].max.x;
  51747. var vEnd = filterExtents[iFaceIdx].max.y;
  51748. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51749. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51750. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51751. for (var v = vStart; v <= vEnd; v++) {
  51752. var normCubeRowWalk = 0;
  51753. var srcCubeRowWalk = 0;
  51754. for (var u = uStart; u <= uEnd; u++) {
  51755. //pointer to direction in cube map associated with texel
  51756. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51757. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51758. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51759. //check dot product to see if texel is within cone
  51760. var tapDotProd = texelVectX * centerTapDir.x +
  51761. texelVectY * centerTapDir.y +
  51762. texelVectZ * centerTapDir.z;
  51763. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51764. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51765. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51766. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51767. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51768. // so just adding one to specularpower do the trick.
  51769. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51770. //iterate over channels
  51771. for (k = 0; k < nSrcChannels; k++) {
  51772. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51773. srcCubeRowWalk++;
  51774. }
  51775. weightAccum += weight; //accumulate weight
  51776. }
  51777. else {
  51778. //step across source pixel
  51779. srcCubeRowWalk += nSrcChannels;
  51780. }
  51781. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51782. }
  51783. startIndexNormCubeMap += normCubePitch;
  51784. startIndexSrcCubeMap += srcCubePitch;
  51785. }
  51786. }
  51787. }
  51788. //divide through by weights if weight is non zero
  51789. if (weightAccum != 0.0) {
  51790. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51791. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51792. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51793. if (this.numChannels > 3) {
  51794. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51795. }
  51796. }
  51797. else {
  51798. // otherwise sample nearest
  51799. // get face idx and u, v texel coordinate in face
  51800. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51801. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51802. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51803. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51804. if (this.numChannels > 3) {
  51805. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51806. }
  51807. }
  51808. return PMREMGenerator._vectorTemp;
  51809. };
  51810. //--------------------------------------------------------------------------------------
  51811. // Fixup cube edges
  51812. //
  51813. // average texels on cube map faces across the edges
  51814. // WARP/BENT Method Only.
  51815. //--------------------------------------------------------------------------------------
  51816. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51817. var k;
  51818. var j;
  51819. var i;
  51820. var iFace;
  51821. var iCorner = 0;
  51822. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51823. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51824. // note that if functionality to filter across the three texels for each corner, then
  51825. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51826. var cornerPtr = [
  51827. [[], [], []],
  51828. [[], [], []],
  51829. [[], [], []],
  51830. [[], [], []],
  51831. [[], [], []],
  51832. [[], [], []],
  51833. [[], [], []],
  51834. [[], [], []]
  51835. ];
  51836. //if there is no fixup, or fixup width = 0, do nothing
  51837. if (cubeMapSize < 1) {
  51838. return;
  51839. }
  51840. //special case 1x1 cubemap, average face colors
  51841. if (cubeMapSize == 1) {
  51842. //iterate over channels
  51843. for (k = 0; k < this.numChannels; k++) {
  51844. var accum = 0.0;
  51845. //iterate over faces to accumulate face colors
  51846. for (iFace = 0; iFace < 6; iFace++) {
  51847. accum += cubeMap[iFace][k];
  51848. }
  51849. //compute average over 6 face colors
  51850. accum /= 6.0;
  51851. //iterate over faces to distribute face colors
  51852. for (iFace = 0; iFace < 6; iFace++) {
  51853. cubeMap[iFace][k] = accum;
  51854. }
  51855. }
  51856. return;
  51857. }
  51858. //iterate over faces to collect list of corner texel pointers
  51859. for (iFace = 0; iFace < 6; iFace++) {
  51860. //the 4 corner pointers for this face
  51861. faceCornerStartIndicies[0] = [iFace, 0];
  51862. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51863. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51864. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51865. //iterate over face corners to collect cube corner pointers
  51866. for (iCorner = 0; iCorner < 4; iCorner++) {
  51867. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51868. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51869. cornerNumPtrs[corner]++;
  51870. }
  51871. }
  51872. //iterate over corners to average across corner tap values
  51873. for (iCorner = 0; iCorner < 8; iCorner++) {
  51874. for (k = 0; k < this.numChannels; k++) {
  51875. var cornerTapAccum = 0.0;
  51876. //iterate over corner texels and average results
  51877. for (i = 0; i < 3; i++) {
  51878. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51879. }
  51880. //divide by 3 to compute average of corner tap values
  51881. cornerTapAccum *= (1.0 / 3.0);
  51882. //iterate over corner texels and average results
  51883. for (i = 0; i < 3; i++) {
  51884. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51885. }
  51886. }
  51887. }
  51888. //iterate over the twelve edges of the cube to average across edges
  51889. for (i = 0; i < 12; i++) {
  51890. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51891. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51892. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51893. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51894. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51895. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51896. var edgeWalk = 0;
  51897. var neighborEdgeWalk = 0;
  51898. //Determine walking pointers based on edge type
  51899. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51900. switch (edge) {
  51901. case PMREMGenerator.CP_EDGE_LEFT:
  51902. // no change to faceEdgeStartPtr
  51903. edgeWalk = this.numChannels * cubeMapSize;
  51904. break;
  51905. case PMREMGenerator.CP_EDGE_RIGHT:
  51906. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51907. edgeWalk = this.numChannels * cubeMapSize;
  51908. break;
  51909. case PMREMGenerator.CP_EDGE_TOP:
  51910. // no change to faceEdgeStartPtr
  51911. edgeWalk = this.numChannels;
  51912. break;
  51913. case PMREMGenerator.CP_EDGE_BOTTOM:
  51914. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51915. edgeWalk = this.numChannels;
  51916. break;
  51917. }
  51918. //For certain types of edge abutments, the neighbor edge walk needs to
  51919. // be flipped: the cases are
  51920. // if a left edge mates with a left or bottom edge on the neighbor
  51921. // if a top edge mates with a top or right edge on the neighbor
  51922. // if a right edge mates with a right or top edge on the neighbor
  51923. // if a bottom edge mates with a bottom or left edge on the neighbor
  51924. //Seeing as the edges are enumerated as follows
  51925. // left =0
  51926. // right =1
  51927. // top =2
  51928. // bottom =3
  51929. //
  51930. //If the edge enums are the same, or the sum of the enums == 3,
  51931. // the neighbor edge walk needs to be flipped
  51932. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51933. switch (neighborEdge) {
  51934. case PMREMGenerator.CP_EDGE_LEFT:
  51935. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51936. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51937. break;
  51938. case PMREMGenerator.CP_EDGE_RIGHT:
  51939. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51940. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51941. break;
  51942. case PMREMGenerator.CP_EDGE_TOP:
  51943. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51944. neighborEdgeWalk = -this.numChannels;
  51945. break;
  51946. case PMREMGenerator.CP_EDGE_BOTTOM:
  51947. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51948. neighborEdgeWalk = -this.numChannels;
  51949. break;
  51950. }
  51951. }
  51952. else {
  51953. //swapped direction neighbor edge walk
  51954. switch (neighborEdge) {
  51955. case PMREMGenerator.CP_EDGE_LEFT:
  51956. //no change to neighborEdgeStartPtr for this case since it points
  51957. // to the upper left corner already
  51958. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51959. break;
  51960. case PMREMGenerator.CP_EDGE_RIGHT:
  51961. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51962. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51963. break;
  51964. case PMREMGenerator.CP_EDGE_TOP:
  51965. //no change to neighborEdgeStartPtr for this case since it points
  51966. // to the upper left corner already
  51967. neighborEdgeWalk = this.numChannels;
  51968. break;
  51969. case PMREMGenerator.CP_EDGE_BOTTOM:
  51970. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51971. neighborEdgeWalk = this.numChannels;
  51972. break;
  51973. }
  51974. }
  51975. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51976. //nearby neighborhood
  51977. //step ahead one texel on edge
  51978. edgeStartIndex += edgeWalk;
  51979. neighborEdgeStartIndex += neighborEdgeWalk;
  51980. // note that this loop does not process the corner texels, since they have already been
  51981. // averaged across faces across earlier
  51982. for (j = 1; j < (cubeMapSize - 1); j++) {
  51983. //for each set of taps along edge, average them
  51984. // and rewrite the results into the edges
  51985. for (k = 0; k < this.numChannels; k++) {
  51986. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51987. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51988. //compute average of tap intensity values
  51989. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51990. //propagate average of taps to edge taps
  51991. cubeMap[face][edgeStartIndex + k] = avgTap;
  51992. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51993. }
  51994. edgeStartIndex += edgeWalk;
  51995. neighborEdgeStartIndex += neighborEdgeWalk;
  51996. }
  51997. }
  51998. };
  51999. return PMREMGenerator;
  52000. }());
  52001. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52002. PMREMGenerator.CP_UDIR = 0;
  52003. PMREMGenerator.CP_VDIR = 1;
  52004. PMREMGenerator.CP_FACEAXIS = 2;
  52005. //used to index cube faces
  52006. PMREMGenerator.CP_FACE_X_POS = 0;
  52007. PMREMGenerator.CP_FACE_X_NEG = 1;
  52008. PMREMGenerator.CP_FACE_Y_POS = 2;
  52009. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52010. PMREMGenerator.CP_FACE_Z_POS = 4;
  52011. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52012. //used to index image edges
  52013. // NOTE.. the actual number corresponding to the edge is important
  52014. // do not change these, or the code will break
  52015. //
  52016. // CP_EDGE_LEFT is u = 0
  52017. // CP_EDGE_RIGHT is u = width-1
  52018. // CP_EDGE_TOP is v = 0
  52019. // CP_EDGE_BOTTOM is v = height-1
  52020. PMREMGenerator.CP_EDGE_LEFT = 0;
  52021. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52022. PMREMGenerator.CP_EDGE_TOP = 2;
  52023. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52024. //corners of CUBE map (P or N specifys if it corresponds to the
  52025. // positive or negative direction each of X, Y, and Z
  52026. PMREMGenerator.CP_CORNER_NNN = 0;
  52027. PMREMGenerator.CP_CORNER_NNP = 1;
  52028. PMREMGenerator.CP_CORNER_NPN = 2;
  52029. PMREMGenerator.CP_CORNER_NPP = 3;
  52030. PMREMGenerator.CP_CORNER_PNN = 4;
  52031. PMREMGenerator.CP_CORNER_PNP = 5;
  52032. PMREMGenerator.CP_CORNER_PPN = 6;
  52033. PMREMGenerator.CP_CORNER_PPP = 7;
  52034. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52035. //3x2 matrices that map cube map indexing vectors in 3d
  52036. // (after face selection and divide through by the
  52037. // _ABSOLUTE VALUE_ of the max coord)
  52038. // into NVC space
  52039. //Note this currently assumes the D3D cube face ordering and orientation
  52040. PMREMGenerator._sgFace2DMapping = [
  52041. //XPOS face
  52042. [[0, 0, -1],
  52043. [0, -1, 0],
  52044. [1, 0, 0]],
  52045. //XNEG face
  52046. [[0, 0, 1],
  52047. [0, -1, 0],
  52048. [-1, 0, 0]],
  52049. //YPOS face
  52050. [[1, 0, 0],
  52051. [0, 0, 1],
  52052. [0, 1, 0]],
  52053. //YNEG face
  52054. [[1, 0, 0],
  52055. [0, 0, -1],
  52056. [0, -1, 0]],
  52057. //ZPOS face
  52058. [[1, 0, 0],
  52059. [0, -1, 0],
  52060. [0, 0, 1]],
  52061. //ZNEG face
  52062. [[-1, 0, 0],
  52063. [0, -1, 0],
  52064. [0, 0, -1]],
  52065. ];
  52066. //------------------------------------------------------------------------------
  52067. // D3D cube map face specification
  52068. // mapping from 3D x,y,z cube map lookup coordinates
  52069. // to 2D within face u,v coordinates
  52070. //
  52071. // --------------------> U direction
  52072. // | (within-face texture space)
  52073. // | _____
  52074. // | | |
  52075. // | | +Y |
  52076. // | _____|_____|_____ _____
  52077. // | | | | | |
  52078. // | | -X | +Z | +X | -Z |
  52079. // | |_____|_____|_____|_____|
  52080. // | | |
  52081. // | | -Y |
  52082. // | |_____|
  52083. // |
  52084. // v V direction
  52085. // (within-face texture space)
  52086. //------------------------------------------------------------------------------
  52087. //Information about neighbors and how texture coorrdinates change across faces
  52088. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52089. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52090. //Note this currently assumes the D3D cube face ordering and orientation
  52091. PMREMGenerator._sgCubeNgh = [
  52092. //XPOS face
  52093. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52094. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52095. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52096. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52097. //XNEG face
  52098. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52099. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52100. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52101. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52102. //YPOS face
  52103. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52104. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52105. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52106. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52107. //YNEG face
  52108. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52109. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52110. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52111. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52112. //ZPOS face
  52113. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52114. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52115. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52116. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52117. //ZNEG face
  52118. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52119. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52120. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52121. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52122. ];
  52123. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52124. // this table is used to average over the edges.
  52125. PMREMGenerator._sgCubeEdgeList = [
  52126. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52127. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52128. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52129. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52130. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52131. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52132. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52133. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52134. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52135. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52136. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52137. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52138. ];
  52139. //Information about which of the 8 cube corners are correspond to the
  52140. // the 4 corners in each cube face
  52141. // the order is upper left, upper right, lower left, lower right
  52142. PMREMGenerator._sgCubeCornerList = [
  52143. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52144. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52145. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52146. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52147. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52148. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52149. ];
  52150. Internals.PMREMGenerator = PMREMGenerator;
  52151. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52152. })(BABYLON || (BABYLON = {}));
  52153. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  52154. var BABYLON;
  52155. (function (BABYLON) {
  52156. /**
  52157. * This represents a texture coming from an HDR input.
  52158. *
  52159. * The only supported format is currently panorama picture stored in RGBE format.
  52160. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52161. */
  52162. var HDRCubeTexture = (function (_super) {
  52163. __extends(HDRCubeTexture, _super);
  52164. /**
  52165. * Instantiates an HDRTexture from the following parameters.
  52166. *
  52167. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52168. * @param scene The scene the texture will be used in
  52169. * @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.
  52170. * @param noMipmap Forces to not generate the mipmap if true
  52171. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52172. * @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)
  52173. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52174. */
  52175. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  52176. if (noMipmap === void 0) { noMipmap = false; }
  52177. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52178. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52179. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52180. var _this = _super.call(this, scene) || this;
  52181. _this._useInGammaSpace = false;
  52182. _this._generateHarmonics = true;
  52183. _this._isBABYLONPreprocessed = false;
  52184. /**
  52185. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52186. */
  52187. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52188. /**
  52189. * The spherical polynomial data extracted from the texture.
  52190. */
  52191. _this.sphericalPolynomial = null;
  52192. /**
  52193. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52194. * This is usefull at run time to apply the good shader.
  52195. */
  52196. _this.isPMREM = false;
  52197. if (!url) {
  52198. return _this;
  52199. }
  52200. _this.name = url;
  52201. _this.url = url;
  52202. _this.hasAlpha = false;
  52203. _this.isCube = true;
  52204. _this._textureMatrix = BABYLON.Matrix.Identity();
  52205. if (size) {
  52206. _this._isBABYLONPreprocessed = false;
  52207. _this._noMipmap = noMipmap;
  52208. _this._size = size;
  52209. _this._useInGammaSpace = useInGammaSpace;
  52210. _this._usePMREMGenerator = usePMREMGenerator &&
  52211. scene.getEngine().getCaps().textureLOD &&
  52212. _this.getScene().getEngine().getCaps().textureFloat &&
  52213. !_this._useInGammaSpace;
  52214. }
  52215. else {
  52216. _this._isBABYLONPreprocessed = true;
  52217. _this._noMipmap = false;
  52218. _this._useInGammaSpace = false;
  52219. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52220. _this.getScene().getEngine().getCaps().textureFloat &&
  52221. !_this._useInGammaSpace;
  52222. }
  52223. _this.isPMREM = _this._usePMREMGenerator;
  52224. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52225. if (!_this._texture) {
  52226. if (!scene.useDelayedTextureLoading) {
  52227. _this.loadTexture();
  52228. }
  52229. else {
  52230. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52231. }
  52232. }
  52233. return _this;
  52234. }
  52235. /**
  52236. * Occurs when the file is a preprocessed .babylon.hdr file.
  52237. */
  52238. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52239. var _this = this;
  52240. var mipLevels = 0;
  52241. var floatArrayView = null;
  52242. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52243. var mips = [];
  52244. var startIndex = 30;
  52245. for (var level = 0; level < mipLevels; level++) {
  52246. mips.push([]);
  52247. // Fill each pixel of the mip level.
  52248. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52249. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52250. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52251. mips[level].push(faceData);
  52252. startIndex += faceSize;
  52253. }
  52254. }
  52255. return mips;
  52256. } : null;
  52257. var callback = function (buffer) {
  52258. // Create Native Array Views
  52259. var intArrayView = new Int32Array(buffer);
  52260. floatArrayView = new Float32Array(buffer);
  52261. // Fill header.
  52262. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52263. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52264. // Update Texture Information.
  52265. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52266. // Fill polynomial information.
  52267. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52268. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52269. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52270. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52271. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52272. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52273. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52274. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52275. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52276. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52277. // Fill pixel data.
  52278. mipLevels = intArrayView[29]; // Number of mip levels.
  52279. var startIndex = 30;
  52280. var data = [];
  52281. var faceSize = Math.pow(_this._size, 2) * 3;
  52282. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52283. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52284. startIndex += faceSize;
  52285. }
  52286. var results = [];
  52287. var byteArray = null;
  52288. // Push each faces.
  52289. for (var k = 0; k < 6; k++) {
  52290. var dataFace = null;
  52291. // If special cases.
  52292. if (!mipmapGenerator) {
  52293. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52294. dataFace = data[j];
  52295. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52296. // 3 channels of 1 bytes per pixel in bytes.
  52297. var byteBuffer = new ArrayBuffer(faceSize);
  52298. byteArray = new Uint8Array(byteBuffer);
  52299. }
  52300. for (var i = 0; i < _this._size * _this._size; i++) {
  52301. // Put in gamma space if requested.
  52302. if (_this._useInGammaSpace) {
  52303. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52304. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52305. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52306. }
  52307. // Convert to int texture for fallback.
  52308. if (byteArray) {
  52309. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52310. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52311. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52312. // May use luminance instead if the result is not accurate.
  52313. var max = Math.max(Math.max(r, g), b);
  52314. if (max > 255) {
  52315. var scale = 255 / max;
  52316. r *= scale;
  52317. g *= scale;
  52318. b *= scale;
  52319. }
  52320. byteArray[(i * 3) + 0] = r;
  52321. byteArray[(i * 3) + 1] = g;
  52322. byteArray[(i * 3) + 2] = b;
  52323. }
  52324. }
  52325. }
  52326. else {
  52327. dataFace = data[k];
  52328. }
  52329. // Fill the array accordingly.
  52330. if (byteArray) {
  52331. results.push(byteArray);
  52332. }
  52333. else {
  52334. results.push(dataFace);
  52335. }
  52336. }
  52337. return results;
  52338. };
  52339. 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);
  52340. };
  52341. /**
  52342. * Occurs when the file is raw .hdr file.
  52343. */
  52344. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52345. var _this = this;
  52346. var callback = function (buffer) {
  52347. // Extract the raw linear data.
  52348. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52349. // Generate harmonics if needed.
  52350. if (_this._generateHarmonics) {
  52351. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52352. }
  52353. var results = [];
  52354. var byteArray = null;
  52355. // Push each faces.
  52356. for (var j = 0; j < 6; j++) {
  52357. // Create uintarray fallback.
  52358. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52359. // 3 channels of 1 bytes per pixel in bytes.
  52360. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52361. byteArray = new Uint8Array(byteBuffer);
  52362. }
  52363. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52364. // If special cases.
  52365. if (_this._useInGammaSpace || byteArray) {
  52366. for (var i = 0; i < _this._size * _this._size; i++) {
  52367. // Put in gamma space if requested.
  52368. if (_this._useInGammaSpace) {
  52369. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52370. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52371. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52372. }
  52373. // Convert to int texture for fallback.
  52374. if (byteArray) {
  52375. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52376. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52377. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52378. // May use luminance instead if the result is not accurate.
  52379. var max = Math.max(Math.max(r, g), b);
  52380. if (max > 255) {
  52381. var scale = 255 / max;
  52382. r *= scale;
  52383. g *= scale;
  52384. b *= scale;
  52385. }
  52386. byteArray[(i * 3) + 0] = r;
  52387. byteArray[(i * 3) + 1] = g;
  52388. byteArray[(i * 3) + 2] = b;
  52389. }
  52390. }
  52391. }
  52392. if (byteArray) {
  52393. results.push(byteArray);
  52394. }
  52395. else {
  52396. results.push(dataFace);
  52397. }
  52398. }
  52399. return results;
  52400. };
  52401. var mipmapGenerator = null;
  52402. if (!this._noMipmap &&
  52403. this._usePMREMGenerator) {
  52404. mipmapGenerator = function (data) {
  52405. // Custom setup of the generator matching with the PBR shader values.
  52406. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52407. return generator.filterCubeMap();
  52408. };
  52409. }
  52410. 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);
  52411. };
  52412. /**
  52413. * Starts the loading process of the texture.
  52414. */
  52415. HDRCubeTexture.prototype.loadTexture = function () {
  52416. if (this._isBABYLONPreprocessed) {
  52417. this.loadBabylonTexture();
  52418. }
  52419. else {
  52420. this.loadHDRTexture();
  52421. }
  52422. };
  52423. HDRCubeTexture.prototype.clone = function () {
  52424. var size = this._isBABYLONPreprocessed ? null : this._size;
  52425. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52426. // Base texture
  52427. newTexture.level = this.level;
  52428. newTexture.wrapU = this.wrapU;
  52429. newTexture.wrapV = this.wrapV;
  52430. newTexture.coordinatesIndex = this.coordinatesIndex;
  52431. newTexture.coordinatesMode = this.coordinatesMode;
  52432. return newTexture;
  52433. };
  52434. // Methods
  52435. HDRCubeTexture.prototype.delayLoad = function () {
  52436. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52437. return;
  52438. }
  52439. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52440. this._texture = this._getFromCache(this.url, this._noMipmap);
  52441. if (!this._texture) {
  52442. this.loadTexture();
  52443. }
  52444. };
  52445. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52446. return this._textureMatrix;
  52447. };
  52448. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52449. var texture = null;
  52450. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52451. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52452. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52453. texture.name = parsedTexture.name;
  52454. texture.hasAlpha = parsedTexture.hasAlpha;
  52455. texture.level = parsedTexture.level;
  52456. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52457. }
  52458. return texture;
  52459. };
  52460. HDRCubeTexture.prototype.serialize = function () {
  52461. if (!this.name) {
  52462. return null;
  52463. }
  52464. var serializationObject = {};
  52465. serializationObject.name = this.name;
  52466. serializationObject.hasAlpha = this.hasAlpha;
  52467. serializationObject.isCube = true;
  52468. serializationObject.level = this.level;
  52469. serializationObject.size = this._size;
  52470. serializationObject.coordinatesMode = this.coordinatesMode;
  52471. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52472. serializationObject.generateHarmonics = this._generateHarmonics;
  52473. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52474. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52475. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52476. serializationObject.noMipmap = this._noMipmap;
  52477. return serializationObject;
  52478. };
  52479. /**
  52480. * Saves as a file the data contained in the texture in a binary format.
  52481. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52482. * as the spherical used in the lighting.
  52483. * @param url The HDR file url.
  52484. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52485. * @param onError Method called if any error happens during download.
  52486. * @return The packed binary data.
  52487. */
  52488. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52489. if (onError === void 0) { onError = null; }
  52490. var callback = function (buffer) {
  52491. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52492. // Returns a URL you can use as a href.
  52493. var objUrl = window.URL.createObjectURL(data);
  52494. // Simulates a link to it and click to dowload.
  52495. var a = document.createElement("a");
  52496. document.body.appendChild(a);
  52497. a.style.display = "none";
  52498. a.href = objUrl;
  52499. a.download = "envmap.babylon.hdr";
  52500. a.click();
  52501. };
  52502. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52503. };
  52504. /**
  52505. * Serializes the data contained in the texture in a binary format.
  52506. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52507. * as the spherical used in the lighting.
  52508. * @param url The HDR file url.
  52509. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52510. * @param onError Method called if any error happens during download.
  52511. * @return The packed binary data.
  52512. */
  52513. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52514. if (onError === void 0) { onError = null; }
  52515. // Needs the url tho create the texture.
  52516. if (!url) {
  52517. return null;
  52518. }
  52519. // Check Power of two size.
  52520. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52521. return null;
  52522. }
  52523. var getDataCallback = function (dataBuffer) {
  52524. // Extract the raw linear data.
  52525. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52526. // Generate harmonics if needed.
  52527. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52528. // Generate seamless faces
  52529. var mipGeneratorArray = [];
  52530. // Data are known to be in +X +Y +Z -X -Y -Z
  52531. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52532. mipGeneratorArray.push(cubeData.right); // +X
  52533. mipGeneratorArray.push(cubeData.left); // -X
  52534. mipGeneratorArray.push(cubeData.up); // +Y
  52535. mipGeneratorArray.push(cubeData.down); // -Y
  52536. mipGeneratorArray.push(cubeData.front); // +Z
  52537. mipGeneratorArray.push(cubeData.back); // -Z
  52538. // Custom setup of the generator matching with the PBR shader values.
  52539. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52540. var mippedData = generator.filterCubeMap();
  52541. // Compute required byte length.
  52542. var byteLength = 1 * 4; // Raw Data Version int32.
  52543. byteLength += 4; // CubeMap max mip face size int32.
  52544. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52545. // Add data size.
  52546. byteLength += 4; // Number of mip levels int32.
  52547. for (var level = 0; level < mippedData.length; level++) {
  52548. var mipSize = size >> level;
  52549. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52550. }
  52551. // Prepare binary structure.
  52552. var buffer = new ArrayBuffer(byteLength);
  52553. var intArrayView = new Int32Array(buffer);
  52554. var floatArrayView = new Float32Array(buffer);
  52555. // Fill header.
  52556. intArrayView[0] = 1; // Version 1.
  52557. intArrayView[1] = size; // CubeMap max mip face size.
  52558. // Fill polynomial information.
  52559. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52560. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52561. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52562. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52563. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52564. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52565. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52566. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52567. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52568. // Fill pixel data.
  52569. intArrayView[29] = mippedData.length; // Number of mip levels.
  52570. var startIndex = 30;
  52571. for (var level = 0; level < mippedData.length; level++) {
  52572. // Fill each pixel of the mip level.
  52573. var faceSize = Math.pow(size >> level, 2) * 3;
  52574. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52575. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52576. startIndex += faceSize;
  52577. }
  52578. }
  52579. // Callback.
  52580. callback(buffer);
  52581. };
  52582. // Download and process.
  52583. BABYLON.Tools.LoadFile(url, function (data) {
  52584. getDataCallback(data);
  52585. }, null, null, true, onError);
  52586. };
  52587. return HDRCubeTexture;
  52588. }(BABYLON.BaseTexture));
  52589. HDRCubeTexture._facesMapping = [
  52590. "right",
  52591. "up",
  52592. "front",
  52593. "left",
  52594. "down",
  52595. "back"
  52596. ];
  52597. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52598. })(BABYLON || (BABYLON = {}));
  52599. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52600. var BABYLON;
  52601. (function (BABYLON) {
  52602. var Debug;
  52603. (function (Debug) {
  52604. /**
  52605. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52606. */
  52607. var SkeletonViewer = (function () {
  52608. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52609. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52610. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52611. this.skeleton = skeleton;
  52612. this.mesh = mesh;
  52613. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52614. this.renderingGroupId = renderingGroupId;
  52615. this.color = BABYLON.Color3.White();
  52616. this._debugLines = [];
  52617. this._isEnabled = false;
  52618. this._scene = scene;
  52619. this.update();
  52620. this._renderFunction = this.update.bind(this);
  52621. }
  52622. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52623. get: function () {
  52624. return this._isEnabled;
  52625. },
  52626. set: function (value) {
  52627. if (this._isEnabled === value) {
  52628. return;
  52629. }
  52630. this._isEnabled = value;
  52631. if (value) {
  52632. this._scene.registerBeforeRender(this._renderFunction);
  52633. }
  52634. else {
  52635. this._scene.unregisterBeforeRender(this._renderFunction);
  52636. }
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52642. if (x === void 0) { x = 0; }
  52643. if (y === void 0) { y = 0; }
  52644. if (z === void 0) { z = 0; }
  52645. var tmat = BABYLON.Tmp.Matrix[0];
  52646. var parentBone = bone.getParent();
  52647. tmat.copyFrom(bone.getLocalMatrix());
  52648. if (x !== 0 || y !== 0 || z !== 0) {
  52649. var tmat2 = BABYLON.Tmp.Matrix[1];
  52650. BABYLON.Matrix.IdentityToRef(tmat2);
  52651. tmat2.m[12] = x;
  52652. tmat2.m[13] = y;
  52653. tmat2.m[14] = z;
  52654. tmat2.multiplyToRef(tmat, tmat);
  52655. }
  52656. if (parentBone) {
  52657. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52658. }
  52659. tmat.multiplyToRef(meshMat, tmat);
  52660. position.x = tmat.m[12];
  52661. position.y = tmat.m[13];
  52662. position.z = tmat.m[14];
  52663. };
  52664. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52665. var len = bones.length;
  52666. for (var i = 0; i < len; i++) {
  52667. var bone = bones[i];
  52668. var points = this._debugLines[i];
  52669. if (!points) {
  52670. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52671. this._debugLines[i] = points;
  52672. }
  52673. this._getBonePosition(points[0], bone, meshMat);
  52674. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52675. }
  52676. };
  52677. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52678. var len = bones.length;
  52679. var boneNum = 0;
  52680. for (var i = len - 1; i >= 0; i--) {
  52681. var childBone = bones[i];
  52682. var parentBone = childBone.getParent();
  52683. if (!parentBone) {
  52684. continue;
  52685. }
  52686. var points = this._debugLines[boneNum];
  52687. if (!points) {
  52688. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52689. this._debugLines[boneNum] = points;
  52690. }
  52691. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52692. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52693. boneNum++;
  52694. }
  52695. };
  52696. SkeletonViewer.prototype.update = function () {
  52697. if (this.autoUpdateBonesMatrices) {
  52698. this.skeleton.computeAbsoluteTransforms();
  52699. }
  52700. if (this.skeleton.bones[0].length === undefined) {
  52701. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52702. }
  52703. else {
  52704. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52705. }
  52706. if (!this._debugMesh) {
  52707. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52708. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52709. }
  52710. else {
  52711. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52712. }
  52713. this._debugMesh.color = this.color;
  52714. };
  52715. SkeletonViewer.prototype.dispose = function () {
  52716. if (this._debugMesh) {
  52717. this.isEnabled = false;
  52718. this._debugMesh.dispose();
  52719. this._debugMesh = null;
  52720. }
  52721. };
  52722. return SkeletonViewer;
  52723. }());
  52724. Debug.SkeletonViewer = SkeletonViewer;
  52725. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52726. })(BABYLON || (BABYLON = {}));
  52727. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52728. var BABYLON;
  52729. (function (BABYLON) {
  52730. var Debug;
  52731. (function (Debug) {
  52732. var AxesViewer = (function () {
  52733. function AxesViewer(scene, scaleLines) {
  52734. if (scaleLines === void 0) { scaleLines = 1; }
  52735. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52736. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52737. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52738. this.scaleLines = 1;
  52739. this.scaleLines = scaleLines;
  52740. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52741. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52742. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52743. this._xmesh.renderingGroupId = 2;
  52744. this._ymesh.renderingGroupId = 2;
  52745. this._zmesh.renderingGroupId = 2;
  52746. this._xmesh.material.checkReadyOnlyOnce = true;
  52747. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52748. this._ymesh.material.checkReadyOnlyOnce = true;
  52749. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52750. this._zmesh.material.checkReadyOnlyOnce = true;
  52751. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52752. this.scene = scene;
  52753. }
  52754. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52755. var scaleLines = this.scaleLines;
  52756. var point1 = this._xline[0];
  52757. var point2 = this._xline[1];
  52758. point1.x = position.x;
  52759. point1.y = position.y;
  52760. point1.z = position.z;
  52761. point2.x = point1.x + xaxis.x * scaleLines;
  52762. point2.y = point1.y + xaxis.y * scaleLines;
  52763. point2.z = point1.z + xaxis.z * scaleLines;
  52764. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52765. point1 = this._yline[0];
  52766. point2 = this._yline[1];
  52767. point1.x = position.x;
  52768. point1.y = position.y;
  52769. point1.z = position.z;
  52770. point2.x = point1.x + yaxis.x * scaleLines;
  52771. point2.y = point1.y + yaxis.y * scaleLines;
  52772. point2.z = point1.z + yaxis.z * scaleLines;
  52773. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52774. point1 = this._zline[0];
  52775. point2 = this._zline[1];
  52776. point1.x = position.x;
  52777. point1.y = position.y;
  52778. point1.z = position.z;
  52779. point2.x = point1.x + zaxis.x * scaleLines;
  52780. point2.y = point1.y + zaxis.y * scaleLines;
  52781. point2.z = point1.z + zaxis.z * scaleLines;
  52782. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52783. };
  52784. AxesViewer.prototype.dispose = function () {
  52785. if (this._xmesh) {
  52786. this._xmesh.dispose();
  52787. this._ymesh.dispose();
  52788. this._zmesh.dispose();
  52789. this._xmesh = null;
  52790. this._ymesh = null;
  52791. this._zmesh = null;
  52792. this._xline = null;
  52793. this._yline = null;
  52794. this._zline = null;
  52795. this.scene = null;
  52796. }
  52797. };
  52798. return AxesViewer;
  52799. }());
  52800. Debug.AxesViewer = AxesViewer;
  52801. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52802. })(BABYLON || (BABYLON = {}));
  52803. //# sourceMappingURL=babylon.axesViewer.js.map
  52804. var BABYLON;
  52805. (function (BABYLON) {
  52806. var Debug;
  52807. (function (Debug) {
  52808. var BoneAxesViewer = (function (_super) {
  52809. __extends(BoneAxesViewer, _super);
  52810. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52811. if (scaleLines === void 0) { scaleLines = 1; }
  52812. var _this = _super.call(this, scene, scaleLines) || this;
  52813. _this.pos = BABYLON.Vector3.Zero();
  52814. _this.xaxis = BABYLON.Vector3.Zero();
  52815. _this.yaxis = BABYLON.Vector3.Zero();
  52816. _this.zaxis = BABYLON.Vector3.Zero();
  52817. _this.mesh = mesh;
  52818. _this.bone = bone;
  52819. return _this;
  52820. }
  52821. BoneAxesViewer.prototype.update = function () {
  52822. var bone = this.bone;
  52823. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52824. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52825. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52826. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52827. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52828. };
  52829. BoneAxesViewer.prototype.dispose = function () {
  52830. if (this.pos) {
  52831. this.pos = null;
  52832. this.xaxis = null;
  52833. this.yaxis = null;
  52834. this.zaxis = null;
  52835. this.mesh = null;
  52836. this.bone = null;
  52837. _super.prototype.dispose.call(this);
  52838. }
  52839. };
  52840. return BoneAxesViewer;
  52841. }(Debug.AxesViewer));
  52842. Debug.BoneAxesViewer = BoneAxesViewer;
  52843. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52844. })(BABYLON || (BABYLON = {}));
  52845. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52846. var BABYLON;
  52847. (function (BABYLON) {
  52848. /**
  52849. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52850. * It can help converting any input color in a desired output one. This can then be used to create effects
  52851. * from sepia, black and white to sixties or futuristic rendering...
  52852. *
  52853. * The only supported format is currently 3dl.
  52854. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52855. */
  52856. var ColorGradingTexture = (function (_super) {
  52857. __extends(ColorGradingTexture, _super);
  52858. /**
  52859. * Instantiates a ColorGradingTexture from the following parameters.
  52860. *
  52861. * @param url The location of the color gradind data (currently only supporting 3dl)
  52862. * @param scene The scene the texture will be used in
  52863. */
  52864. function ColorGradingTexture(url, scene) {
  52865. var _this = _super.call(this, scene) || this;
  52866. if (!url) {
  52867. return _this;
  52868. }
  52869. _this._textureMatrix = BABYLON.Matrix.Identity();
  52870. _this.name = url;
  52871. _this.url = url;
  52872. _this.hasAlpha = false;
  52873. _this.isCube = false;
  52874. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52875. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52876. _this.anisotropicFilteringLevel = 1;
  52877. _this._texture = _this._getFromCache(url, true);
  52878. if (!_this._texture) {
  52879. if (!scene.useDelayedTextureLoading) {
  52880. _this.loadTexture();
  52881. }
  52882. else {
  52883. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52884. }
  52885. }
  52886. return _this;
  52887. }
  52888. /**
  52889. * Returns the texture matrix used in most of the material.
  52890. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52891. */
  52892. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52893. return this._textureMatrix;
  52894. };
  52895. /**
  52896. * Occurs when the file being loaded is a .3dl LUT file.
  52897. */
  52898. ColorGradingTexture.prototype.load3dlTexture = function () {
  52899. var _this = this;
  52900. var mipLevels = 0;
  52901. var floatArrayView = null;
  52902. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52903. this._texture = texture;
  52904. var callback = function (text) {
  52905. var data;
  52906. var tempData;
  52907. var line;
  52908. var lines = text.split('\n');
  52909. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52910. var maxColor = 0;
  52911. for (var i = 0; i < lines.length; i++) {
  52912. line = lines[i];
  52913. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52914. continue;
  52915. if (line.indexOf('#') === 0)
  52916. continue;
  52917. var words = line.split(" ");
  52918. if (size === 0) {
  52919. // Number of space + one
  52920. size = words.length;
  52921. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52922. tempData = new Float32Array(size * size * size * 4);
  52923. continue;
  52924. }
  52925. if (size != 0) {
  52926. var r = Math.max(parseInt(words[0]), 0);
  52927. var g = Math.max(parseInt(words[1]), 0);
  52928. var b = Math.max(parseInt(words[2]), 0);
  52929. maxColor = Math.max(r, maxColor);
  52930. maxColor = Math.max(g, maxColor);
  52931. maxColor = Math.max(b, maxColor);
  52932. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52933. tempData[pixelStorageIndex + 0] = r;
  52934. tempData[pixelStorageIndex + 1] = g;
  52935. tempData[pixelStorageIndex + 2] = b;
  52936. tempData[pixelStorageIndex + 3] = 0;
  52937. pixelIndexSlice++;
  52938. if (pixelIndexSlice % size == 0) {
  52939. pixelIndexH++;
  52940. pixelIndexSlice = 0;
  52941. if (pixelIndexH % size == 0) {
  52942. pixelIndexW++;
  52943. pixelIndexH = 0;
  52944. }
  52945. }
  52946. }
  52947. }
  52948. for (var i = 0; i < tempData.length; i++) {
  52949. var value = tempData[i];
  52950. data[i] = (value / maxColor * 255);
  52951. }
  52952. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52953. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52954. };
  52955. BABYLON.Tools.LoadFile(this.url, callback);
  52956. return this._texture;
  52957. };
  52958. /**
  52959. * Starts the loading process of the texture.
  52960. */
  52961. ColorGradingTexture.prototype.loadTexture = function () {
  52962. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52963. this.load3dlTexture();
  52964. }
  52965. };
  52966. /**
  52967. * Clones the color gradind texture.
  52968. */
  52969. ColorGradingTexture.prototype.clone = function () {
  52970. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52971. // Base texture
  52972. newTexture.level = this.level;
  52973. return newTexture;
  52974. };
  52975. /**
  52976. * Called during delayed load for textures.
  52977. */
  52978. ColorGradingTexture.prototype.delayLoad = function () {
  52979. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52980. return;
  52981. }
  52982. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52983. this._texture = this._getFromCache(this.url, true);
  52984. if (!this._texture) {
  52985. this.loadTexture();
  52986. }
  52987. };
  52988. /**
  52989. * Binds the color grading to the shader.
  52990. * @param colorGrading The texture to bind
  52991. * @param effect The effect to bind to
  52992. */
  52993. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52994. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52995. var x = colorGrading.level; // Texture Level
  52996. var y = colorGrading.getSize().height; // Texture Size example with 8
  52997. var z = y - 1.0; // SizeMinusOne 8 - 1
  52998. var w = 1 / y; // Space of 1 slice 1 / 8
  52999. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  53000. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  53001. 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
  53002. 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
  53003. 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
  53004. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  53005. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  53006. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  53007. };
  53008. /**
  53009. * Prepare the list of uniforms associated with the ColorGrading effects.
  53010. * @param uniformsList The list of uniforms used in the effect
  53011. * @param samplersList The list of samplers used in the effect
  53012. */
  53013. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  53014. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  53015. samplersList.push("cameraColorGrading2DSampler");
  53016. };
  53017. /**
  53018. * Parses a color grading texture serialized by Babylon.
  53019. * @param parsedTexture The texture information being parsedTexture
  53020. * @param scene The scene to load the texture in
  53021. * @param rootUrl The root url of the data assets to load
  53022. * @return A color gradind texture
  53023. */
  53024. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53025. var texture = null;
  53026. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  53027. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  53028. texture.name = parsedTexture.name;
  53029. texture.level = parsedTexture.level;
  53030. }
  53031. return texture;
  53032. };
  53033. /**
  53034. * Serializes the LUT texture to json format.
  53035. */
  53036. ColorGradingTexture.prototype.serialize = function () {
  53037. if (!this.name) {
  53038. return null;
  53039. }
  53040. var serializationObject = {};
  53041. serializationObject.name = this.name;
  53042. serializationObject.level = this.level;
  53043. serializationObject.customType = "BABYLON.ColorGradingTexture";
  53044. return serializationObject;
  53045. };
  53046. return ColorGradingTexture;
  53047. }(BABYLON.BaseTexture));
  53048. /**
  53049. * Empty line regex stored for GC.
  53050. */
  53051. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  53052. BABYLON.ColorGradingTexture = ColorGradingTexture;
  53053. })(BABYLON || (BABYLON = {}));
  53054. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  53055. var BABYLON;
  53056. (function (BABYLON) {
  53057. /**
  53058. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53059. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53060. * 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;
  53061. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53062. */
  53063. var ColorCurves = (function () {
  53064. function ColorCurves() {
  53065. this._dirty = true;
  53066. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  53067. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  53068. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53069. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  53070. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53071. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  53072. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  53073. this._globalHue = 30;
  53074. this._globalDensity = 0;
  53075. this._globalSaturation = 0;
  53076. this._globalExposure = 0;
  53077. this._highlightsHue = 30;
  53078. this._highlightsDensity = 0;
  53079. this._highlightsSaturation = 0;
  53080. this._highlightsExposure = 0;
  53081. this._midtonesHue = 30;
  53082. this._midtonesDensity = 0;
  53083. this._midtonesSaturation = 0;
  53084. this._midtonesExposure = 0;
  53085. this._shadowsHue = 30;
  53086. this._shadowsDensity = 0;
  53087. this._shadowsSaturation = 0;
  53088. this._shadowsExposure = 0;
  53089. }
  53090. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  53091. /**
  53092. * Gets the global Hue value.
  53093. * 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).
  53094. */
  53095. get: function () {
  53096. return this._globalHue;
  53097. },
  53098. /**
  53099. * Sets the global Hue value.
  53100. * 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).
  53101. */
  53102. set: function (value) {
  53103. this._globalHue = value;
  53104. this._dirty = true;
  53105. },
  53106. enumerable: true,
  53107. configurable: true
  53108. });
  53109. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  53110. /**
  53111. * Gets the global Density value.
  53112. * 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.
  53113. * Values less than zero provide a filter of opposite hue.
  53114. */
  53115. get: function () {
  53116. return this._globalDensity;
  53117. },
  53118. /**
  53119. * Sets the global Density value.
  53120. * 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.
  53121. * Values less than zero provide a filter of opposite hue.
  53122. */
  53123. set: function (value) {
  53124. this._globalDensity = value;
  53125. this._dirty = true;
  53126. },
  53127. enumerable: true,
  53128. configurable: true
  53129. });
  53130. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  53131. /**
  53132. * Gets the global Saturation value.
  53133. * 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.
  53134. */
  53135. get: function () {
  53136. return this._globalSaturation;
  53137. },
  53138. /**
  53139. * Sets the global Saturation value.
  53140. * 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.
  53141. */
  53142. set: function (value) {
  53143. this._globalSaturation = value;
  53144. this._dirty = true;
  53145. },
  53146. enumerable: true,
  53147. configurable: true
  53148. });
  53149. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  53150. /**
  53151. * Gets the highlights Hue value.
  53152. * 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).
  53153. */
  53154. get: function () {
  53155. return this._highlightsHue;
  53156. },
  53157. /**
  53158. * Sets the highlights Hue value.
  53159. * 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).
  53160. */
  53161. set: function (value) {
  53162. this._highlightsHue = value;
  53163. this._dirty = true;
  53164. },
  53165. enumerable: true,
  53166. configurable: true
  53167. });
  53168. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  53169. /**
  53170. * Gets the highlights Density value.
  53171. * 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.
  53172. * Values less than zero provide a filter of opposite hue.
  53173. */
  53174. get: function () {
  53175. return this._highlightsDensity;
  53176. },
  53177. /**
  53178. * Sets the highlights Density value.
  53179. * 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.
  53180. * Values less than zero provide a filter of opposite hue.
  53181. */
  53182. set: function (value) {
  53183. this._highlightsDensity = value;
  53184. this._dirty = true;
  53185. },
  53186. enumerable: true,
  53187. configurable: true
  53188. });
  53189. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  53190. /**
  53191. * Gets the highlights Saturation value.
  53192. * 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.
  53193. */
  53194. get: function () {
  53195. return this._highlightsSaturation;
  53196. },
  53197. /**
  53198. * Sets the highlights Saturation value.
  53199. * 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.
  53200. */
  53201. set: function (value) {
  53202. this._highlightsSaturation = value;
  53203. this._dirty = true;
  53204. },
  53205. enumerable: true,
  53206. configurable: true
  53207. });
  53208. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  53209. /**
  53210. * Gets the highlights Exposure value.
  53211. * 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.
  53212. */
  53213. get: function () {
  53214. return this._highlightsExposure;
  53215. },
  53216. /**
  53217. * Sets the highlights Exposure value.
  53218. * 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.
  53219. */
  53220. set: function (value) {
  53221. this._highlightsExposure = value;
  53222. this._dirty = true;
  53223. },
  53224. enumerable: true,
  53225. configurable: true
  53226. });
  53227. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  53228. /**
  53229. * Gets the midtones Hue value.
  53230. * 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).
  53231. */
  53232. get: function () {
  53233. return this._midtonesHue;
  53234. },
  53235. /**
  53236. * Sets the midtones Hue value.
  53237. * 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).
  53238. */
  53239. set: function (value) {
  53240. this._midtonesHue = value;
  53241. this._dirty = true;
  53242. },
  53243. enumerable: true,
  53244. configurable: true
  53245. });
  53246. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  53247. /**
  53248. * Gets the midtones Density value.
  53249. * 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.
  53250. * Values less than zero provide a filter of opposite hue.
  53251. */
  53252. get: function () {
  53253. return this._midtonesDensity;
  53254. },
  53255. /**
  53256. * Sets the midtones Density value.
  53257. * 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.
  53258. * Values less than zero provide a filter of opposite hue.
  53259. */
  53260. set: function (value) {
  53261. this._midtonesDensity = value;
  53262. this._dirty = true;
  53263. },
  53264. enumerable: true,
  53265. configurable: true
  53266. });
  53267. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  53268. /**
  53269. * Gets the midtones Saturation value.
  53270. * 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.
  53271. */
  53272. get: function () {
  53273. return this._midtonesSaturation;
  53274. },
  53275. /**
  53276. * Sets the midtones Saturation value.
  53277. * 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.
  53278. */
  53279. set: function (value) {
  53280. this._midtonesSaturation = value;
  53281. this._dirty = true;
  53282. },
  53283. enumerable: true,
  53284. configurable: true
  53285. });
  53286. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  53287. /**
  53288. * Gets the midtones Exposure value.
  53289. * 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.
  53290. */
  53291. get: function () {
  53292. return this._midtonesExposure;
  53293. },
  53294. /**
  53295. * Sets the midtones Exposure value.
  53296. * 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.
  53297. */
  53298. set: function (value) {
  53299. this._midtonesExposure = value;
  53300. this._dirty = true;
  53301. },
  53302. enumerable: true,
  53303. configurable: true
  53304. });
  53305. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  53306. /**
  53307. * Gets the shadows Hue value.
  53308. * 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).
  53309. */
  53310. get: function () {
  53311. return this._shadowsHue;
  53312. },
  53313. /**
  53314. * Sets the shadows Hue value.
  53315. * 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).
  53316. */
  53317. set: function (value) {
  53318. this._shadowsHue = value;
  53319. this._dirty = true;
  53320. },
  53321. enumerable: true,
  53322. configurable: true
  53323. });
  53324. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  53325. /**
  53326. * Gets the shadows Density value.
  53327. * 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.
  53328. * Values less than zero provide a filter of opposite hue.
  53329. */
  53330. get: function () {
  53331. return this._shadowsDensity;
  53332. },
  53333. /**
  53334. * Sets the shadows Density value.
  53335. * 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.
  53336. * Values less than zero provide a filter of opposite hue.
  53337. */
  53338. set: function (value) {
  53339. this._shadowsDensity = value;
  53340. this._dirty = true;
  53341. },
  53342. enumerable: true,
  53343. configurable: true
  53344. });
  53345. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  53346. /**
  53347. * Gets the shadows Saturation value.
  53348. * 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.
  53349. */
  53350. get: function () {
  53351. return this._shadowsSaturation;
  53352. },
  53353. /**
  53354. * Sets the shadows Saturation value.
  53355. * 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.
  53356. */
  53357. set: function (value) {
  53358. this._shadowsSaturation = value;
  53359. this._dirty = true;
  53360. },
  53361. enumerable: true,
  53362. configurable: true
  53363. });
  53364. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  53365. /**
  53366. * Gets the shadows Exposure value.
  53367. * 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.
  53368. */
  53369. get: function () {
  53370. return this._shadowsExposure;
  53371. },
  53372. /**
  53373. * Sets the shadows Exposure value.
  53374. * 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.
  53375. */
  53376. set: function (value) {
  53377. this._shadowsExposure = value;
  53378. this._dirty = true;
  53379. },
  53380. enumerable: true,
  53381. configurable: true
  53382. });
  53383. /**
  53384. * Binds the color curves to the shader.
  53385. * @param colorCurves The color curve to bind
  53386. * @param effect The effect to bind to
  53387. */
  53388. ColorCurves.Bind = function (colorCurves, effect) {
  53389. if (colorCurves._dirty) {
  53390. colorCurves._dirty = false;
  53391. // Fill in global info.
  53392. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  53393. // Compute highlights info.
  53394. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  53395. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  53396. // Compute midtones info.
  53397. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  53398. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  53399. // Compute shadows info.
  53400. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  53401. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  53402. // Compute deltas (neutral is midtones).
  53403. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  53404. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  53405. }
  53406. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  53407. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  53408. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  53409. };
  53410. /**
  53411. * Prepare the list of uniforms associated with the ColorCurves effects.
  53412. * @param uniformsList The list of uniforms used in the effect
  53413. */
  53414. ColorCurves.PrepareUniforms = function (uniformsList) {
  53415. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  53416. };
  53417. /**
  53418. * Returns color grading data based on a hue, density, saturation and exposure value.
  53419. * @param filterHue The hue of the color filter.
  53420. * @param filterDensity The density of the color filter.
  53421. * @param saturation The saturation.
  53422. * @param exposure The exposure.
  53423. * @param result The result data container.
  53424. */
  53425. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  53426. if (hue == null) {
  53427. return;
  53428. }
  53429. hue = ColorCurves.clamp(hue, 0, 360);
  53430. density = ColorCurves.clamp(density, -100, 100);
  53431. saturation = ColorCurves.clamp(saturation, -100, 100);
  53432. exposure = ColorCurves.clamp(exposure, -100, 100);
  53433. // Remap the slider/config filter density with non-linear mapping and also scale by half
  53434. // so that the maximum filter density is only 50% control. This provides fine control
  53435. // for small values and reasonable range.
  53436. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  53437. density *= 0.5;
  53438. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  53439. if (density < 0) {
  53440. density *= -1;
  53441. hue = (hue + 180) % 360;
  53442. }
  53443. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  53444. result.scaleToRef(2, result);
  53445. result.a = 1 + 0.01 * saturation;
  53446. };
  53447. /**
  53448. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  53449. * @param value The input slider value in range [-100,100].
  53450. * @returns Adjusted value.
  53451. */
  53452. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  53453. value /= 100;
  53454. var x = Math.abs(value);
  53455. x = Math.pow(x, 2);
  53456. if (value < 0) {
  53457. x *= -1;
  53458. }
  53459. x *= 100;
  53460. return x;
  53461. };
  53462. /**
  53463. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  53464. * @param hue The hue (H) input.
  53465. * @param saturation The saturation (S) input.
  53466. * @param brightness The brightness (B) input.
  53467. * @result An RGBA color represented as Vector4.
  53468. */
  53469. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  53470. var h = ColorCurves.clamp(hue, 0, 360);
  53471. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  53472. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  53473. if (s === 0) {
  53474. result.r = v;
  53475. result.g = v;
  53476. result.b = v;
  53477. }
  53478. else {
  53479. // sector 0 to 5
  53480. h /= 60;
  53481. var i = Math.floor(h);
  53482. // fractional part of h
  53483. var f = h - i;
  53484. var p = v * (1 - s);
  53485. var q = v * (1 - s * f);
  53486. var t = v * (1 - s * (1 - f));
  53487. switch (i) {
  53488. case 0:
  53489. result.r = v;
  53490. result.g = t;
  53491. result.b = p;
  53492. break;
  53493. case 1:
  53494. result.r = q;
  53495. result.g = v;
  53496. result.b = p;
  53497. break;
  53498. case 2:
  53499. result.r = p;
  53500. result.g = v;
  53501. result.b = t;
  53502. break;
  53503. case 3:
  53504. result.r = p;
  53505. result.g = q;
  53506. result.b = v;
  53507. break;
  53508. case 4:
  53509. result.r = t;
  53510. result.g = p;
  53511. result.b = v;
  53512. break;
  53513. default:
  53514. result.r = v;
  53515. result.g = p;
  53516. result.b = q;
  53517. break;
  53518. }
  53519. }
  53520. result.a = 1;
  53521. };
  53522. /**
  53523. * Returns a value clamped between min and max
  53524. * @param value The value to clamp
  53525. * @param min The minimum of value
  53526. * @param max The maximum of value
  53527. * @returns The clamped value.
  53528. */
  53529. ColorCurves.clamp = function (value, min, max) {
  53530. return Math.min(Math.max(value, min), max);
  53531. };
  53532. /**
  53533. * Clones the current color curve instance.
  53534. * @return The cloned curves
  53535. */
  53536. ColorCurves.prototype.clone = function () {
  53537. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  53538. };
  53539. /**
  53540. * Serializes the current color curve instance to a json representation.
  53541. * @return a JSON representation
  53542. */
  53543. ColorCurves.prototype.serialize = function () {
  53544. return BABYLON.SerializationHelper.Serialize(this);
  53545. };
  53546. /**
  53547. * Parses the color curve from a json representation.
  53548. * @param source the JSON source to parse
  53549. * @return The parsed curves
  53550. */
  53551. ColorCurves.Parse = function (source) {
  53552. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53553. };
  53554. return ColorCurves;
  53555. }());
  53556. __decorate([
  53557. BABYLON.serialize()
  53558. ], ColorCurves.prototype, "_globalHue", void 0);
  53559. __decorate([
  53560. BABYLON.serialize()
  53561. ], ColorCurves.prototype, "_globalDensity", void 0);
  53562. __decorate([
  53563. BABYLON.serialize()
  53564. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53565. __decorate([
  53566. BABYLON.serialize()
  53567. ], ColorCurves.prototype, "_globalExposure", void 0);
  53568. __decorate([
  53569. BABYLON.serialize()
  53570. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53571. __decorate([
  53572. BABYLON.serialize()
  53573. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53574. __decorate([
  53575. BABYLON.serialize()
  53576. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53577. __decorate([
  53578. BABYLON.serialize()
  53579. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53580. __decorate([
  53581. BABYLON.serialize()
  53582. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53583. __decorate([
  53584. BABYLON.serialize()
  53585. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53586. __decorate([
  53587. BABYLON.serialize()
  53588. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53589. __decorate([
  53590. BABYLON.serialize()
  53591. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53592. BABYLON.ColorCurves = ColorCurves;
  53593. })(BABYLON || (BABYLON = {}));
  53594. //# sourceMappingURL=babylon.colorCurves.js.map
  53595. var BABYLON;
  53596. (function (BABYLON) {
  53597. var PBRMaterialDefines = (function (_super) {
  53598. __extends(PBRMaterialDefines, _super);
  53599. function PBRMaterialDefines() {
  53600. var _this = _super.call(this) || this;
  53601. _this.ALBEDO = false;
  53602. _this.AMBIENT = false;
  53603. _this.OPACITY = false;
  53604. _this.OPACITYRGB = false;
  53605. _this.REFLECTION = false;
  53606. _this.EMISSIVE = false;
  53607. _this.REFLECTIVITY = false;
  53608. _this.BUMP = false;
  53609. _this.PARALLAX = false;
  53610. _this.PARALLAXOCCLUSION = false;
  53611. _this.SPECULAROVERALPHA = false;
  53612. _this.CLIPPLANE = false;
  53613. _this.ALPHATEST = false;
  53614. _this.ALPHAFROMALBEDO = false;
  53615. _this.POINTSIZE = false;
  53616. _this.FOG = false;
  53617. _this.SPECULARTERM = false;
  53618. _this.OPACITYFRESNEL = false;
  53619. _this.EMISSIVEFRESNEL = false;
  53620. _this.FRESNEL = false;
  53621. _this.NORMAL = false;
  53622. _this.UV1 = false;
  53623. _this.UV2 = false;
  53624. _this.VERTEXCOLOR = false;
  53625. _this.VERTEXALPHA = false;
  53626. _this.NUM_BONE_INFLUENCERS = 0;
  53627. _this.BonesPerMesh = 0;
  53628. _this.INSTANCES = false;
  53629. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53630. _this.MICROSURFACEAUTOMATIC = false;
  53631. _this.EMISSIVEASILLUMINATION = false;
  53632. _this.LINKEMISSIVEWITHALBEDO = false;
  53633. _this.LIGHTMAP = false;
  53634. _this.USELIGHTMAPASSHADOWMAP = false;
  53635. _this.REFLECTIONMAP_3D = false;
  53636. _this.REFLECTIONMAP_SPHERICAL = false;
  53637. _this.REFLECTIONMAP_PLANAR = false;
  53638. _this.REFLECTIONMAP_CUBIC = false;
  53639. _this.REFLECTIONMAP_PROJECTION = false;
  53640. _this.REFLECTIONMAP_SKYBOX = false;
  53641. _this.REFLECTIONMAP_EXPLICIT = false;
  53642. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53643. _this.INVERTCUBICMAP = false;
  53644. _this.LOGARITHMICDEPTH = false;
  53645. _this.CAMERATONEMAP = false;
  53646. _this.CAMERACONTRAST = false;
  53647. _this.CAMERACOLORGRADING = false;
  53648. _this.CAMERACOLORCURVES = false;
  53649. _this.OVERLOADEDVALUES = false;
  53650. _this.OVERLOADEDSHADOWVALUES = false;
  53651. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53652. _this.REFRACTION = false;
  53653. _this.REFRACTIONMAP_3D = false;
  53654. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53655. _this.REFRACTIONMAPINLINEARSPACE = false;
  53656. _this.LODBASEDMICROSFURACE = false;
  53657. _this.USEPHYSICALLIGHTFALLOFF = false;
  53658. _this.RADIANCEOVERALPHA = false;
  53659. _this.USEPMREMREFLECTION = false;
  53660. _this.USEPMREMREFRACTION = false;
  53661. _this.OPENGLNORMALMAP = false;
  53662. _this.INVERTNORMALMAPX = false;
  53663. _this.INVERTNORMALMAPY = false;
  53664. _this.SHADOWFULLFLOAT = false;
  53665. _this.METALLICWORKFLOW = false;
  53666. _this.METALLICROUGHNESSMAP = false;
  53667. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53668. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53669. _this.rebuild();
  53670. return _this;
  53671. }
  53672. return PBRMaterialDefines;
  53673. }(BABYLON.MaterialDefines));
  53674. /**
  53675. * The Physically based material of BJS.
  53676. *
  53677. * This offers the main features of a standard PBR material.
  53678. * For more information, please refer to the documentation :
  53679. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53680. */
  53681. var PBRMaterial = (function (_super) {
  53682. __extends(PBRMaterial, _super);
  53683. /**
  53684. * Instantiates a new PBRMaterial instance.
  53685. *
  53686. * @param name The material name
  53687. * @param scene The scene the material will be use in.
  53688. */
  53689. function PBRMaterial(name, scene) {
  53690. var _this = _super.call(this, name, scene) || this;
  53691. /**
  53692. * Intensity of the direct lights e.g. the four lights available in your scene.
  53693. * This impacts both the direct diffuse and specular highlights.
  53694. */
  53695. _this.directIntensity = 1.0;
  53696. /**
  53697. * Intensity of the emissive part of the material.
  53698. * This helps controlling the emissive effect without modifying the emissive color.
  53699. */
  53700. _this.emissiveIntensity = 1.0;
  53701. /**
  53702. * Intensity of the environment e.g. how much the environment will light the object
  53703. * either through harmonics for rough material or through the refelction for shiny ones.
  53704. */
  53705. _this.environmentIntensity = 1.0;
  53706. /**
  53707. * This is a special control allowing the reduction of the specular highlights coming from the
  53708. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53709. */
  53710. _this.specularIntensity = 1.0;
  53711. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53712. /**
  53713. * Debug Control allowing disabling the bump map on this material.
  53714. */
  53715. _this.disableBumpMap = false;
  53716. /**
  53717. * Debug Control helping enforcing or dropping the darkness of shadows.
  53718. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53719. */
  53720. _this.overloadedShadowIntensity = 1.0;
  53721. /**
  53722. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53723. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53724. */
  53725. _this.overloadedShadeIntensity = 1.0;
  53726. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53727. /**
  53728. * The camera exposure used on this material.
  53729. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53730. * This corresponds to a photographic exposure.
  53731. */
  53732. _this.cameraExposure = 1.0;
  53733. /**
  53734. * The camera contrast used on this material.
  53735. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53736. */
  53737. _this.cameraContrast = 1.0;
  53738. /**
  53739. * Color Grading 2D Lookup Texture.
  53740. * This allows special effects like sepia, black and white to sixties rendering style.
  53741. */
  53742. _this.cameraColorGradingTexture = null;
  53743. /**
  53744. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53745. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53746. * 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;
  53747. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53748. */
  53749. _this.cameraColorCurves = null;
  53750. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53751. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53752. /**
  53753. * Debug Control allowing to overload the ambient color.
  53754. * This as to be use with the overloadedAmbientIntensity parameter.
  53755. */
  53756. _this.overloadedAmbient = BABYLON.Color3.White();
  53757. /**
  53758. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53759. */
  53760. _this.overloadedAmbientIntensity = 0.0;
  53761. /**
  53762. * Debug Control allowing to overload the albedo color.
  53763. * This as to be use with the overloadedAlbedoIntensity parameter.
  53764. */
  53765. _this.overloadedAlbedo = BABYLON.Color3.White();
  53766. /**
  53767. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53768. */
  53769. _this.overloadedAlbedoIntensity = 0.0;
  53770. /**
  53771. * Debug Control allowing to overload the reflectivity color.
  53772. * This as to be use with the overloadedReflectivityIntensity parameter.
  53773. */
  53774. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53775. /**
  53776. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53777. */
  53778. _this.overloadedReflectivityIntensity = 0.0;
  53779. /**
  53780. * Debug Control allowing to overload the emissive color.
  53781. * This as to be use with the overloadedEmissiveIntensity parameter.
  53782. */
  53783. _this.overloadedEmissive = BABYLON.Color3.White();
  53784. /**
  53785. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53786. */
  53787. _this.overloadedEmissiveIntensity = 0.0;
  53788. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53789. /**
  53790. * Debug Control allowing to overload the reflection color.
  53791. * This as to be use with the overloadedReflectionIntensity parameter.
  53792. */
  53793. _this.overloadedReflection = BABYLON.Color3.White();
  53794. /**
  53795. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53796. */
  53797. _this.overloadedReflectionIntensity = 0.0;
  53798. /**
  53799. * Debug Control allowing to overload the microsurface.
  53800. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53801. */
  53802. _this.overloadedMicroSurface = 0.0;
  53803. /**
  53804. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53805. */
  53806. _this.overloadedMicroSurfaceIntensity = 0.0;
  53807. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53808. /**
  53809. * AKA Occlusion Texture Intensity in other nomenclature.
  53810. */
  53811. _this.ambientTextureStrength = 1.0;
  53812. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53813. /**
  53814. * AKA Diffuse Color in other nomenclature.
  53815. */
  53816. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53817. /**
  53818. * AKA Specular Color in other nomenclature.
  53819. */
  53820. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53821. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53822. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53823. /**
  53824. * AKA Glossiness in other nomenclature.
  53825. */
  53826. _this.microSurface = 0.9;
  53827. /**
  53828. * source material index of refraction (IOR)' / 'destination material IOR.
  53829. */
  53830. _this.indexOfRefraction = 0.66;
  53831. /**
  53832. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53833. */
  53834. _this.invertRefractionY = false;
  53835. /**
  53836. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53837. * Materials half opaque for instance using refraction could benefit from this control.
  53838. */
  53839. _this.linkRefractionWithTransparency = false;
  53840. /**
  53841. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53842. */
  53843. _this.linkEmissiveWithAlbedo = false;
  53844. _this.useLightmapAsShadowmap = false;
  53845. /**
  53846. * In this mode, the emissive informtaion will always be added to the lighting once.
  53847. * A light for instance can be thought as emissive.
  53848. */
  53849. _this.useEmissiveAsIllumination = false;
  53850. /**
  53851. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53852. */
  53853. _this.useAlphaFromAlbedoTexture = false;
  53854. /**
  53855. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53856. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53857. */
  53858. _this.useSpecularOverAlpha = true;
  53859. /**
  53860. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53861. */
  53862. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53863. /**
  53864. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53865. */
  53866. _this.useRoughnessFromMetallicTextureAlpha = true;
  53867. /**
  53868. * Specifies if the metallic texture contains the roughness information in its green channel.
  53869. */
  53870. _this.useRoughnessFromMetallicTextureGreen = false;
  53871. /**
  53872. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53873. * The material will try to infer what glossiness each pixel should be.
  53874. */
  53875. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53876. /**
  53877. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53878. * the creation of the material.
  53879. */
  53880. _this.useScalarInLinearSpace = false;
  53881. /**
  53882. * BJS is using an harcoded light falloff based on a manually sets up range.
  53883. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53884. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53885. */
  53886. _this.usePhysicalLightFalloff = true;
  53887. /**
  53888. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53889. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53890. */
  53891. _this.useRadianceOverAlpha = true;
  53892. /**
  53893. * Allows using the bump map in parallax mode.
  53894. */
  53895. _this.useParallax = false;
  53896. /**
  53897. * Allows using the bump map in parallax occlusion mode.
  53898. */
  53899. _this.useParallaxOcclusion = false;
  53900. /**
  53901. * Controls the scale bias of the parallax mode.
  53902. */
  53903. _this.parallaxScaleBias = 0.05;
  53904. /**
  53905. * If sets to true, disables all the lights affecting the material.
  53906. */
  53907. _this.disableLighting = false;
  53908. /**
  53909. * Number of Simultaneous lights allowed on the material.
  53910. */
  53911. _this.maxSimultaneousLights = 4;
  53912. /**
  53913. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53914. */
  53915. _this.invertNormalMapX = false;
  53916. /**
  53917. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53918. */
  53919. _this.invertNormalMapY = false;
  53920. _this._renderTargets = new BABYLON.SmartArray(16);
  53921. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53922. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53923. _this._tempColor = new BABYLON.Color3();
  53924. _this._defines = new PBRMaterialDefines();
  53925. _this._cachedDefines = new PBRMaterialDefines();
  53926. _this._myScene = null;
  53927. _this._myShadowGenerator = null;
  53928. _this._cachedDefines.BonesPerMesh = -1;
  53929. _this.getRenderTargetTextures = function () {
  53930. _this._renderTargets.reset();
  53931. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53932. _this._renderTargets.push(_this.reflectionTexture);
  53933. }
  53934. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53935. _this._renderTargets.push(_this.refractionTexture);
  53936. }
  53937. return _this._renderTargets;
  53938. };
  53939. return _this;
  53940. }
  53941. PBRMaterial.prototype.getClassName = function () {
  53942. return "PBRMaterial";
  53943. };
  53944. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53945. get: function () {
  53946. return this._useLogarithmicDepth;
  53947. },
  53948. set: function (value) {
  53949. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53950. },
  53951. enumerable: true,
  53952. configurable: true
  53953. });
  53954. PBRMaterial.prototype.needAlphaBlending = function () {
  53955. if (this.linkRefractionWithTransparency) {
  53956. return false;
  53957. }
  53958. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53959. };
  53960. PBRMaterial.prototype.needAlphaTesting = function () {
  53961. if (this.linkRefractionWithTransparency) {
  53962. return false;
  53963. }
  53964. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53965. };
  53966. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53967. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53968. };
  53969. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53970. return this.albedoTexture;
  53971. };
  53972. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53973. if (!mesh) {
  53974. return true;
  53975. }
  53976. if (this._defines.INSTANCES !== useInstances) {
  53977. return false;
  53978. }
  53979. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53980. return true;
  53981. }
  53982. return false;
  53983. };
  53984. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53985. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53986. };
  53987. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53988. if (!useScalarInLinear) {
  53989. color.toLinearSpaceToRef(ref);
  53990. }
  53991. else {
  53992. ref.r = color.r;
  53993. ref.g = color.g;
  53994. ref.b = color.b;
  53995. }
  53996. };
  53997. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53998. var lightIndex = 0;
  53999. var depthValuesAlreadySet = false;
  54000. for (var index = 0; index < scene.lights.length; index++) {
  54001. var light = scene.lights[index];
  54002. if (!light.isEnabled()) {
  54003. continue;
  54004. }
  54005. if (!light.canAffectMesh(mesh)) {
  54006. continue;
  54007. }
  54008. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  54009. // GAMMA CORRECTION.
  54010. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  54011. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  54012. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  54013. if (defines["SPECULARTERM"]) {
  54014. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  54015. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  54016. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  54017. }
  54018. // Shadows
  54019. if (scene.shadowsEnabled) {
  54020. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  54021. }
  54022. lightIndex++;
  54023. if (lightIndex === maxSimultaneousLights)
  54024. break;
  54025. }
  54026. };
  54027. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  54028. if (this.isFrozen) {
  54029. if (this._wasPreviouslyReady) {
  54030. return true;
  54031. }
  54032. }
  54033. var scene = this.getScene();
  54034. var engine = scene.getEngine();
  54035. var needNormals = false;
  54036. var needUVs = false;
  54037. this._defines.reset();
  54038. if (scene.lightsEnabled && !this.disableLighting) {
  54039. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  54040. }
  54041. if (!this.checkReadyOnEveryCall) {
  54042. if (this._renderId === scene.getRenderId()) {
  54043. if (this._checkCache(scene, mesh, useInstances)) {
  54044. return true;
  54045. }
  54046. }
  54047. }
  54048. if (scene.texturesEnabled) {
  54049. if (scene.getEngine().getCaps().textureLOD) {
  54050. this._defines.LODBASEDMICROSFURACE = true;
  54051. }
  54052. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54053. if (!this.albedoTexture.isReady()) {
  54054. return false;
  54055. }
  54056. else {
  54057. needUVs = true;
  54058. this._defines.ALBEDO = true;
  54059. }
  54060. }
  54061. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54062. if (!this.ambientTexture.isReady()) {
  54063. return false;
  54064. }
  54065. else {
  54066. needUVs = true;
  54067. this._defines.AMBIENT = true;
  54068. }
  54069. }
  54070. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54071. if (!this.opacityTexture.isReady()) {
  54072. return false;
  54073. }
  54074. else {
  54075. needUVs = true;
  54076. this._defines.OPACITY = true;
  54077. if (this.opacityTexture.getAlphaFromRGB) {
  54078. this._defines.OPACITYRGB = true;
  54079. }
  54080. }
  54081. }
  54082. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54083. if (!this.reflectionTexture.isReady()) {
  54084. return false;
  54085. }
  54086. else {
  54087. needNormals = true;
  54088. this._defines.REFLECTION = true;
  54089. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  54090. this._defines.INVERTCUBICMAP = true;
  54091. }
  54092. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  54093. switch (this.reflectionTexture.coordinatesMode) {
  54094. case BABYLON.Texture.CUBIC_MODE:
  54095. case BABYLON.Texture.INVCUBIC_MODE:
  54096. this._defines.REFLECTIONMAP_CUBIC = true;
  54097. break;
  54098. case BABYLON.Texture.EXPLICIT_MODE:
  54099. this._defines.REFLECTIONMAP_EXPLICIT = true;
  54100. break;
  54101. case BABYLON.Texture.PLANAR_MODE:
  54102. this._defines.REFLECTIONMAP_PLANAR = true;
  54103. break;
  54104. case BABYLON.Texture.PROJECTION_MODE:
  54105. this._defines.REFLECTIONMAP_PROJECTION = true;
  54106. break;
  54107. case BABYLON.Texture.SKYBOX_MODE:
  54108. this._defines.REFLECTIONMAP_SKYBOX = true;
  54109. break;
  54110. case BABYLON.Texture.SPHERICAL_MODE:
  54111. this._defines.REFLECTIONMAP_SPHERICAL = true;
  54112. break;
  54113. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  54114. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  54115. break;
  54116. }
  54117. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  54118. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  54119. needNormals = true;
  54120. if (this.reflectionTexture.isPMREM) {
  54121. this._defines.USEPMREMREFLECTION = true;
  54122. }
  54123. }
  54124. }
  54125. }
  54126. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54127. if (!this.lightmapTexture.isReady()) {
  54128. return false;
  54129. }
  54130. else {
  54131. needUVs = true;
  54132. this._defines.LIGHTMAP = true;
  54133. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  54134. }
  54135. }
  54136. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54137. if (!this.emissiveTexture.isReady()) {
  54138. return false;
  54139. }
  54140. else {
  54141. needUVs = true;
  54142. this._defines.EMISSIVE = true;
  54143. }
  54144. }
  54145. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54146. if (this.metallicTexture) {
  54147. if (!this.metallicTexture.isReady()) {
  54148. return false;
  54149. }
  54150. else {
  54151. needUVs = true;
  54152. this._defines.METALLICWORKFLOW = true;
  54153. this._defines.METALLICROUGHNESSMAP = true;
  54154. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  54155. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  54156. }
  54157. }
  54158. else if (this.reflectivityTexture) {
  54159. if (!this.reflectivityTexture.isReady()) {
  54160. return false;
  54161. }
  54162. else {
  54163. needUVs = true;
  54164. this._defines.REFLECTIVITY = true;
  54165. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  54166. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  54167. }
  54168. }
  54169. }
  54170. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54171. if (!this.bumpTexture.isReady()) {
  54172. return false;
  54173. }
  54174. else {
  54175. needUVs = true;
  54176. this._defines.BUMP = true;
  54177. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54178. this._defines.PARALLAX = true;
  54179. if (this.useParallaxOcclusion) {
  54180. this._defines.PARALLAXOCCLUSION = true;
  54181. }
  54182. }
  54183. if (this.invertNormalMapX) {
  54184. this._defines.INVERTNORMALMAPX = true;
  54185. }
  54186. if (this.invertNormalMapY) {
  54187. this._defines.INVERTNORMALMAPY = true;
  54188. }
  54189. if (scene._mirroredCameraPosition) {
  54190. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  54191. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  54192. }
  54193. }
  54194. }
  54195. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54196. if (!this.refractionTexture.isReady()) {
  54197. return false;
  54198. }
  54199. else {
  54200. needUVs = true;
  54201. this._defines.REFRACTION = true;
  54202. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  54203. if (this.linkRefractionWithTransparency) {
  54204. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  54205. }
  54206. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  54207. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  54208. if (this.refractionTexture.isPMREM) {
  54209. this._defines.USEPMREMREFRACTION = true;
  54210. }
  54211. }
  54212. }
  54213. }
  54214. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54215. if (!this.cameraColorGradingTexture.isReady()) {
  54216. return false;
  54217. }
  54218. else {
  54219. this._defines.CAMERACOLORGRADING = true;
  54220. }
  54221. }
  54222. }
  54223. // Effect
  54224. if (scene.clipPlane) {
  54225. this._defines.CLIPPLANE = true;
  54226. }
  54227. if (engine.getAlphaTesting()) {
  54228. this._defines.ALPHATEST = true;
  54229. }
  54230. if (this._shouldUseAlphaFromAlbedoTexture()) {
  54231. this._defines.ALPHAFROMALBEDO = true;
  54232. }
  54233. if (this.useEmissiveAsIllumination) {
  54234. this._defines.EMISSIVEASILLUMINATION = true;
  54235. }
  54236. if (this.linkEmissiveWithAlbedo) {
  54237. this._defines.LINKEMISSIVEWITHALBEDO = true;
  54238. }
  54239. if (this.useLogarithmicDepth) {
  54240. this._defines.LOGARITHMICDEPTH = true;
  54241. }
  54242. if (this.cameraContrast != 1) {
  54243. this._defines.CAMERACONTRAST = true;
  54244. }
  54245. if (this.cameraExposure != 1) {
  54246. this._defines.CAMERATONEMAP = true;
  54247. }
  54248. if (this.cameraColorCurves) {
  54249. this._defines.CAMERACOLORCURVES = true;
  54250. }
  54251. if (this.overloadedShadeIntensity != 1 ||
  54252. this.overloadedShadowIntensity != 1) {
  54253. this._defines.OVERLOADEDSHADOWVALUES = true;
  54254. }
  54255. if (this.overloadedMicroSurfaceIntensity > 0 ||
  54256. this.overloadedEmissiveIntensity > 0 ||
  54257. this.overloadedReflectivityIntensity > 0 ||
  54258. this.overloadedAlbedoIntensity > 0 ||
  54259. this.overloadedAmbientIntensity > 0 ||
  54260. this.overloadedReflectionIntensity > 0) {
  54261. this._defines.OVERLOADEDVALUES = true;
  54262. }
  54263. // Point size
  54264. if (this.pointsCloud || scene.forcePointsCloud) {
  54265. this._defines.POINTSIZE = true;
  54266. }
  54267. // Fog
  54268. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54269. this._defines.FOG = true;
  54270. }
  54271. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54272. // Fresnel
  54273. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  54274. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54275. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54276. this._defines.OPACITYFRESNEL = true;
  54277. }
  54278. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54279. this._defines.EMISSIVEFRESNEL = true;
  54280. }
  54281. needNormals = true;
  54282. this._defines.FRESNEL = true;
  54283. }
  54284. }
  54285. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  54286. this._defines.SPECULAROVERALPHA = true;
  54287. }
  54288. if (this.usePhysicalLightFalloff) {
  54289. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  54290. }
  54291. if (this.useRadianceOverAlpha) {
  54292. this._defines.RADIANCEOVERALPHA = true;
  54293. }
  54294. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  54295. this._defines.METALLICWORKFLOW = true;
  54296. }
  54297. // Attribs
  54298. if (mesh) {
  54299. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54300. this._defines.NORMAL = true;
  54301. }
  54302. if (needUVs) {
  54303. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54304. this._defines.UV1 = true;
  54305. }
  54306. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54307. this._defines.UV2 = true;
  54308. }
  54309. }
  54310. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54311. this._defines.VERTEXCOLOR = true;
  54312. if (mesh.hasVertexAlpha) {
  54313. this._defines.VERTEXALPHA = true;
  54314. }
  54315. }
  54316. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54317. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  54318. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  54319. }
  54320. // Instances
  54321. if (useInstances) {
  54322. this._defines.INSTANCES = true;
  54323. }
  54324. }
  54325. // Get correct effect
  54326. if (!this._defines.isEqual(this._cachedDefines)) {
  54327. this._defines.cloneTo(this._cachedDefines);
  54328. scene.resetCachedMaterial();
  54329. // Fallbacks
  54330. var fallbacks = new BABYLON.EffectFallbacks();
  54331. if (this._defines.REFLECTION) {
  54332. fallbacks.addFallback(0, "REFLECTION");
  54333. }
  54334. if (this._defines.REFRACTION) {
  54335. fallbacks.addFallback(0, "REFRACTION");
  54336. }
  54337. if (this._defines.REFLECTIVITY) {
  54338. fallbacks.addFallback(0, "REFLECTIVITY");
  54339. }
  54340. if (this._defines.BUMP) {
  54341. fallbacks.addFallback(0, "BUMP");
  54342. }
  54343. if (this._defines.PARALLAX) {
  54344. fallbacks.addFallback(1, "PARALLAX");
  54345. }
  54346. if (this._defines.PARALLAXOCCLUSION) {
  54347. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  54348. }
  54349. if (this._defines.SPECULAROVERALPHA) {
  54350. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  54351. }
  54352. if (this._defines.FOG) {
  54353. fallbacks.addFallback(1, "FOG");
  54354. }
  54355. if (this._defines.POINTSIZE) {
  54356. fallbacks.addFallback(0, "POINTSIZE");
  54357. }
  54358. if (this._defines.LOGARITHMICDEPTH) {
  54359. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  54360. }
  54361. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  54362. if (this._defines.SPECULARTERM) {
  54363. fallbacks.addFallback(0, "SPECULARTERM");
  54364. }
  54365. if (this._defines.OPACITYFRESNEL) {
  54366. fallbacks.addFallback(1, "OPACITYFRESNEL");
  54367. }
  54368. if (this._defines.EMISSIVEFRESNEL) {
  54369. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  54370. }
  54371. if (this._defines.FRESNEL) {
  54372. fallbacks.addFallback(3, "FRESNEL");
  54373. }
  54374. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  54375. fallbacks.addCPUSkinningFallback(0, mesh);
  54376. }
  54377. //Attributes
  54378. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54379. if (this._defines.NORMAL) {
  54380. attribs.push(BABYLON.VertexBuffer.NormalKind);
  54381. }
  54382. if (this._defines.UV1) {
  54383. attribs.push(BABYLON.VertexBuffer.UVKind);
  54384. }
  54385. if (this._defines.UV2) {
  54386. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54387. }
  54388. if (this._defines.VERTEXCOLOR) {
  54389. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54390. }
  54391. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  54392. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  54393. // Legacy browser patch
  54394. var join = this._defines.toString();
  54395. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  54396. "vFogInfos", "vFogColor", "pointSize",
  54397. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  54398. "mBones",
  54399. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  54400. "depthValues",
  54401. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  54402. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  54403. "logarithmicDepthConstant",
  54404. "vSphericalX", "vSphericalY", "vSphericalZ",
  54405. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  54406. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  54407. "vMicrosurfaceTextureLods",
  54408. "vCameraInfos"
  54409. ];
  54410. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  54411. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  54412. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  54413. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  54414. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  54415. }
  54416. if (!this._effect.isReady()) {
  54417. return false;
  54418. }
  54419. this._renderId = scene.getRenderId();
  54420. this._wasPreviouslyReady = true;
  54421. if (mesh) {
  54422. if (!mesh._materialDefines) {
  54423. mesh._materialDefines = new PBRMaterialDefines();
  54424. }
  54425. this._defines.cloneTo(mesh._materialDefines);
  54426. }
  54427. return true;
  54428. };
  54429. PBRMaterial.prototype.unbind = function () {
  54430. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  54431. this._effect.setTexture("reflection2DSampler", null);
  54432. }
  54433. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  54434. this._effect.setTexture("refraction2DSampler", null);
  54435. }
  54436. _super.prototype.unbind.call(this);
  54437. };
  54438. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54439. this._effect.setMatrix("world", world);
  54440. };
  54441. PBRMaterial.prototype.bind = function (world, mesh) {
  54442. this._myScene = this.getScene();
  54443. // Matrices
  54444. this.bindOnlyWorldMatrix(world);
  54445. // Bones
  54446. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54447. if (this._myScene.getCachedMaterial() !== this) {
  54448. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  54449. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54450. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54451. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  54452. }
  54453. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54454. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  54455. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  54456. }
  54457. }
  54458. // Textures
  54459. if (this._myScene.texturesEnabled) {
  54460. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54461. this._effect.setTexture("albedoSampler", this.albedoTexture);
  54462. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  54463. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  54464. }
  54465. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54466. this._effect.setTexture("ambientSampler", this.ambientTexture);
  54467. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  54468. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  54469. }
  54470. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54471. this._effect.setTexture("opacitySampler", this.opacityTexture);
  54472. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  54473. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  54474. }
  54475. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54476. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  54477. if (this.reflectionTexture.isCube) {
  54478. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  54479. }
  54480. else {
  54481. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  54482. }
  54483. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  54484. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  54485. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  54486. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  54487. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  54488. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  54489. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  54490. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  54491. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  54492. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  54493. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  54494. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  54495. }
  54496. }
  54497. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54498. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  54499. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  54500. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  54501. }
  54502. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54503. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  54504. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  54505. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  54506. }
  54507. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54508. if (this.metallicTexture) {
  54509. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  54510. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  54511. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  54512. }
  54513. else if (this.reflectivityTexture) {
  54514. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  54515. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  54516. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  54517. }
  54518. }
  54519. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54520. this._effect.setTexture("bumpSampler", this.bumpTexture);
  54521. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  54522. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  54523. }
  54524. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54525. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  54526. var depth = 1.0;
  54527. if (this.refractionTexture.isCube) {
  54528. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  54529. }
  54530. else {
  54531. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  54532. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  54533. if (this.refractionTexture.depth) {
  54534. depth = this.refractionTexture.depth;
  54535. }
  54536. }
  54537. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  54538. }
  54539. if ((this.reflectionTexture || this.refractionTexture)) {
  54540. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  54541. }
  54542. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54543. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54544. }
  54545. }
  54546. // Clip plane
  54547. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54548. // Point size
  54549. if (this.pointsCloud) {
  54550. this._effect.setFloat("pointSize", this.pointSize);
  54551. }
  54552. // Colors
  54553. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54554. if (this._defines.METALLICWORKFLOW) {
  54555. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54556. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54557. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54558. }
  54559. else {
  54560. // GAMMA CORRECTION.
  54561. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54562. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54563. }
  54564. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54565. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54566. // GAMMA CORRECTION.
  54567. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54568. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54569. // GAMMA CORRECTION.
  54570. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54571. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54572. }
  54573. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54574. // GAMMA CORRECTION.
  54575. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54576. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54577. // Lights
  54578. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54579. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54580. }
  54581. // View
  54582. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54583. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54584. }
  54585. // Fog
  54586. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54587. this._lightingInfos.x = this.directIntensity;
  54588. this._lightingInfos.y = this.emissiveIntensity;
  54589. this._lightingInfos.z = this.environmentIntensity;
  54590. this._lightingInfos.w = this.specularIntensity;
  54591. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54592. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54593. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54594. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54595. this._cameraInfos.x = this.cameraExposure;
  54596. this._cameraInfos.y = this.cameraContrast;
  54597. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54598. if (this.cameraColorCurves) {
  54599. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54600. }
  54601. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54602. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54603. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54604. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54605. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54606. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54607. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54608. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54609. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54610. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54611. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54612. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54613. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54614. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54615. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54616. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54617. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54618. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54619. // Log. depth
  54620. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54621. }
  54622. _super.prototype.bind.call(this, world, mesh);
  54623. this._myScene = null;
  54624. };
  54625. PBRMaterial.prototype.getAnimatables = function () {
  54626. var results = [];
  54627. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54628. results.push(this.albedoTexture);
  54629. }
  54630. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54631. results.push(this.ambientTexture);
  54632. }
  54633. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54634. results.push(this.opacityTexture);
  54635. }
  54636. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54637. results.push(this.reflectionTexture);
  54638. }
  54639. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54640. results.push(this.emissiveTexture);
  54641. }
  54642. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54643. results.push(this.metallicTexture);
  54644. }
  54645. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54646. results.push(this.reflectivityTexture);
  54647. }
  54648. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54649. results.push(this.bumpTexture);
  54650. }
  54651. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54652. results.push(this.lightmapTexture);
  54653. }
  54654. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54655. results.push(this.refractionTexture);
  54656. }
  54657. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54658. results.push(this.cameraColorGradingTexture);
  54659. }
  54660. return results;
  54661. };
  54662. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54663. if (forceDisposeTextures) {
  54664. if (this.albedoTexture) {
  54665. this.albedoTexture.dispose();
  54666. }
  54667. if (this.ambientTexture) {
  54668. this.ambientTexture.dispose();
  54669. }
  54670. if (this.opacityTexture) {
  54671. this.opacityTexture.dispose();
  54672. }
  54673. if (this.reflectionTexture) {
  54674. this.reflectionTexture.dispose();
  54675. }
  54676. if (this.emissiveTexture) {
  54677. this.emissiveTexture.dispose();
  54678. }
  54679. if (this.metallicTexture) {
  54680. this.metallicTexture.dispose();
  54681. }
  54682. if (this.reflectivityTexture) {
  54683. this.reflectivityTexture.dispose();
  54684. }
  54685. if (this.bumpTexture) {
  54686. this.bumpTexture.dispose();
  54687. }
  54688. if (this.lightmapTexture) {
  54689. this.lightmapTexture.dispose();
  54690. }
  54691. if (this.refractionTexture) {
  54692. this.refractionTexture.dispose();
  54693. }
  54694. if (this.cameraColorGradingTexture) {
  54695. this.cameraColorGradingTexture.dispose();
  54696. }
  54697. }
  54698. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54699. };
  54700. PBRMaterial.prototype.clone = function (name) {
  54701. var _this = this;
  54702. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54703. };
  54704. PBRMaterial.prototype.serialize = function () {
  54705. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54706. serializationObject.customType = "BABYLON.PBRMaterial";
  54707. return serializationObject;
  54708. };
  54709. // Statics
  54710. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54711. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54712. };
  54713. return PBRMaterial;
  54714. }(BABYLON.Material));
  54715. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54716. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54717. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54718. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54719. __decorate([
  54720. BABYLON.serialize()
  54721. ], PBRMaterial.prototype, "directIntensity", void 0);
  54722. __decorate([
  54723. BABYLON.serialize()
  54724. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54725. __decorate([
  54726. BABYLON.serialize()
  54727. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54728. __decorate([
  54729. BABYLON.serialize()
  54730. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54731. __decorate([
  54732. BABYLON.serialize()
  54733. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54734. __decorate([
  54735. BABYLON.serialize()
  54736. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54737. __decorate([
  54738. BABYLON.serialize()
  54739. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54740. __decorate([
  54741. BABYLON.serialize()
  54742. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54743. __decorate([
  54744. BABYLON.serialize()
  54745. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54746. __decorate([
  54747. BABYLON.serializeAsTexture()
  54748. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54749. __decorate([
  54750. BABYLON.serializeAsColorCurves()
  54751. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54752. __decorate([
  54753. BABYLON.serializeAsColor3()
  54754. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54755. __decorate([
  54756. BABYLON.serialize()
  54757. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54758. __decorate([
  54759. BABYLON.serializeAsColor3()
  54760. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54761. __decorate([
  54762. BABYLON.serialize()
  54763. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54764. __decorate([
  54765. BABYLON.serializeAsColor3()
  54766. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54767. __decorate([
  54768. BABYLON.serialize()
  54769. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54770. __decorate([
  54771. BABYLON.serializeAsColor3()
  54772. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54773. __decorate([
  54774. BABYLON.serialize()
  54775. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54776. __decorate([
  54777. BABYLON.serializeAsColor3()
  54778. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54779. __decorate([
  54780. BABYLON.serialize()
  54781. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54782. __decorate([
  54783. BABYLON.serialize()
  54784. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54785. __decorate([
  54786. BABYLON.serialize()
  54787. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54788. __decorate([
  54789. BABYLON.serializeAsTexture()
  54790. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54791. __decorate([
  54792. BABYLON.serializeAsTexture()
  54793. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54794. __decorate([
  54795. BABYLON.serialize()
  54796. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54797. __decorate([
  54798. BABYLON.serializeAsTexture()
  54799. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54800. __decorate([
  54801. BABYLON.serializeAsTexture()
  54802. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54803. __decorate([
  54804. BABYLON.serializeAsTexture()
  54805. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54806. __decorate([
  54807. BABYLON.serializeAsTexture()
  54808. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54809. __decorate([
  54810. BABYLON.serializeAsTexture()
  54811. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54812. __decorate([
  54813. BABYLON.serialize()
  54814. ], PBRMaterial.prototype, "metallic", void 0);
  54815. __decorate([
  54816. BABYLON.serialize()
  54817. ], PBRMaterial.prototype, "roughness", void 0);
  54818. __decorate([
  54819. BABYLON.serializeAsTexture()
  54820. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54821. __decorate([
  54822. BABYLON.serializeAsTexture()
  54823. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54824. __decorate([
  54825. BABYLON.serializeAsTexture()
  54826. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54827. __decorate([
  54828. BABYLON.serializeAsColor3("ambient")
  54829. ], PBRMaterial.prototype, "ambientColor", void 0);
  54830. __decorate([
  54831. BABYLON.serializeAsColor3("albedo")
  54832. ], PBRMaterial.prototype, "albedoColor", void 0);
  54833. __decorate([
  54834. BABYLON.serializeAsColor3("reflectivity")
  54835. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54836. __decorate([
  54837. BABYLON.serializeAsColor3("reflection")
  54838. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54839. __decorate([
  54840. BABYLON.serializeAsColor3("emissive")
  54841. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54842. __decorate([
  54843. BABYLON.serialize()
  54844. ], PBRMaterial.prototype, "microSurface", void 0);
  54845. __decorate([
  54846. BABYLON.serialize()
  54847. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54848. __decorate([
  54849. BABYLON.serialize()
  54850. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54851. __decorate([
  54852. BABYLON.serializeAsFresnelParameters()
  54853. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54854. __decorate([
  54855. BABYLON.serializeAsFresnelParameters()
  54856. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54857. __decorate([
  54858. BABYLON.serialize()
  54859. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54860. __decorate([
  54861. BABYLON.serialize()
  54862. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54863. __decorate([
  54864. BABYLON.serialize()
  54865. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54866. __decorate([
  54867. BABYLON.serialize()
  54868. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54869. __decorate([
  54870. BABYLON.serialize()
  54871. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54872. __decorate([
  54873. BABYLON.serialize()
  54874. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54875. __decorate([
  54876. BABYLON.serialize()
  54877. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54878. __decorate([
  54879. BABYLON.serialize()
  54880. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54881. __decorate([
  54882. BABYLON.serialize()
  54883. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54884. __decorate([
  54885. BABYLON.serialize()
  54886. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54887. __decorate([
  54888. BABYLON.serialize()
  54889. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54890. __decorate([
  54891. BABYLON.serialize()
  54892. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54893. __decorate([
  54894. BABYLON.serialize()
  54895. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54896. __decorate([
  54897. BABYLON.serialize()
  54898. ], PBRMaterial.prototype, "useParallax", void 0);
  54899. __decorate([
  54900. BABYLON.serialize()
  54901. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54902. __decorate([
  54903. BABYLON.serialize()
  54904. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54905. __decorate([
  54906. BABYLON.serialize()
  54907. ], PBRMaterial.prototype, "disableLighting", void 0);
  54908. __decorate([
  54909. BABYLON.serialize()
  54910. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54911. __decorate([
  54912. BABYLON.serialize()
  54913. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54914. __decorate([
  54915. BABYLON.serialize()
  54916. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54917. __decorate([
  54918. BABYLON.serialize()
  54919. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54920. BABYLON.PBRMaterial = PBRMaterial;
  54921. })(BABYLON || (BABYLON = {}));
  54922. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54923. var BABYLON;
  54924. (function (BABYLON) {
  54925. var DebugLayer = (function () {
  54926. function DebugLayer(scene) {
  54927. this._scene = scene;
  54928. }
  54929. /** Creates the inspector window. */
  54930. DebugLayer.prototype._createInspector = function (popup) {
  54931. if (!this._inspector) {
  54932. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54933. } // else nothing to do,; instance is already existing
  54934. };
  54935. DebugLayer.prototype.isVisible = function () {
  54936. return false;
  54937. };
  54938. DebugLayer.prototype.hide = function () {
  54939. if (this._inspector) {
  54940. this._inspector.dispose();
  54941. this._inspector = null;
  54942. }
  54943. };
  54944. DebugLayer.prototype.show = function (popup) {
  54945. if (typeof INSPECTOR == 'undefined') {
  54946. // Load inspector and add it to the DOM
  54947. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54948. }
  54949. else {
  54950. // Otherwise creates the inspector
  54951. this._createInspector(popup);
  54952. }
  54953. };
  54954. return DebugLayer;
  54955. }());
  54956. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54957. BABYLON.DebugLayer = DebugLayer;
  54958. })(BABYLON || (BABYLON = {}));
  54959. //# sourceMappingURL=babylon.debugLayer.js.map
  54960. var BABYLON;
  54961. (function (BABYLON) {
  54962. var StandardRenderingPipeline = (function (_super) {
  54963. __extends(StandardRenderingPipeline, _super);
  54964. /**
  54965. * @constructor
  54966. * @param {string} name - The rendering pipeline name
  54967. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54968. * @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)
  54969. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54970. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54971. */
  54972. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54973. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54974. var _this = _super.call(this, scene.getEngine(), name) || this;
  54975. _this.downSampleX4PostProcess = null;
  54976. _this.brightPassPostProcess = null;
  54977. _this.gaussianBlurHPostProcesses = [];
  54978. _this.gaussianBlurVPostProcesses = [];
  54979. _this.textureAdderPostProcess = null;
  54980. _this.textureAdderFinalPostProcess = null;
  54981. _this.lensFlarePostProcess = null;
  54982. _this.lensFlareComposePostProcess = null;
  54983. _this.depthOfFieldPostProcess = null;
  54984. // Values
  54985. _this.brightThreshold = 1.0;
  54986. _this.blurWidth = 2.0;
  54987. _this.gaussianCoefficient = 0.25;
  54988. _this.gaussianMean = 1.0;
  54989. _this.gaussianStandardDeviation = 1.0;
  54990. _this.exposure = 1.0;
  54991. _this.lensTexture = null;
  54992. _this.lensColorTexture = null;
  54993. _this.lensFlareStrength = 20.0;
  54994. _this.lensFlareGhostDispersal = 1.4;
  54995. _this.lensFlareHaloWidth = 0.7;
  54996. _this.lensFlareDistortionStrength = 16.0;
  54997. _this.lensStarTexture = null;
  54998. _this.lensFlareDirtTexture = null;
  54999. _this.depthOfFieldDistance = 10.0;
  55000. // IAnimatable
  55001. _this.animations = [];
  55002. _this._depthRenderer = null;
  55003. // Getters and setters
  55004. _this._depthOfFieldEnabled = true;
  55005. _this._lensFlareEnabled = true;
  55006. // Initialize
  55007. _this._scene = scene;
  55008. // Create pass post-processe
  55009. if (!originalPostProcess) {
  55010. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  55011. }
  55012. else {
  55013. _this.originalPostProcess = originalPostProcess;
  55014. }
  55015. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  55016. // Create down sample X4 post-process
  55017. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  55018. // Create bright pass post-process
  55019. _this._createBrightPassPostProcess(scene, ratio / 2);
  55020. // Create gaussian blur post-processes (down sampling blurs)
  55021. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  55022. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  55023. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  55024. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  55025. // Create texture adder post-process
  55026. _this._createTextureAdderPostProcess(scene, ratio);
  55027. // Create depth-of-field source post-process
  55028. _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);
  55029. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  55030. // Create lens flare post-process
  55031. _this._createLensFlarePostProcess(scene, ratio);
  55032. // Create gaussian blur used by depth-of-field
  55033. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  55034. // Create depth-of-field post-process
  55035. _this._createDepthOfFieldPostProcess(scene, ratio);
  55036. // Finish
  55037. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55038. if (cameras !== null) {
  55039. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55040. }
  55041. // Deactivate
  55042. _this.LensFlareEnabled = false;
  55043. _this.DepthOfFieldEnabled = false;
  55044. return _this;
  55045. }
  55046. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  55047. get: function () {
  55048. return this._depthOfFieldEnabled;
  55049. },
  55050. set: function (enabled) {
  55051. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  55052. if (enabled && !this._depthOfFieldEnabled) {
  55053. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55054. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55055. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55056. this._depthRenderer = this._scene.enableDepthRenderer();
  55057. }
  55058. else if (!enabled && this._depthOfFieldEnabled) {
  55059. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55060. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55061. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55062. }
  55063. this._depthOfFieldEnabled = enabled;
  55064. },
  55065. enumerable: true,
  55066. configurable: true
  55067. });
  55068. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  55069. get: function () {
  55070. return this._lensFlareEnabled;
  55071. },
  55072. set: function (enabled) {
  55073. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  55074. if (enabled && !this._lensFlareEnabled) {
  55075. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55076. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55077. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55078. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55079. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55080. }
  55081. else if (!enabled && this._lensFlareEnabled) {
  55082. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55083. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55084. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55085. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55086. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55087. }
  55088. this._lensFlareEnabled = enabled;
  55089. },
  55090. enumerable: true,
  55091. configurable: true
  55092. });
  55093. // Down Sample X4 Post-Processs
  55094. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55095. var _this = this;
  55096. var downSampleX4Offsets = new Array(32);
  55097. 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);
  55098. this.downSampleX4PostProcess.onApply = function (effect) {
  55099. var id = 0;
  55100. for (var i = -2; i < 2; i++) {
  55101. for (var j = -2; j < 2; j++) {
  55102. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  55103. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  55104. id += 2;
  55105. }
  55106. }
  55107. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55108. };
  55109. // Add to pipeline
  55110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  55111. };
  55112. // Brightpass Post-Process
  55113. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55114. var _this = this;
  55115. var brightOffsets = new Array(8);
  55116. 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);
  55117. this.brightPassPostProcess.onApply = function (effect) {
  55118. var sU = (1.0 / _this.brightPassPostProcess.width);
  55119. var sV = (1.0 / _this.brightPassPostProcess.height);
  55120. brightOffsets[0] = -0.5 * sU;
  55121. brightOffsets[1] = 0.5 * sV;
  55122. brightOffsets[2] = 0.5 * sU;
  55123. brightOffsets[3] = 0.5 * sV;
  55124. brightOffsets[4] = -0.5 * sU;
  55125. brightOffsets[5] = -0.5 * sV;
  55126. brightOffsets[6] = 0.5 * sU;
  55127. brightOffsets[7] = -0.5 * sV;
  55128. effect.setArray2("dsOffsets", brightOffsets);
  55129. effect.setFloat("brightThreshold", _this.brightThreshold);
  55130. };
  55131. // Add to pipeline
  55132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  55133. };
  55134. // Create gaussian blur H&V post-processes
  55135. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  55136. var _this = this;
  55137. var blurOffsets = new Array(9);
  55138. var blurWeights = new Array(9);
  55139. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  55140. var callback = function (height) {
  55141. return function (effect) {
  55142. // Weights
  55143. var x = 0.0;
  55144. for (var i = 0; i < 9; i++) {
  55145. x = (i - 4.0) / 4.0;
  55146. blurWeights[i] =
  55147. _this.gaussianCoefficient
  55148. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  55149. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  55150. }
  55151. var lastOutputDimensions = {
  55152. width: scene.getEngine().getRenderWidth(),
  55153. height: scene.getEngine().getRenderHeight()
  55154. };
  55155. for (var i = 0; i < 9; i++) {
  55156. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55157. blurOffsets[i] = value;
  55158. }
  55159. effect.setArray("blurOffsets", blurOffsets);
  55160. effect.setArray("blurWeights", blurWeights);
  55161. effect.setFloat("blurWidth", _this.blurWidth);
  55162. };
  55163. };
  55164. // Create horizontal gaussian blur post-processes
  55165. 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);
  55166. gaussianBlurHPostProcess.onApply = callback(false);
  55167. // Create vertical gaussian blur post-process
  55168. 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);
  55169. gaussianBlurVPostProcess.onApply = callback(true);
  55170. // Add to pipeline
  55171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  55172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  55173. // Finish
  55174. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  55175. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  55176. };
  55177. // Create texture adder post-process
  55178. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55179. var _this = this;
  55180. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  55181. 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);
  55182. this.textureAdderPostProcess.onApply = function (effect) {
  55183. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  55184. effect.setTexture("lensSampler", _this.lensTexture);
  55185. effect.setFloat("exposure", _this.exposure);
  55186. };
  55187. // Add to pipeline
  55188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  55189. };
  55190. // Create lens flare post-process
  55191. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55192. var _this = this;
  55193. 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);
  55194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  55195. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  55196. 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);
  55197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  55198. var resolution = new BABYLON.Vector2(0, 0);
  55199. // Lens flare
  55200. this.lensFlarePostProcess.onApply = function (effect) {
  55201. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  55202. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55203. effect.setFloat("strength", _this.lensFlareStrength);
  55204. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55205. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55206. // Shift
  55207. resolution.x = _this.lensFlarePostProcess.width;
  55208. resolution.y = _this.lensFlarePostProcess.height;
  55209. effect.setVector2("resolution", resolution);
  55210. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55211. };
  55212. // Compose
  55213. 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);
  55214. 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);
  55215. this.lensFlareComposePostProcess.onApply = function (effect) {
  55216. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55217. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55218. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55219. // Lens start rotation matrix
  55220. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55221. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55222. 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));
  55223. camRot *= 4.0;
  55224. 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);
  55225. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55226. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55227. };
  55228. };
  55229. // Create depth-of-field post-process
  55230. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55231. var _this = this;
  55232. 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);
  55233. this.depthOfFieldPostProcess.onApply = function (effect) {
  55234. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55235. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  55236. effect.setFloat("distance", _this.depthOfFieldDistance);
  55237. };
  55238. // Add to pipeline
  55239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55240. };
  55241. // Dispose
  55242. StandardRenderingPipeline.prototype.dispose = function () {
  55243. for (var i = 0; i < this._scene.cameras.length; i++) {
  55244. var camera = this._scene.cameras[i];
  55245. this.originalPostProcess.dispose(camera);
  55246. this.downSampleX4PostProcess.dispose(camera);
  55247. this.brightPassPostProcess.dispose(camera);
  55248. this.textureAdderPostProcess.dispose(camera);
  55249. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  55250. this.gaussianBlurHPostProcesses[j].dispose(camera);
  55251. }
  55252. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  55253. this.gaussianBlurVPostProcesses[j].dispose(camera);
  55254. }
  55255. this.textureAdderFinalPostProcess.dispose(camera);
  55256. this.lensFlarePostProcess.dispose(camera);
  55257. this.lensFlareComposePostProcess.dispose(camera);
  55258. this.depthOfFieldPostProcess.dispose(camera);
  55259. }
  55260. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55261. _super.prototype.dispose.call(this);
  55262. };
  55263. return StandardRenderingPipeline;
  55264. }(BABYLON.PostProcessRenderPipeline));
  55265. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55266. })(BABYLON || (BABYLON = {}));
  55267. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55268. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=abs(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 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  55269. 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=abs((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"};
  55270. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.multiply=function(t){\nvar i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t)},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  55271. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55272. module.exports = BABYLON;
  55273. };