babylon.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548
  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. /**
  22. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  23. */
  24. MathTools.WithinEpsilon = function (a, b, epsilon) {
  25. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  26. var num = a - b;
  27. return -epsilon <= num && num <= epsilon;
  28. };
  29. /**
  30. * Returns a string : the upper case translation of the number i to hexadecimal.
  31. */
  32. MathTools.ToHex = function (i) {
  33. var str = i.toString(16);
  34. if (i <= 15) {
  35. return ("0" + str).toUpperCase();
  36. }
  37. return str.toUpperCase();
  38. };
  39. /**
  40. * Returns -1 if value is negative and +1 is value is positive.
  41. * Returns the value itself if it's equal to zero.
  42. */
  43. MathTools.Sign = function (value) {
  44. value = +value; // convert to a number
  45. if (value === 0 || isNaN(value))
  46. return value;
  47. return value > 0 ? 1 : -1;
  48. };
  49. /**
  50. * Returns the value itself if it's between min and max.
  51. * Returns min if the value is lower than min.
  52. * Returns max if the value is greater than max.
  53. */
  54. MathTools.Clamp = function (value, min, max) {
  55. if (min === void 0) { min = 0; }
  56. if (max === void 0) { max = 1; }
  57. return Math.min(max, Math.max(min, value));
  58. };
  59. return MathTools;
  60. }());
  61. BABYLON.MathTools = MathTools;
  62. var Color3 = (function () {
  63. /**
  64. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  65. */
  66. function Color3(r, g, b) {
  67. if (r === void 0) { r = 0; }
  68. if (g === void 0) { g = 0; }
  69. if (b === void 0) { b = 0; }
  70. this.r = r;
  71. this.g = g;
  72. this.b = b;
  73. }
  74. /**
  75. * Returns a string with the Color3 current values.
  76. */
  77. Color3.prototype.toString = function () {
  78. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  79. };
  80. /**
  81. * Returns the string "Color3".
  82. */
  83. Color3.prototype.getClassName = function () {
  84. return "Color3";
  85. };
  86. /**
  87. * Returns the Color3 hash code.
  88. */
  89. Color3.prototype.getHashCode = function () {
  90. var hash = this.r || 0;
  91. hash = (hash * 397) ^ (this.g || 0);
  92. hash = (hash * 397) ^ (this.b || 0);
  93. return hash;
  94. };
  95. // Operators
  96. /**
  97. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  98. * Returns the Color3.
  99. */
  100. Color3.prototype.toArray = function (array, index) {
  101. if (index === undefined) {
  102. index = 0;
  103. }
  104. array[index] = this.r;
  105. array[index + 1] = this.g;
  106. array[index + 2] = this.b;
  107. return this;
  108. };
  109. /**
  110. * Returns a new Color4 object from the current Color3 and the passed alpha.
  111. */
  112. Color3.prototype.toColor4 = function (alpha) {
  113. if (alpha === void 0) { alpha = 1; }
  114. return new Color4(this.r, this.g, this.b, alpha);
  115. };
  116. /**
  117. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  118. */
  119. Color3.prototype.asArray = function () {
  120. var result = [];
  121. this.toArray(result, 0);
  122. return result;
  123. };
  124. /**
  125. * Returns the luminance value (float).
  126. */
  127. Color3.prototype.toLuminance = function () {
  128. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  129. };
  130. /**
  131. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  132. * Returns this new object.
  133. */
  134. Color3.prototype.multiply = function (otherColor) {
  135. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  136. };
  137. /**
  138. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  139. * Returns the current Color3.
  140. */
  141. Color3.prototype.multiplyToRef = function (otherColor, result) {
  142. result.r = this.r * otherColor.r;
  143. result.g = this.g * otherColor.g;
  144. result.b = this.b * otherColor.b;
  145. return this;
  146. };
  147. /**
  148. * Boolean : True if the rgb values are equal to the passed ones.
  149. */
  150. Color3.prototype.equals = function (otherColor) {
  151. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  152. };
  153. /**
  154. * Boolean : True if the rgb values are equal to the passed ones.
  155. */
  156. Color3.prototype.equalsFloats = function (r, g, b) {
  157. return this.r === r && this.g === g && this.b === b;
  158. };
  159. /**
  160. * Multiplies in place each rgb value by scale.
  161. * Returns the updated Color3.
  162. */
  163. Color3.prototype.scale = function (scale) {
  164. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  165. };
  166. /**
  167. * Multiplies the rgb values by scale and stores the result into "result".
  168. * Returns the unmodified current Color3.
  169. */
  170. Color3.prototype.scaleToRef = function (scale, result) {
  171. result.r = this.r * scale;
  172. result.g = this.g * scale;
  173. result.b = this.b * scale;
  174. return this;
  175. };
  176. /**
  177. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  178. */
  179. Color3.prototype.add = function (otherColor) {
  180. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  181. };
  182. /**
  183. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  184. * Returns the unmodified current Color3.
  185. */
  186. Color3.prototype.addToRef = function (otherColor, result) {
  187. result.r = this.r + otherColor.r;
  188. result.g = this.g + otherColor.g;
  189. result.b = this.b + otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  194. */
  195. Color3.prototype.subtract = function (otherColor) {
  196. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  197. };
  198. /**
  199. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  200. * Returns the unmodified current Color3.
  201. */
  202. Color3.prototype.subtractToRef = function (otherColor, result) {
  203. result.r = this.r - otherColor.r;
  204. result.g = this.g - otherColor.g;
  205. result.b = this.b - otherColor.b;
  206. return this;
  207. };
  208. /**
  209. * Returns a new Color3 copied the current one.
  210. */
  211. Color3.prototype.clone = function () {
  212. return new Color3(this.r, this.g, this.b);
  213. };
  214. /**
  215. * Copies the rgb values from the source in the current Color3.
  216. * Returns the updated Color3.
  217. */
  218. Color3.prototype.copyFrom = function (source) {
  219. this.r = source.r;
  220. this.g = source.g;
  221. this.b = source.b;
  222. return this;
  223. };
  224. /**
  225. * Updates the Color3 rgb values from the passed floats.
  226. * Returns the Color3.
  227. */
  228. Color3.prototype.copyFromFloats = function (r, g, b) {
  229. this.r = r;
  230. this.g = g;
  231. this.b = b;
  232. return this;
  233. };
  234. /**
  235. * Updates the Color3 rgb values from the passed floats.
  236. * Returns the Color3.
  237. */
  238. Color3.prototype.set = function (r, g, b) {
  239. return this.copyFromFloats(r, g, b);
  240. };
  241. /**
  242. * Returns the Color3 hexadecimal code as a string.
  243. */
  244. Color3.prototype.toHexString = function () {
  245. var intR = (this.r * 255) | 0;
  246. var intG = (this.g * 255) | 0;
  247. var intB = (this.b * 255) | 0;
  248. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  249. };
  250. /**
  251. * Returns a new Color3 converted to linear space.
  252. */
  253. Color3.prototype.toLinearSpace = function () {
  254. var convertedColor = new Color3();
  255. this.toLinearSpaceToRef(convertedColor);
  256. return convertedColor;
  257. };
  258. /**
  259. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  260. * Returns the unmodified Color3.
  261. */
  262. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  263. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  264. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  265. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  266. return this;
  267. };
  268. /**
  269. * Returns a new Color3 converted to gamma space.
  270. */
  271. Color3.prototype.toGammaSpace = function () {
  272. var convertedColor = new Color3();
  273. this.toGammaSpaceToRef(convertedColor);
  274. return convertedColor;
  275. };
  276. /**
  277. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  278. * Returns the unmodified Color3.
  279. */
  280. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  281. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  282. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  283. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  284. return this;
  285. };
  286. // Statics
  287. /**
  288. * Creates a new Color3 from the string containing valid hexadecimal values.
  289. */
  290. Color3.FromHexString = function (hex) {
  291. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  292. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  293. return new Color3(0, 0, 0);
  294. }
  295. var r = parseInt(hex.substring(1, 3), 16);
  296. var g = parseInt(hex.substring(3, 5), 16);
  297. var b = parseInt(hex.substring(5, 7), 16);
  298. return Color3.FromInts(r, g, b);
  299. };
  300. /**
  301. * Creates a new Vector3 from the startind index of the passed array.
  302. */
  303. Color3.FromArray = function (array, offset) {
  304. if (offset === void 0) { offset = 0; }
  305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  306. };
  307. /**
  308. * Creates a new Color3 from integer values ( < 256).
  309. */
  310. Color3.FromInts = function (r, g, b) {
  311. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  312. };
  313. /**
  314. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  315. */
  316. Color3.Lerp = function (start, end, amount) {
  317. var r = start.r + ((end.r - start.r) * amount);
  318. var g = start.g + ((end.g - start.g) * amount);
  319. var b = start.b + ((end.b - start.b) * amount);
  320. return new Color3(r, g, b);
  321. };
  322. Color3.Red = function () { return new Color3(1, 0, 0); };
  323. Color3.Green = function () { return new Color3(0, 1, 0); };
  324. Color3.Blue = function () { return new Color3(0, 0, 1); };
  325. Color3.Black = function () { return new Color3(0, 0, 0); };
  326. Color3.White = function () { return new Color3(1, 1, 1); };
  327. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  328. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  329. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  330. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  331. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  332. return Color3;
  333. }());
  334. BABYLON.Color3 = Color3;
  335. var Color4 = (function () {
  336. /**
  337. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  338. */
  339. function Color4(r, g, b, a) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. this.a = a;
  344. }
  345. // Operators
  346. /**
  347. * Adds in place the passed Color4 values to the current Color4.
  348. * Returns the updated Color4.
  349. */
  350. Color4.prototype.addInPlace = function (right) {
  351. this.r += right.r;
  352. this.g += right.g;
  353. this.b += right.b;
  354. this.a += right.a;
  355. return this;
  356. };
  357. /**
  358. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  359. */
  360. Color4.prototype.asArray = function () {
  361. var result = [];
  362. this.toArray(result, 0);
  363. return result;
  364. };
  365. /**
  366. * Stores from the starting index in the passed array the Color4 successive values.
  367. * Returns the Color4.
  368. */
  369. Color4.prototype.toArray = function (array, index) {
  370. if (index === undefined) {
  371. index = 0;
  372. }
  373. array[index] = this.r;
  374. array[index + 1] = this.g;
  375. array[index + 2] = this.b;
  376. array[index + 3] = this.a;
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  381. */
  382. Color4.prototype.add = function (right) {
  383. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  384. };
  385. /**
  386. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  387. */
  388. Color4.prototype.subtract = function (right) {
  389. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  390. };
  391. /**
  392. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  393. * Returns the Color4.
  394. */
  395. Color4.prototype.subtractToRef = function (right, result) {
  396. result.r = this.r - right.r;
  397. result.g = this.g - right.g;
  398. result.b = this.b - right.b;
  399. result.a = this.a - right.a;
  400. return this;
  401. };
  402. /**
  403. * Creates a new Color4 with the current Color4 values multiplied by scale.
  404. */
  405. Color4.prototype.scale = function (scale) {
  406. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  407. };
  408. /**
  409. * Multiplies the current Color4 values by scale and stores the result in "result".
  410. * Returns the Color4.
  411. */
  412. Color4.prototype.scaleToRef = function (scale, result) {
  413. result.r = this.r * scale;
  414. result.g = this.g * scale;
  415. result.b = this.b * scale;
  416. result.a = this.a * scale;
  417. return this;
  418. };
  419. /**
  420. * Multipy an RGBA Color4 value by another and return a new Color4 object
  421. * @param color The Color4 (RGBA) value to multiply by
  422. * @returns A new Color4.
  423. */
  424. Color4.prototype.multiply = function (color) {
  425. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  426. };
  427. /**
  428. * Multipy an RGBA Color4 value by another and push the result in a reference value
  429. * @param color The Color4 (RGBA) value to multiply by
  430. * @param result The Color4 (RGBA) to fill the result in
  431. * @returns the result Color4.
  432. */
  433. Color4.prototype.multiplyToRef = function (color, result) {
  434. result.r = this.r * color.r;
  435. result.g = this.g * color.g;
  436. result.b = this.b * color.b;
  437. result.a = this.a * color.a;
  438. return result;
  439. };
  440. /**
  441. * Returns a string with the Color4 values.
  442. */
  443. Color4.prototype.toString = function () {
  444. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  445. };
  446. /**
  447. * Returns the string "Color4"
  448. */
  449. Color4.prototype.getClassName = function () {
  450. return "Color4";
  451. };
  452. /**
  453. * Return the Color4 hash code as a number.
  454. */
  455. Color4.prototype.getHashCode = function () {
  456. var hash = this.r || 0;
  457. hash = (hash * 397) ^ (this.g || 0);
  458. hash = (hash * 397) ^ (this.b || 0);
  459. hash = (hash * 397) ^ (this.a || 0);
  460. return hash;
  461. };
  462. /**
  463. * Creates a new Color4 copied from the current one.
  464. */
  465. Color4.prototype.clone = function () {
  466. return new Color4(this.r, this.g, this.b, this.a);
  467. };
  468. /**
  469. * Copies the passed Color4 values into the current one.
  470. * Returns the updated Color4.
  471. */
  472. Color4.prototype.copyFrom = function (source) {
  473. this.r = source.r;
  474. this.g = source.g;
  475. this.b = source.b;
  476. this.a = source.a;
  477. return this;
  478. };
  479. /**
  480. * Copies the passed float values into the current one.
  481. * Returns the updated Color4.
  482. */
  483. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  484. this.r = r;
  485. this.g = g;
  486. this.b = b;
  487. this.a = a;
  488. return this;
  489. };
  490. /**
  491. * Copies the passed float values into the current one.
  492. * Returns the updated Color4.
  493. */
  494. Color4.prototype.set = function (r, g, b, a) {
  495. return this.copyFromFloats(r, g, b, a);
  496. };
  497. /**
  498. * Returns a string containing the hexadecimal Color4 code.
  499. */
  500. Color4.prototype.toHexString = function () {
  501. var intR = (this.r * 255) | 0;
  502. var intG = (this.g * 255) | 0;
  503. var intB = (this.b * 255) | 0;
  504. var intA = (this.a * 255) | 0;
  505. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  506. };
  507. // Statics
  508. /**
  509. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  510. */
  511. Color4.FromHexString = function (hex) {
  512. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  513. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  514. return new Color4(0.0, 0.0, 0.0, 0.0);
  515. }
  516. var r = parseInt(hex.substring(1, 3), 16);
  517. var g = parseInt(hex.substring(3, 5), 16);
  518. var b = parseInt(hex.substring(5, 7), 16);
  519. var a = parseInt(hex.substring(7, 9), 16);
  520. return Color4.FromInts(r, g, b, a);
  521. };
  522. /**
  523. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  524. */
  525. Color4.Lerp = function (left, right, amount) {
  526. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  527. Color4.LerpToRef(left, right, amount, result);
  528. return result;
  529. };
  530. /**
  531. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  532. */
  533. Color4.LerpToRef = function (left, right, amount, result) {
  534. result.r = left.r + (right.r - left.r) * amount;
  535. result.g = left.g + (right.g - left.g) * amount;
  536. result.b = left.b + (right.b - left.b) * amount;
  537. result.a = left.a + (right.a - left.a) * amount;
  538. };
  539. /**
  540. * Creates a new Color4 from the starting index element of the passed array.
  541. */
  542. Color4.FromArray = function (array, offset) {
  543. if (offset === void 0) { offset = 0; }
  544. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  545. };
  546. /**
  547. * Creates a new Color4 from the passed integers ( < 256 ).
  548. */
  549. Color4.FromInts = function (r, g, b, a) {
  550. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  551. };
  552. Color4.CheckColors4 = function (colors, count) {
  553. // Check if color3 was used
  554. if (colors.length === count * 3) {
  555. var colors4 = [];
  556. for (var index = 0; index < colors.length; index += 3) {
  557. var newIndex = (index / 3) * 4;
  558. colors4[newIndex] = colors[index];
  559. colors4[newIndex + 1] = colors[index + 1];
  560. colors4[newIndex + 2] = colors[index + 2];
  561. colors4[newIndex + 3] = 1.0;
  562. }
  563. return colors4;
  564. }
  565. return colors;
  566. };
  567. return Color4;
  568. }());
  569. BABYLON.Color4 = Color4;
  570. var Vector2 = (function () {
  571. /**
  572. * Creates a new Vector2 from the passed x and y coordinates.
  573. */
  574. function Vector2(x, y) {
  575. this.x = x;
  576. this.y = y;
  577. }
  578. /**
  579. * Returns a string with the Vector2 coordinates.
  580. */
  581. Vector2.prototype.toString = function () {
  582. return "{X: " + this.x + " Y:" + this.y + "}";
  583. };
  584. /**
  585. * Returns the string "Vector2"
  586. */
  587. Vector2.prototype.getClassName = function () {
  588. return "Vector2";
  589. };
  590. /**
  591. * Returns the Vector2 hash code as a number.
  592. */
  593. Vector2.prototype.getHashCode = function () {
  594. var hash = this.x || 0;
  595. hash = (hash * 397) ^ (this.y || 0);
  596. return hash;
  597. };
  598. // Operators
  599. /**
  600. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  601. * Returns the Vector2.
  602. */
  603. Vector2.prototype.toArray = function (array, index) {
  604. if (index === void 0) { index = 0; }
  605. array[index] = this.x;
  606. array[index + 1] = this.y;
  607. return this;
  608. };
  609. /**
  610. * Returns a new array with 2 elements : the Vector2 coordinates.
  611. */
  612. Vector2.prototype.asArray = function () {
  613. var result = [];
  614. this.toArray(result, 0);
  615. return result;
  616. };
  617. /**
  618. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  619. * Returns the updated Vector2.
  620. */
  621. Vector2.prototype.copyFrom = function (source) {
  622. this.x = source.x;
  623. this.y = source.y;
  624. return this;
  625. };
  626. /**
  627. * Sets the Vector2 coordinates with the passed floats.
  628. * Returns the updated Vector2.
  629. */
  630. Vector2.prototype.copyFromFloats = function (x, y) {
  631. this.x = x;
  632. this.y = y;
  633. return this;
  634. };
  635. /**
  636. * Sets the Vector2 coordinates with the passed floats.
  637. * Returns the updated Vector2.
  638. */
  639. Vector2.prototype.set = function (x, y) {
  640. return this.copyFromFloats(x, y);
  641. };
  642. /**
  643. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  644. */
  645. Vector2.prototype.add = function (otherVector) {
  646. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  647. };
  648. /**
  649. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  650. * Returns the Vector2.
  651. */
  652. Vector2.prototype.addToRef = function (otherVector, result) {
  653. result.x = this.x + otherVector.x;
  654. result.y = this.y + otherVector.y;
  655. return this;
  656. };
  657. /**
  658. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  659. * Returns the updated Vector2.
  660. */
  661. Vector2.prototype.addInPlace = function (otherVector) {
  662. this.x += otherVector.x;
  663. this.y += otherVector.y;
  664. return this;
  665. };
  666. /**
  667. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  668. */
  669. Vector2.prototype.addVector3 = function (otherVector) {
  670. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  671. };
  672. /**
  673. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  674. */
  675. Vector2.prototype.subtract = function (otherVector) {
  676. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  677. };
  678. /**
  679. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  680. * Returns the Vector2.
  681. */
  682. Vector2.prototype.subtractToRef = function (otherVector, result) {
  683. result.x = this.x - otherVector.x;
  684. result.y = this.y - otherVector.y;
  685. return this;
  686. };
  687. /**
  688. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  689. * Returns the updated Vector2.
  690. */
  691. Vector2.prototype.subtractInPlace = function (otherVector) {
  692. this.x -= otherVector.x;
  693. this.y -= otherVector.y;
  694. return this;
  695. };
  696. /**
  697. * Multiplies in place the current Vector2 coordinates by the passed ones.
  698. * Returns the updated Vector2.
  699. */
  700. Vector2.prototype.multiplyInPlace = function (otherVector) {
  701. this.x *= otherVector.x;
  702. this.y *= otherVector.y;
  703. return this;
  704. };
  705. /**
  706. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  707. */
  708. Vector2.prototype.multiply = function (otherVector) {
  709. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  710. };
  711. /**
  712. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  713. * Returns the Vector2.
  714. */
  715. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  716. result.x = this.x * otherVector.x;
  717. result.y = this.y * otherVector.y;
  718. return this;
  719. };
  720. /**
  721. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  722. */
  723. Vector2.prototype.multiplyByFloats = function (x, y) {
  724. return new Vector2(this.x * x, this.y * y);
  725. };
  726. /**
  727. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  728. */
  729. Vector2.prototype.divide = function (otherVector) {
  730. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  731. };
  732. /**
  733. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  734. * Returns the Vector2.
  735. */
  736. Vector2.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. return this;
  740. };
  741. /**
  742. * Returns a new Vector2 with current Vector2 negated coordinates.
  743. */
  744. Vector2.prototype.negate = function () {
  745. return new Vector2(-this.x, -this.y);
  746. };
  747. /**
  748. * Multiply the Vector2 coordinates by scale.
  749. * Returns the updated Vector2.
  750. */
  751. Vector2.prototype.scaleInPlace = function (scale) {
  752. this.x *= scale;
  753. this.y *= scale;
  754. return this;
  755. };
  756. /**
  757. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  758. */
  759. Vector2.prototype.scale = function (scale) {
  760. return new Vector2(this.x * scale, this.y * scale);
  761. };
  762. /**
  763. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  764. */
  765. Vector2.prototype.equals = function (otherVector) {
  766. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  767. };
  768. /**
  769. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  770. */
  771. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  772. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  773. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  774. };
  775. // Properties
  776. /**
  777. * Returns the vector length (float).
  778. */
  779. Vector2.prototype.length = function () {
  780. return Math.sqrt(this.x * this.x + this.y * this.y);
  781. };
  782. /**
  783. * Returns the vector squared length (float);
  784. */
  785. Vector2.prototype.lengthSquared = function () {
  786. return (this.x * this.x + this.y * this.y);
  787. };
  788. // Methods
  789. /**
  790. * Normalize the vector.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.normalize = function () {
  794. var len = this.length();
  795. if (len === 0)
  796. return this;
  797. var num = 1.0 / len;
  798. this.x *= num;
  799. this.y *= num;
  800. return this;
  801. };
  802. /**
  803. * Returns a new Vector2 copied from the Vector2.
  804. */
  805. Vector2.prototype.clone = function () {
  806. return new Vector2(this.x, this.y);
  807. };
  808. // Statics
  809. /**
  810. * Returns a new Vector2(0, 0)
  811. */
  812. Vector2.Zero = function () {
  813. return new Vector2(0, 0);
  814. };
  815. /**
  816. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  817. */
  818. Vector2.FromArray = function (array, offset) {
  819. if (offset === void 0) { offset = 0; }
  820. return new Vector2(array[offset], array[offset + 1]);
  821. };
  822. /**
  823. * Sets "result" from the passed index element of the passed array or Float32Array.
  824. * Returns the Vector2.
  825. */
  826. Vector2.FromArrayToRef = function (array, offset, result) {
  827. result.x = array[offset];
  828. result.y = array[offset + 1];
  829. };
  830. /**
  831. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  832. */
  833. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  834. var squared = amount * amount;
  835. var cubed = amount * squared;
  836. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  837. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  838. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  839. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  840. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  841. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  842. return new Vector2(x, y);
  843. };
  844. /**
  845. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  846. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  847. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  848. */
  849. Vector2.Clamp = function (value, min, max) {
  850. var x = value.x;
  851. x = (x > max.x) ? max.x : x;
  852. x = (x < min.x) ? min.x : x;
  853. var y = value.y;
  854. y = (y > max.y) ? max.y : y;
  855. y = (y < min.y) ? min.y : y;
  856. return new Vector2(x, y);
  857. };
  858. /**
  859. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  860. */
  861. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  865. var part2 = (-2.0 * cubed) + (3.0 * squared);
  866. var part3 = (cubed - (2.0 * squared)) + amount;
  867. var part4 = cubed - squared;
  868. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  869. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  870. return new Vector2(x, y);
  871. };
  872. /**
  873. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  874. */
  875. Vector2.Lerp = function (start, end, amount) {
  876. var x = start.x + ((end.x - start.x) * amount);
  877. var y = start.y + ((end.y - start.y) * amount);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns the dot product (float) of the vector "left" and the vector "right".
  882. */
  883. Vector2.Dot = function (left, right) {
  884. return left.x * right.x + left.y * right.y;
  885. };
  886. /**
  887. * Returns a new Vector2 equal to the normalized passed vector.
  888. */
  889. Vector2.Normalize = function (vector) {
  890. var newVector = vector.clone();
  891. newVector.normalize();
  892. return newVector;
  893. };
  894. /**
  895. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  896. */
  897. Vector2.Minimize = function (left, right) {
  898. var x = (left.x < right.x) ? left.x : right.x;
  899. var y = (left.y < right.y) ? left.y : right.y;
  900. return new Vector2(x, y);
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Maximize = function (left, right) {
  906. var x = (left.x > right.x) ? left.x : right.x;
  907. var y = (left.y > right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  912. */
  913. Vector2.Transform = function (vector, transformation) {
  914. var r = Vector2.Zero();
  915. Vector2.TransformToRef(vector, transformation, r);
  916. return r;
  917. };
  918. /**
  919. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  920. */
  921. Vector2.TransformToRef = function (vector, transformation, result) {
  922. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  923. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  924. result.x = x;
  925. result.y = y;
  926. };
  927. /**
  928. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  929. */
  930. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  931. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  932. var sign = a < 0 ? -1 : 1;
  933. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  934. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  935. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  936. };
  937. /**
  938. * Returns the distance (float) between the vectors "value1" and "value2".
  939. */
  940. Vector2.Distance = function (value1, value2) {
  941. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  942. };
  943. /**
  944. * Returns the squared distance (float) between the vectors "value1" and "value2".
  945. */
  946. Vector2.DistanceSquared = function (value1, value2) {
  947. var x = value1.x - value2.x;
  948. var y = value1.y - value2.y;
  949. return (x * x) + (y * y);
  950. };
  951. /**
  952. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  953. */
  954. Vector2.Center = function (value1, value2) {
  955. var center = value1.add(value2);
  956. center.scaleInPlace(0.5);
  957. return center;
  958. };
  959. /**
  960. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  961. */
  962. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  963. var l2 = Vector2.DistanceSquared(segA, segB);
  964. if (l2 === 0.0) {
  965. return Vector2.Distance(p, segA);
  966. }
  967. var v = segB.subtract(segA);
  968. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  969. var proj = segA.add(v.multiplyByFloats(t, t));
  970. return Vector2.Distance(p, proj);
  971. };
  972. return Vector2;
  973. }());
  974. BABYLON.Vector2 = Vector2;
  975. var Vector3 = (function () {
  976. /**
  977. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  978. * A Vector3 is the main object used in 3D geometry.
  979. * It can represent etiher the coordinates of a point the space, either a direction.
  980. */
  981. function Vector3(x, y, z) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. }
  986. /**
  987. * Returns a string with the Vector3 coordinates.
  988. */
  989. Vector3.prototype.toString = function () {
  990. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  991. };
  992. /**
  993. * Returns the string "Vector3"
  994. */
  995. Vector3.prototype.getClassName = function () {
  996. return "Vector3";
  997. };
  998. /**
  999. * Returns the Vector hash code.
  1000. */
  1001. Vector3.prototype.getHashCode = function () {
  1002. var hash = this.x || 0;
  1003. hash = (hash * 397) ^ (this.y || 0);
  1004. hash = (hash * 397) ^ (this.z || 0);
  1005. return hash;
  1006. };
  1007. // Operators
  1008. /**
  1009. * Returns a new array with three elements : the coordinates the Vector3.
  1010. */
  1011. Vector3.prototype.asArray = function () {
  1012. var result = [];
  1013. this.toArray(result, 0);
  1014. return result;
  1015. };
  1016. /**
  1017. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1018. * Returns the Vector3.
  1019. */
  1020. Vector3.prototype.toArray = function (array, index) {
  1021. if (index === void 0) { index = 0; }
  1022. array[index] = this.x;
  1023. array[index + 1] = this.y;
  1024. array[index + 2] = this.z;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1029. */
  1030. Vector3.prototype.toQuaternion = function () {
  1031. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1032. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1033. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1034. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1035. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1036. var cosy = Math.cos(this.y * 0.5);
  1037. var siny = Math.sin(this.y * 0.5);
  1038. result.x = coszMinusx * siny;
  1039. result.y = -sinzMinusx * siny;
  1040. result.z = sinxPlusz * cosy;
  1041. result.w = cosxPlusz * cosy;
  1042. return result;
  1043. };
  1044. /**
  1045. * Adds the passed vector to the current Vector3.
  1046. * Returns the updated Vector3.
  1047. */
  1048. Vector3.prototype.addInPlace = function (otherVector) {
  1049. this.x += otherVector.x;
  1050. this.y += otherVector.y;
  1051. this.z += otherVector.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1056. */
  1057. Vector3.prototype.add = function (otherVector) {
  1058. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1059. };
  1060. /**
  1061. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1062. * Returns the current Vector3.
  1063. */
  1064. Vector3.prototype.addToRef = function (otherVector, result) {
  1065. result.x = this.x + otherVector.x;
  1066. result.y = this.y + otherVector.y;
  1067. result.z = this.z + otherVector.z;
  1068. return this;
  1069. };
  1070. /**
  1071. * Subtract the passed vector from the current Vector3.
  1072. * Returns the updated Vector3.
  1073. */
  1074. Vector3.prototype.subtractInPlace = function (otherVector) {
  1075. this.x -= otherVector.x;
  1076. this.y -= otherVector.y;
  1077. this.z -= otherVector.z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1082. */
  1083. Vector3.prototype.subtract = function (otherVector) {
  1084. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1085. };
  1086. /**
  1087. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1088. * Returns the current Vector3.
  1089. */
  1090. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1091. result.x = this.x - otherVector.x;
  1092. result.y = this.y - otherVector.y;
  1093. result.z = this.z - otherVector.z;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1098. */
  1099. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1100. return new Vector3(this.x - x, this.y - y, this.z - z);
  1101. };
  1102. /**
  1103. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1107. result.x = this.x - x;
  1108. result.y = this.y - y;
  1109. result.z = this.z - z;
  1110. return this;
  1111. };
  1112. /**
  1113. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1114. */
  1115. Vector3.prototype.negate = function () {
  1116. return new Vector3(-this.x, -this.y, -this.z);
  1117. };
  1118. /**
  1119. * Multiplies the Vector3 coordinates by the float "scale".
  1120. * Returns the updated Vector3.
  1121. */
  1122. Vector3.prototype.scaleInPlace = function (scale) {
  1123. this.x *= scale;
  1124. this.y *= scale;
  1125. this.z *= scale;
  1126. return this;
  1127. };
  1128. /**
  1129. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1130. */
  1131. Vector3.prototype.scale = function (scale) {
  1132. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1133. };
  1134. /**
  1135. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1136. * Returns the current Vector3.
  1137. */
  1138. Vector3.prototype.scaleToRef = function (scale, result) {
  1139. result.x = this.x * scale;
  1140. result.y = this.y * scale;
  1141. result.z = this.z * scale;
  1142. return this;
  1143. };
  1144. /**
  1145. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1146. */
  1147. Vector3.prototype.equals = function (otherVector) {
  1148. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1149. };
  1150. /**
  1151. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1152. */
  1153. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1154. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1155. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1156. };
  1157. /**
  1158. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1159. */
  1160. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1161. return this.x === x && this.y === y && this.z === z;
  1162. };
  1163. /**
  1164. * Muliplies the current Vector3 coordinates by the passed ones.
  1165. * Returns the updated Vector3.
  1166. */
  1167. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1168. this.x *= otherVector.x;
  1169. this.y *= otherVector.y;
  1170. this.z *= otherVector.z;
  1171. return this;
  1172. };
  1173. /**
  1174. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1175. */
  1176. Vector3.prototype.multiply = function (otherVector) {
  1177. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1178. };
  1179. /**
  1180. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1181. * Returns the current Vector3.
  1182. */
  1183. Vector3.prototype.multiplyToRef = 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. return this;
  1188. };
  1189. /**
  1190. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1191. */
  1192. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1193. return new Vector3(this.x * x, this.y * y, this.z * z);
  1194. };
  1195. /**
  1196. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1197. */
  1198. Vector3.prototype.divide = function (otherVector) {
  1199. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1200. };
  1201. /**
  1202. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1203. * Returns the current Vector3.
  1204. */
  1205. Vector3.prototype.divideToRef = function (otherVector, result) {
  1206. result.x = this.x / otherVector.x;
  1207. result.y = this.y / otherVector.y;
  1208. result.z = this.z / otherVector.z;
  1209. return this;
  1210. };
  1211. /**
  1212. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1213. * Returns the updated Vector3.
  1214. */
  1215. Vector3.prototype.MinimizeInPlace = function (other) {
  1216. if (other.x < this.x)
  1217. this.x = other.x;
  1218. if (other.y < this.y)
  1219. this.y = other.y;
  1220. if (other.z < this.z)
  1221. this.z = other.z;
  1222. return this;
  1223. };
  1224. /**
  1225. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1226. * Returns the updated Vector3.
  1227. */
  1228. Vector3.prototype.MaximizeInPlace = function (other) {
  1229. if (other.x > this.x)
  1230. this.x = other.x;
  1231. if (other.y > this.y)
  1232. this.y = other.y;
  1233. if (other.z > this.z)
  1234. this.z = other.z;
  1235. return this;
  1236. };
  1237. // Properties
  1238. /**
  1239. * Returns the length of the Vector3 (float).
  1240. */
  1241. Vector3.prototype.length = function () {
  1242. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1243. };
  1244. /**
  1245. * Returns the squared length of the Vector3 (float).
  1246. */
  1247. Vector3.prototype.lengthSquared = function () {
  1248. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1249. };
  1250. // Methods
  1251. /**
  1252. * Normalize the current Vector3.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.normalize = function () {
  1256. var len = this.length();
  1257. if (len === 0 || len === 1.0)
  1258. return this;
  1259. var num = 1.0 / len;
  1260. this.x *= num;
  1261. this.y *= num;
  1262. this.z *= num;
  1263. return this;
  1264. };
  1265. /**
  1266. * Returns a new Vector3 copied from the current Vector3.
  1267. */
  1268. Vector3.prototype.clone = function () {
  1269. return new Vector3(this.x, this.y, this.z);
  1270. };
  1271. /**
  1272. * Copies the passed vector coordinates to the current Vector3 ones.
  1273. * Returns the updated Vector3.
  1274. */
  1275. Vector3.prototype.copyFrom = function (source) {
  1276. this.x = source.x;
  1277. this.y = source.y;
  1278. this.z = source.z;
  1279. return this;
  1280. };
  1281. /**
  1282. * Copies the passed floats to the current Vector3 coordinates.
  1283. * Returns the updated Vector3.
  1284. */
  1285. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1286. this.x = x;
  1287. this.y = y;
  1288. this.z = z;
  1289. return this;
  1290. };
  1291. /**
  1292. * Copies the passed floats to the current Vector3 coordinates.
  1293. * Returns the updated Vector3.
  1294. */
  1295. Vector3.prototype.set = function (x, y, z) {
  1296. return this.copyFromFloats(x, y, z);
  1297. };
  1298. // Statics
  1299. /**
  1300. *
  1301. */
  1302. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1303. var d0 = Vector3.Dot(vector0, axis) - size;
  1304. var d1 = Vector3.Dot(vector1, axis) - size;
  1305. var s = d0 / (d0 - d1);
  1306. return s;
  1307. };
  1308. /**
  1309. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1310. */
  1311. Vector3.FromArray = function (array, offset) {
  1312. if (!offset) {
  1313. offset = 0;
  1314. }
  1315. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1319. */
  1320. Vector3.FromFloatArray = function (array, offset) {
  1321. if (!offset) {
  1322. offset = 0;
  1323. }
  1324. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1325. };
  1326. /**
  1327. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1328. */
  1329. Vector3.FromArrayToRef = function (array, offset, result) {
  1330. result.x = array[offset];
  1331. result.y = array[offset + 1];
  1332. result.z = array[offset + 2];
  1333. };
  1334. /**
  1335. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1336. */
  1337. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. };
  1342. /**
  1343. * Sets the passed vector "result" with the passed floats.
  1344. */
  1345. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1346. result.x = x;
  1347. result.y = y;
  1348. result.z = z;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1352. */
  1353. Vector3.Zero = function () {
  1354. return new Vector3(0.0, 0.0, 0.0);
  1355. };
  1356. /**
  1357. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1358. */
  1359. Vector3.Up = function () {
  1360. return new Vector3(0.0, 1.0, 0.0);
  1361. };
  1362. /**
  1363. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1364. */
  1365. Vector3.Forward = function () {
  1366. return new Vector3(0.0, 0.0, 1.0);
  1367. };
  1368. /**
  1369. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1370. */
  1371. Vector3.Right = function () {
  1372. return new Vector3(1.0, 0.0, 0.0);
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1376. */
  1377. Vector3.Left = function () {
  1378. return new Vector3(-1.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1382. * This method computes tranformed coordinates only, not transformed direction vectors.
  1383. */
  1384. Vector3.TransformCoordinates = function (vector, transformation) {
  1385. var result = Vector3.Zero();
  1386. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1387. return result;
  1388. };
  1389. /**
  1390. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1391. * This method computes tranformed coordinates only, not transformed direction vectors.
  1392. */
  1393. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1394. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1395. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1396. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1397. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1398. result.x = x / w;
  1399. result.y = y / w;
  1400. result.z = z / w;
  1401. };
  1402. /**
  1403. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1404. * This method computes tranformed coordinates only, not transformed direction vectors.
  1405. */
  1406. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1407. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1408. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1409. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1410. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1411. result.x = rx / rw;
  1412. result.y = ry / rw;
  1413. result.z = rz / rw;
  1414. };
  1415. /**
  1416. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1417. * This methods computes transformed normalized direction vectors only.
  1418. */
  1419. Vector3.TransformNormal = function (vector, transformation) {
  1420. var result = Vector3.Zero();
  1421. Vector3.TransformNormalToRef(vector, transformation, result);
  1422. return result;
  1423. };
  1424. /**
  1425. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1426. * This methods computes transformed normalized direction vectors only.
  1427. */
  1428. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1429. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1430. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1431. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1432. result.x = x;
  1433. result.y = y;
  1434. result.z = z;
  1435. };
  1436. /**
  1437. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1438. * This methods computes transformed normalized direction vectors only.
  1439. */
  1440. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1441. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1442. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1443. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1444. };
  1445. /**
  1446. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1447. */
  1448. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1449. var squared = amount * amount;
  1450. var cubed = amount * squared;
  1451. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1452. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1453. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1454. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1455. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1456. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1457. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1458. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1459. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1460. return new Vector3(x, y, z);
  1461. };
  1462. /**
  1463. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1464. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1465. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1466. */
  1467. Vector3.Clamp = function (value, min, max) {
  1468. var x = value.x;
  1469. x = (x > max.x) ? max.x : x;
  1470. x = (x < min.x) ? min.x : x;
  1471. var y = value.y;
  1472. y = (y > max.y) ? max.y : y;
  1473. y = (y < min.y) ? min.y : y;
  1474. var z = value.z;
  1475. z = (z > max.z) ? max.z : z;
  1476. z = (z < min.z) ? min.z : z;
  1477. return new Vector3(x, y, z);
  1478. };
  1479. /**
  1480. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1481. */
  1482. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1483. var squared = amount * amount;
  1484. var cubed = amount * squared;
  1485. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1486. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1487. var part3 = (cubed - (2.0 * squared)) + amount;
  1488. var part4 = cubed - squared;
  1489. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1490. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1491. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1492. return new Vector3(x, y, z);
  1493. };
  1494. /**
  1495. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1496. */
  1497. Vector3.Lerp = function (start, end, amount) {
  1498. var result = new Vector3(0, 0, 0);
  1499. Vector3.LerpToRef(start, end, amount, result);
  1500. return result;
  1501. };
  1502. /**
  1503. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1504. */
  1505. Vector3.LerpToRef = function (start, end, amount, result) {
  1506. result.x = start.x + ((end.x - start.x) * amount);
  1507. result.y = start.y + ((end.y - start.y) * amount);
  1508. result.z = start.z + ((end.z - start.z) * amount);
  1509. };
  1510. /**
  1511. * Returns the dot product (float) between the vectors "left" and "right".
  1512. */
  1513. Vector3.Dot = function (left, right) {
  1514. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1515. };
  1516. /**
  1517. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1518. * The cross product is then orthogonal to both "left" and "right".
  1519. */
  1520. Vector3.Cross = function (left, right) {
  1521. var result = Vector3.Zero();
  1522. Vector3.CrossToRef(left, right, result);
  1523. return result;
  1524. };
  1525. /**
  1526. * Sets the passed vector "result" with the cross product of "left" and "right".
  1527. * The cross product is then orthogonal to both "left" and "right".
  1528. */
  1529. Vector3.CrossToRef = function (left, right, result) {
  1530. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1531. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1532. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1533. result.copyFrom(MathTmp.Vector3[0]);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 as the normalization of the passed vector.
  1537. */
  1538. Vector3.Normalize = function (vector) {
  1539. var result = Vector3.Zero();
  1540. Vector3.NormalizeToRef(vector, result);
  1541. return result;
  1542. };
  1543. /**
  1544. * Sets the passed vector "result" with the normalization of the passed first vector.
  1545. */
  1546. Vector3.NormalizeToRef = function (vector, result) {
  1547. result.copyFrom(vector);
  1548. result.normalize();
  1549. };
  1550. Vector3.Project = function (vector, world, transform, viewport) {
  1551. var cw = viewport.width;
  1552. var ch = viewport.height;
  1553. var cx = viewport.x;
  1554. var cy = viewport.y;
  1555. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1556. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1557. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1558. world.multiplyToRef(transform, matrix);
  1559. matrix.multiplyToRef(viewportMatrix, matrix);
  1560. return Vector3.TransformCoordinates(vector, matrix);
  1561. };
  1562. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1563. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1564. world.multiplyToRef(transform, matrix);
  1565. matrix.invert();
  1566. source.x = source.x / viewportWidth * 2 - 1;
  1567. source.y = -(source.y / viewportHeight * 2 - 1);
  1568. var vector = Vector3.TransformCoordinates(source, matrix);
  1569. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1570. if (MathTools.WithinEpsilon(num, 1.0)) {
  1571. vector = vector.scale(1.0 / num);
  1572. }
  1573. return vector;
  1574. };
  1575. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1576. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1577. world.multiplyToRef(view, matrix);
  1578. matrix.multiplyToRef(projection, matrix);
  1579. matrix.invert();
  1580. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1581. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1582. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1583. if (MathTools.WithinEpsilon(num, 1.0)) {
  1584. vector = vector.scale(1.0 / num);
  1585. }
  1586. return vector;
  1587. };
  1588. Vector3.Minimize = function (left, right) {
  1589. var min = left.clone();
  1590. min.MinimizeInPlace(right);
  1591. return min;
  1592. };
  1593. Vector3.Maximize = function (left, right) {
  1594. var max = left.clone();
  1595. max.MaximizeInPlace(right);
  1596. return max;
  1597. };
  1598. /**
  1599. * Returns the distance (float) between the vectors "value1" and "value2".
  1600. */
  1601. Vector3.Distance = function (value1, value2) {
  1602. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1603. };
  1604. /**
  1605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1606. */
  1607. Vector3.DistanceSquared = function (value1, value2) {
  1608. var x = value1.x - value2.x;
  1609. var y = value1.y - value2.y;
  1610. var z = value1.z - value2.z;
  1611. return (x * x) + (y * y) + (z * z);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 located at the center between "value1" and "value2".
  1615. */
  1616. Vector3.Center = function (value1, value2) {
  1617. var center = value1.add(value2);
  1618. center.scaleInPlace(0.5);
  1619. return center;
  1620. };
  1621. /**
  1622. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1623. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1624. * to something in order to rotate it from its local system to the given target system.
  1625. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1626. * Returns a new Vector3.
  1627. */
  1628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1629. var rotation = Vector3.Zero();
  1630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1631. return rotation;
  1632. };
  1633. /**
  1634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1635. */
  1636. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1637. var quat = MathTmp.Quaternion[0];
  1638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1639. quat.toEulerAnglesToRef(ref);
  1640. };
  1641. return Vector3;
  1642. }());
  1643. BABYLON.Vector3 = Vector3;
  1644. //Vector4 class created for EulerAngle class conversion to Quaternion
  1645. var Vector4 = (function () {
  1646. /**
  1647. * Creates a Vector4 object from the passed floats.
  1648. */
  1649. function Vector4(x, y, z, w) {
  1650. this.x = x;
  1651. this.y = y;
  1652. this.z = z;
  1653. this.w = w;
  1654. }
  1655. /**
  1656. * Returns the string with the Vector4 coordinates.
  1657. */
  1658. Vector4.prototype.toString = function () {
  1659. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1660. };
  1661. /**
  1662. * Returns the string "Vector4".
  1663. */
  1664. Vector4.prototype.getClassName = function () {
  1665. return "Vector4";
  1666. };
  1667. /**
  1668. * Returns the Vector4 hash code.
  1669. */
  1670. Vector4.prototype.getHashCode = function () {
  1671. var hash = this.x || 0;
  1672. hash = (hash * 397) ^ (this.y || 0);
  1673. hash = (hash * 397) ^ (this.z || 0);
  1674. hash = (hash * 397) ^ (this.w || 0);
  1675. return hash;
  1676. };
  1677. // Operators
  1678. /**
  1679. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1680. */
  1681. Vector4.prototype.asArray = function () {
  1682. var result = [];
  1683. this.toArray(result, 0);
  1684. return result;
  1685. };
  1686. /**
  1687. * Populates the passed array from the passed index with the Vector4 coordinates.
  1688. * Returns the Vector4.
  1689. */
  1690. Vector4.prototype.toArray = function (array, index) {
  1691. if (index === undefined) {
  1692. index = 0;
  1693. }
  1694. array[index] = this.x;
  1695. array[index + 1] = this.y;
  1696. array[index + 2] = this.z;
  1697. array[index + 3] = this.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Adds the passed vector to the current Vector4.
  1702. * Returns the updated Vector4.
  1703. */
  1704. Vector4.prototype.addInPlace = function (otherVector) {
  1705. this.x += otherVector.x;
  1706. this.y += otherVector.y;
  1707. this.z += otherVector.z;
  1708. this.w += otherVector.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1713. */
  1714. Vector4.prototype.add = function (otherVector) {
  1715. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1716. };
  1717. /**
  1718. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1719. * Returns the current Vector4.
  1720. */
  1721. Vector4.prototype.addToRef = function (otherVector, result) {
  1722. result.x = this.x + otherVector.x;
  1723. result.y = this.y + otherVector.y;
  1724. result.z = this.z + otherVector.z;
  1725. result.w = this.w + otherVector.w;
  1726. return this;
  1727. };
  1728. /**
  1729. * Subtract in place the passed vector from the current Vector4.
  1730. * Returns the updated Vector4.
  1731. */
  1732. Vector4.prototype.subtractInPlace = function (otherVector) {
  1733. this.x -= otherVector.x;
  1734. this.y -= otherVector.y;
  1735. this.z -= otherVector.z;
  1736. this.w -= otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1741. */
  1742. Vector4.prototype.subtract = function (otherVector) {
  1743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1744. };
  1745. /**
  1746. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1747. * Returns the current Vector4.
  1748. */
  1749. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1750. result.x = this.x - otherVector.x;
  1751. result.y = this.y - otherVector.y;
  1752. result.z = this.z - otherVector.z;
  1753. result.w = this.w - otherVector.w;
  1754. return this;
  1755. };
  1756. /**
  1757. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1758. */
  1759. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1760. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1761. };
  1762. /**
  1763. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1764. * Returns the current Vector4.
  1765. */
  1766. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1767. result.x = this.x - x;
  1768. result.y = this.y - y;
  1769. result.z = this.z - z;
  1770. result.w = this.w - w;
  1771. return this;
  1772. };
  1773. /**
  1774. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1775. */
  1776. Vector4.prototype.negate = function () {
  1777. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1778. };
  1779. /**
  1780. * Multiplies the current Vector4 coordinates by scale (float).
  1781. * Returns the updated Vector4.
  1782. */
  1783. Vector4.prototype.scaleInPlace = function (scale) {
  1784. this.x *= scale;
  1785. this.y *= scale;
  1786. this.z *= scale;
  1787. this.w *= scale;
  1788. return this;
  1789. };
  1790. /**
  1791. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1792. */
  1793. Vector4.prototype.scale = function (scale) {
  1794. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1795. };
  1796. /**
  1797. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1798. * Returns the current Vector4.
  1799. */
  1800. Vector4.prototype.scaleToRef = function (scale, result) {
  1801. result.x = this.x * scale;
  1802. result.y = this.y * scale;
  1803. result.z = this.z * scale;
  1804. result.w = this.w * scale;
  1805. return this;
  1806. };
  1807. /**
  1808. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1809. */
  1810. Vector4.prototype.equals = function (otherVector) {
  1811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1812. };
  1813. /**
  1814. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1815. */
  1816. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1817. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1818. return otherVector
  1819. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1820. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1821. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1822. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1823. };
  1824. /**
  1825. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1826. */
  1827. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1828. return this.x === x && this.y === y && this.z === z && this.w === w;
  1829. };
  1830. /**
  1831. * Multiplies in place the current Vector4 by the passed one.
  1832. * Returns the updated Vector4.
  1833. */
  1834. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1835. this.x *= otherVector.x;
  1836. this.y *= otherVector.y;
  1837. this.z *= otherVector.z;
  1838. this.w *= otherVector.w;
  1839. return this;
  1840. };
  1841. /**
  1842. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1843. */
  1844. Vector4.prototype.multiply = function (otherVector) {
  1845. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1846. };
  1847. /**
  1848. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1849. * Returns the current Vector4.
  1850. */
  1851. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1852. result.x = this.x * otherVector.x;
  1853. result.y = this.y * otherVector.y;
  1854. result.z = this.z * otherVector.z;
  1855. result.w = this.w * otherVector.w;
  1856. return this;
  1857. };
  1858. /**
  1859. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1860. */
  1861. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1862. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1863. };
  1864. /**
  1865. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1866. */
  1867. Vector4.prototype.divide = function (otherVector) {
  1868. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1869. };
  1870. /**
  1871. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1872. * Returns the current Vector4.
  1873. */
  1874. Vector4.prototype.divideToRef = function (otherVector, result) {
  1875. result.x = this.x / otherVector.x;
  1876. result.y = this.y / otherVector.y;
  1877. result.z = this.z / otherVector.z;
  1878. result.w = this.w / otherVector.w;
  1879. return this;
  1880. };
  1881. /**
  1882. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1883. */
  1884. Vector4.prototype.MinimizeInPlace = function (other) {
  1885. if (other.x < this.x)
  1886. this.x = other.x;
  1887. if (other.y < this.y)
  1888. this.y = other.y;
  1889. if (other.z < this.z)
  1890. this.z = other.z;
  1891. if (other.w < this.w)
  1892. this.w = other.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1897. */
  1898. Vector4.prototype.MaximizeInPlace = function (other) {
  1899. if (other.x > this.x)
  1900. this.x = other.x;
  1901. if (other.y > this.y)
  1902. this.y = other.y;
  1903. if (other.z > this.z)
  1904. this.z = other.z;
  1905. if (other.w > this.w)
  1906. this.w = other.w;
  1907. return this;
  1908. };
  1909. // Properties
  1910. /**
  1911. * Returns the Vector4 length (float).
  1912. */
  1913. Vector4.prototype.length = function () {
  1914. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1915. };
  1916. /**
  1917. * Returns the Vector4 squared length (float).
  1918. */
  1919. Vector4.prototype.lengthSquared = function () {
  1920. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1921. };
  1922. // Methods
  1923. /**
  1924. * Normalizes in place the Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.normalize = function () {
  1928. var len = this.length();
  1929. if (len === 0)
  1930. return this;
  1931. var num = 1.0 / len;
  1932. this.x *= num;
  1933. this.y *= num;
  1934. this.z *= num;
  1935. this.w *= num;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1940. */
  1941. Vector4.prototype.toVector3 = function () {
  1942. return new Vector3(this.x, this.y, this.z);
  1943. };
  1944. /**
  1945. * Returns a new Vector4 copied from the current one.
  1946. */
  1947. Vector4.prototype.clone = function () {
  1948. return new Vector4(this.x, this.y, this.z, this.w);
  1949. };
  1950. /**
  1951. * Updates the current Vector4 with the passed one coordinates.
  1952. * Returns the updated Vector4.
  1953. */
  1954. Vector4.prototype.copyFrom = function (source) {
  1955. this.x = source.x;
  1956. this.y = source.y;
  1957. this.z = source.z;
  1958. this.w = source.w;
  1959. return this;
  1960. };
  1961. /**
  1962. * Updates the current Vector4 coordinates with the passed floats.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1966. this.x = x;
  1967. this.y = y;
  1968. this.z = z;
  1969. this.w = w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.set = function (x, y, z, w) {
  1977. return this.copyFromFloats(x, y, z, w);
  1978. };
  1979. // Statics
  1980. /**
  1981. * Returns a new Vector4 set from the starting index of the passed array.
  1982. */
  1983. Vector4.FromArray = function (array, offset) {
  1984. if (!offset) {
  1985. offset = 0;
  1986. }
  1987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1988. };
  1989. /**
  1990. * Updates the passed vector "result" from the starting index of the passed array.
  1991. */
  1992. Vector4.FromArrayToRef = function (array, offset, result) {
  1993. result.x = array[offset];
  1994. result.y = array[offset + 1];
  1995. result.z = array[offset + 2];
  1996. result.w = array[offset + 3];
  1997. };
  1998. /**
  1999. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2000. */
  2001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2002. result.x = array[offset];
  2003. result.y = array[offset + 1];
  2004. result.z = array[offset + 2];
  2005. result.w = array[offset + 3];
  2006. };
  2007. /**
  2008. * Updates the passed vector "result" coordinates from the passed floats.
  2009. */
  2010. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2011. result.x = x;
  2012. result.y = y;
  2013. result.z = z;
  2014. result.w = w;
  2015. };
  2016. /**
  2017. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2018. */
  2019. Vector4.Zero = function () {
  2020. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2021. };
  2022. /**
  2023. * Returns a new normalized Vector4 from the passed one.
  2024. */
  2025. Vector4.Normalize = function (vector) {
  2026. var result = Vector4.Zero();
  2027. Vector4.NormalizeToRef(vector, result);
  2028. return result;
  2029. };
  2030. /**
  2031. * Updates the passed vector "result" from the normalization of the passed one.
  2032. */
  2033. Vector4.NormalizeToRef = function (vector, result) {
  2034. result.copyFrom(vector);
  2035. result.normalize();
  2036. };
  2037. Vector4.Minimize = function (left, right) {
  2038. var min = left.clone();
  2039. min.MinimizeInPlace(right);
  2040. return min;
  2041. };
  2042. Vector4.Maximize = function (left, right) {
  2043. var max = left.clone();
  2044. max.MaximizeInPlace(right);
  2045. return max;
  2046. };
  2047. /**
  2048. * Returns the distance (float) between the vectors "value1" and "value2".
  2049. */
  2050. Vector4.Distance = function (value1, value2) {
  2051. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2052. };
  2053. /**
  2054. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2055. */
  2056. Vector4.DistanceSquared = function (value1, value2) {
  2057. var x = value1.x - value2.x;
  2058. var y = value1.y - value2.y;
  2059. var z = value1.z - value2.z;
  2060. var w = value1.w - value2.w;
  2061. return (x * x) + (y * y) + (z * z) + (w * w);
  2062. };
  2063. /**
  2064. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2065. */
  2066. Vector4.Center = function (value1, value2) {
  2067. var center = value1.add(value2);
  2068. center.scaleInPlace(0.5);
  2069. return center;
  2070. };
  2071. /**
  2072. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2073. * This methods computes transformed normalized direction vectors only.
  2074. */
  2075. Vector4.TransformNormal = function (vector, transformation) {
  2076. var result = Vector4.Zero();
  2077. Vector4.TransformNormalToRef(vector, transformation, result);
  2078. return result;
  2079. };
  2080. /**
  2081. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2082. * This methods computes transformed normalized direction vectors only.
  2083. */
  2084. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2085. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2086. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2087. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2088. result.x = x;
  2089. result.y = y;
  2090. result.z = z;
  2091. result.w = vector.w;
  2092. };
  2093. /**
  2094. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2095. * This methods computes transformed normalized direction vectors only.
  2096. */
  2097. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2098. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2099. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2100. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2101. result.w = w;
  2102. };
  2103. return Vector4;
  2104. }());
  2105. BABYLON.Vector4 = Vector4;
  2106. var Size = (function () {
  2107. /**
  2108. * Creates a Size object from the passed width and height (floats).
  2109. */
  2110. function Size(width, height) {
  2111. this.width = width;
  2112. this.height = height;
  2113. }
  2114. // Returns a string with the Size width and height.
  2115. Size.prototype.toString = function () {
  2116. return "{W: " + this.width + ", H: " + this.height + "}";
  2117. };
  2118. /**
  2119. * Returns the string "Size"
  2120. */
  2121. Size.prototype.getClassName = function () {
  2122. return "Size";
  2123. };
  2124. /**
  2125. * Returns the Size hash code.
  2126. */
  2127. Size.prototype.getHashCode = function () {
  2128. var hash = this.width || 0;
  2129. hash = (hash * 397) ^ (this.height || 0);
  2130. return hash;
  2131. };
  2132. /**
  2133. * Updates the current size from the passed one.
  2134. * Returns the updated Size.
  2135. */
  2136. Size.prototype.copyFrom = function (src) {
  2137. this.width = src.width;
  2138. this.height = src.height;
  2139. };
  2140. /**
  2141. * Updates in place the current Size from the passed floats.
  2142. * Returns the updated Size.
  2143. */
  2144. Size.prototype.copyFromFloats = function (width, height) {
  2145. this.width = width;
  2146. this.height = height;
  2147. return this;
  2148. };
  2149. /**
  2150. * Updates in place the current Size from the passed floats.
  2151. * Returns the updated Size.
  2152. */
  2153. Size.prototype.set = function (width, height) {
  2154. return this.copyFromFloats(width, height);
  2155. };
  2156. /**
  2157. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2158. */
  2159. Size.prototype.multiplyByFloats = function (w, h) {
  2160. return new Size(this.width * w, this.height * h);
  2161. };
  2162. /**
  2163. * Returns a new Size copied from the passed one.
  2164. */
  2165. Size.prototype.clone = function () {
  2166. return new Size(this.width, this.height);
  2167. };
  2168. /**
  2169. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2170. */
  2171. Size.prototype.equals = function (other) {
  2172. if (!other) {
  2173. return false;
  2174. }
  2175. return (this.width === other.width) && (this.height === other.height);
  2176. };
  2177. Object.defineProperty(Size.prototype, "surface", {
  2178. /**
  2179. * Returns the surface of the Size : width * height (float).
  2180. */
  2181. get: function () {
  2182. return this.width * this.height;
  2183. },
  2184. enumerable: true,
  2185. configurable: true
  2186. });
  2187. /**
  2188. * Returns a new Size set to (0.0, 0.0)
  2189. */
  2190. Size.Zero = function () {
  2191. return new Size(0.0, 0.0);
  2192. };
  2193. /**
  2194. * Returns a new Size set as the addition result of the current Size and the passed one.
  2195. */
  2196. Size.prototype.add = function (otherSize) {
  2197. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2198. return r;
  2199. };
  2200. /**
  2201. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2202. */
  2203. Size.prototype.subtract = function (otherSize) {
  2204. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2205. return r;
  2206. };
  2207. /**
  2208. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2209. */
  2210. Size.Lerp = function (start, end, amount) {
  2211. var w = start.width + ((end.width - start.width) * amount);
  2212. var h = start.height + ((end.height - start.height) * amount);
  2213. return new Size(w, h);
  2214. };
  2215. return Size;
  2216. }());
  2217. BABYLON.Size = Size;
  2218. var Quaternion = (function () {
  2219. /**
  2220. * Creates a new Quaternion from the passed floats.
  2221. */
  2222. function Quaternion(x, y, z, w) {
  2223. if (x === void 0) { x = 0.0; }
  2224. if (y === void 0) { y = 0.0; }
  2225. if (z === void 0) { z = 0.0; }
  2226. if (w === void 0) { w = 1.0; }
  2227. this.x = x;
  2228. this.y = y;
  2229. this.z = z;
  2230. this.w = w;
  2231. }
  2232. /**
  2233. * Returns a string with the Quaternion coordinates.
  2234. */
  2235. Quaternion.prototype.toString = function () {
  2236. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2237. };
  2238. /**
  2239. * Returns the string "Quaternion".
  2240. */
  2241. Quaternion.prototype.getClassName = function () {
  2242. return "Quaternion";
  2243. };
  2244. /**
  2245. * Returns the Quaternion hash code.
  2246. */
  2247. Quaternion.prototype.getHashCode = function () {
  2248. var hash = this.x || 0;
  2249. hash = (hash * 397) ^ (this.y || 0);
  2250. hash = (hash * 397) ^ (this.z || 0);
  2251. hash = (hash * 397) ^ (this.w || 0);
  2252. return hash;
  2253. };
  2254. /**
  2255. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2256. */
  2257. Quaternion.prototype.asArray = function () {
  2258. return [this.x, this.y, this.z, this.w];
  2259. };
  2260. /**
  2261. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2262. */
  2263. Quaternion.prototype.equals = function (otherQuaternion) {
  2264. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2265. };
  2266. /**
  2267. * Returns a new Quaternion copied from the current one.
  2268. */
  2269. Quaternion.prototype.clone = function () {
  2270. return new Quaternion(this.x, this.y, this.z, this.w);
  2271. };
  2272. /**
  2273. * Updates the current Quaternion from the passed one coordinates.
  2274. * Returns the updated Quaterion.
  2275. */
  2276. Quaternion.prototype.copyFrom = function (other) {
  2277. this.x = other.x;
  2278. this.y = other.y;
  2279. this.z = other.z;
  2280. this.w = other.w;
  2281. return this;
  2282. };
  2283. /**
  2284. * Updates the current Quaternion from the passed float coordinates.
  2285. * Returns the updated Quaterion.
  2286. */
  2287. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2288. this.x = x;
  2289. this.y = y;
  2290. this.z = z;
  2291. this.w = w;
  2292. return this;
  2293. };
  2294. /**
  2295. * Updates the current Quaternion from the passed float coordinates.
  2296. * Returns the updated Quaterion.
  2297. */
  2298. Quaternion.prototype.set = function (x, y, z, w) {
  2299. return this.copyFromFloats(x, y, z, w);
  2300. };
  2301. /**
  2302. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2303. */
  2304. Quaternion.prototype.add = function (other) {
  2305. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2306. };
  2307. /**
  2308. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2309. */
  2310. Quaternion.prototype.subtract = function (other) {
  2311. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2312. };
  2313. /**
  2314. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2315. */
  2316. Quaternion.prototype.scale = function (value) {
  2317. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2318. };
  2319. /**
  2320. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2321. */
  2322. Quaternion.prototype.multiply = function (q1) {
  2323. var result = new Quaternion(0, 0, 0, 1.0);
  2324. this.multiplyToRef(q1, result);
  2325. return result;
  2326. };
  2327. /**
  2328. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2329. * Returns the current Quaternion.
  2330. */
  2331. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2332. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2333. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2334. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2335. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2336. result.copyFromFloats(x, y, z, w);
  2337. return this;
  2338. };
  2339. /**
  2340. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2341. * Returns the updated Quaternion.
  2342. */
  2343. Quaternion.prototype.multiplyInPlace = function (q1) {
  2344. this.multiplyToRef(q1, this);
  2345. return this;
  2346. };
  2347. /**
  2348. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2349. * Returns the current Quaternion.
  2350. */
  2351. Quaternion.prototype.conjugateToRef = function (ref) {
  2352. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2353. return this;
  2354. };
  2355. /**
  2356. * Conjugates in place the current Quaternion.
  2357. * Returns the updated Quaternion.
  2358. */
  2359. Quaternion.prototype.conjugateInPlace = function () {
  2360. this.x *= -1;
  2361. this.y *= -1;
  2362. this.z *= -1;
  2363. return this;
  2364. };
  2365. /**
  2366. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2367. */
  2368. Quaternion.prototype.conjugate = function () {
  2369. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2370. return result;
  2371. };
  2372. /**
  2373. * Returns the Quaternion length (float).
  2374. */
  2375. Quaternion.prototype.length = function () {
  2376. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2377. };
  2378. /**
  2379. * Normalize in place the current Quaternion.
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.normalize = function () {
  2383. var length = 1.0 / this.length();
  2384. this.x *= length;
  2385. this.y *= length;
  2386. this.z *= length;
  2387. this.w *= length;
  2388. return this;
  2389. };
  2390. /**
  2391. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2392. */
  2393. Quaternion.prototype.toEulerAngles = function (order) {
  2394. if (order === void 0) { order = "YZX"; }
  2395. var result = Vector3.Zero();
  2396. this.toEulerAnglesToRef(result, order);
  2397. return result;
  2398. };
  2399. /**
  2400. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2401. * Returns the current Quaternion.
  2402. */
  2403. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2404. if (order === void 0) { order = "YZX"; }
  2405. var qz = this.z;
  2406. var qx = this.x;
  2407. var qy = this.y;
  2408. var qw = this.w;
  2409. var sqw = qw * qw;
  2410. var sqz = qz * qz;
  2411. var sqx = qx * qx;
  2412. var sqy = qy * qy;
  2413. var zAxisY = qy * qz - qx * qw;
  2414. var limit = .4999999;
  2415. if (zAxisY < -limit) {
  2416. result.y = 2 * Math.atan2(qy, qw);
  2417. result.x = Math.PI / 2;
  2418. result.z = 0;
  2419. }
  2420. else if (zAxisY > limit) {
  2421. result.y = 2 * Math.atan2(qy, qw);
  2422. result.x = -Math.PI / 2;
  2423. result.z = 0;
  2424. }
  2425. else {
  2426. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2427. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2428. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2429. }
  2430. return this;
  2431. };
  2432. /**
  2433. * Updates the passed rotation matrix with the current Quaternion values.
  2434. * Returns the current Quaternion.
  2435. */
  2436. Quaternion.prototype.toRotationMatrix = function (result) {
  2437. var xx = this.x * this.x;
  2438. var yy = this.y * this.y;
  2439. var zz = this.z * this.z;
  2440. var xy = this.x * this.y;
  2441. var zw = this.z * this.w;
  2442. var zx = this.z * this.x;
  2443. var yw = this.y * this.w;
  2444. var yz = this.y * this.z;
  2445. var xw = this.x * this.w;
  2446. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2447. result.m[1] = 2.0 * (xy + zw);
  2448. result.m[2] = 2.0 * (zx - yw);
  2449. result.m[3] = 0;
  2450. result.m[4] = 2.0 * (xy - zw);
  2451. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2452. result.m[6] = 2.0 * (yz + xw);
  2453. result.m[7] = 0;
  2454. result.m[8] = 2.0 * (zx + yw);
  2455. result.m[9] = 2.0 * (yz - xw);
  2456. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2457. result.m[11] = 0;
  2458. result.m[12] = 0;
  2459. result.m[13] = 0;
  2460. result.m[14] = 0;
  2461. result.m[15] = 1.0;
  2462. return this;
  2463. };
  2464. /**
  2465. * Updates the current Quaternion from the passed rotation matrix values.
  2466. * Returns the updated Quaternion.
  2467. */
  2468. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2469. Quaternion.FromRotationMatrixToRef(matrix, this);
  2470. return this;
  2471. };
  2472. // Statics
  2473. /**
  2474. * Returns a new Quaternion set from the passed rotation matrix values.
  2475. */
  2476. Quaternion.FromRotationMatrix = function (matrix) {
  2477. var result = new Quaternion();
  2478. Quaternion.FromRotationMatrixToRef(matrix, result);
  2479. return result;
  2480. };
  2481. /**
  2482. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2483. */
  2484. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2485. var data = matrix.m;
  2486. var m11 = data[0], m12 = data[4], m13 = data[8];
  2487. var m21 = data[1], m22 = data[5], m23 = data[9];
  2488. var m31 = data[2], m32 = data[6], m33 = data[10];
  2489. var trace = m11 + m22 + m33;
  2490. var s;
  2491. if (trace > 0) {
  2492. s = 0.5 / Math.sqrt(trace + 1.0);
  2493. result.w = 0.25 / s;
  2494. result.x = (m32 - m23) * s;
  2495. result.y = (m13 - m31) * s;
  2496. result.z = (m21 - m12) * s;
  2497. }
  2498. else if (m11 > m22 && m11 > m33) {
  2499. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2500. result.w = (m32 - m23) / s;
  2501. result.x = 0.25 * s;
  2502. result.y = (m12 + m21) / s;
  2503. result.z = (m13 + m31) / s;
  2504. }
  2505. else if (m22 > m33) {
  2506. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2507. result.w = (m13 - m31) / s;
  2508. result.x = (m12 + m21) / s;
  2509. result.y = 0.25 * s;
  2510. result.z = (m23 + m32) / s;
  2511. }
  2512. else {
  2513. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2514. result.w = (m21 - m12) / s;
  2515. result.x = (m13 + m31) / s;
  2516. result.y = (m23 + m32) / s;
  2517. result.z = 0.25 * s;
  2518. }
  2519. };
  2520. /**
  2521. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2522. */
  2523. Quaternion.Zero = function () {
  2524. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2525. };
  2526. /**
  2527. * Returns a new Quaternion as the inverted current Quaternion.
  2528. */
  2529. Quaternion.Inverse = function (q) {
  2530. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2531. };
  2532. /**
  2533. * Returns the identity Quaternion.
  2534. */
  2535. Quaternion.Identity = function () {
  2536. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2537. };
  2538. Quaternion.IsIdentity = function (quaternion) {
  2539. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2543. */
  2544. Quaternion.RotationAxis = function (axis, angle) {
  2545. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2546. };
  2547. /**
  2548. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2549. */
  2550. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2551. var sin = Math.sin(angle / 2);
  2552. axis.normalize();
  2553. result.w = Math.cos(angle / 2);
  2554. result.x = axis.x * sin;
  2555. result.y = axis.y * sin;
  2556. result.z = axis.z * sin;
  2557. return result;
  2558. };
  2559. /**
  2560. * Retuns a new Quaternion set from the starting index of the passed array.
  2561. */
  2562. Quaternion.FromArray = function (array, offset) {
  2563. if (!offset) {
  2564. offset = 0;
  2565. }
  2566. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2567. };
  2568. /**
  2569. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2570. */
  2571. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2572. var q = new Quaternion();
  2573. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2574. return q;
  2575. };
  2576. /**
  2577. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2578. */
  2579. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2580. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2581. var halfRoll = roll * 0.5;
  2582. var halfPitch = pitch * 0.5;
  2583. var halfYaw = yaw * 0.5;
  2584. var sinRoll = Math.sin(halfRoll);
  2585. var cosRoll = Math.cos(halfRoll);
  2586. var sinPitch = Math.sin(halfPitch);
  2587. var cosPitch = Math.cos(halfPitch);
  2588. var sinYaw = Math.sin(halfYaw);
  2589. var cosYaw = Math.cos(halfYaw);
  2590. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2591. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2592. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2593. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2594. };
  2595. /**
  2596. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2597. */
  2598. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2599. var result = new Quaternion();
  2600. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2601. return result;
  2602. };
  2603. /**
  2604. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2605. */
  2606. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2607. // Produces a quaternion from Euler angles in the z-x-z orientation
  2608. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2609. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2610. var halfBeta = beta * 0.5;
  2611. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2612. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2613. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2614. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2615. };
  2616. /**
  2617. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2618. * cf to Vector3.RotationFromAxis() documentation.
  2619. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2620. */
  2621. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2622. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2623. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2624. return quat;
  2625. };
  2626. /**
  2627. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2628. * cf to Vector3.RotationFromAxis() documentation.
  2629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2630. */
  2631. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2632. var rotMat = MathTmp.Matrix[0];
  2633. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2634. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2635. };
  2636. Quaternion.Slerp = function (left, right, amount) {
  2637. var result = Quaternion.Identity();
  2638. Quaternion.SlerpToRef(left, right, amount, result);
  2639. return result;
  2640. };
  2641. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2642. var num2;
  2643. var num3;
  2644. var num = amount;
  2645. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2646. var flag = false;
  2647. if (num4 < 0) {
  2648. flag = true;
  2649. num4 = -num4;
  2650. }
  2651. if (num4 > 0.999999) {
  2652. num3 = 1 - num;
  2653. num2 = flag ? -num : num;
  2654. }
  2655. else {
  2656. var num5 = Math.acos(num4);
  2657. var num6 = (1.0 / Math.sin(num5));
  2658. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2659. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2660. }
  2661. result.x = (num3 * left.x) + (num2 * right.x);
  2662. result.y = (num3 * left.y) + (num2 * right.y);
  2663. result.z = (num3 * left.z) + (num2 * right.z);
  2664. result.w = (num3 * left.w) + (num2 * right.w);
  2665. };
  2666. return Quaternion;
  2667. }());
  2668. BABYLON.Quaternion = Quaternion;
  2669. var Matrix = (function () {
  2670. function Matrix() {
  2671. this.m = new Float32Array(16);
  2672. }
  2673. // Properties
  2674. /**
  2675. * Boolean : True is the matrix is the identity matrix
  2676. */
  2677. Matrix.prototype.isIdentity = function () {
  2678. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2679. return false;
  2680. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2681. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2682. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2683. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2684. return false;
  2685. return true;
  2686. };
  2687. /**
  2688. * Returns the matrix determinant (float).
  2689. */
  2690. Matrix.prototype.determinant = function () {
  2691. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2692. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2693. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2694. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2695. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2696. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2697. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2698. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2699. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2700. };
  2701. // Methods
  2702. /**
  2703. * Returns the matrix underlying array.
  2704. */
  2705. Matrix.prototype.toArray = function () {
  2706. return this.m;
  2707. };
  2708. /**
  2709. * Returns the matrix underlying array.
  2710. */
  2711. Matrix.prototype.asArray = function () {
  2712. return this.toArray();
  2713. };
  2714. /**
  2715. * Inverts in place the Matrix.
  2716. * Returns the Matrix inverted.
  2717. */
  2718. Matrix.prototype.invert = function () {
  2719. this.invertToRef(this);
  2720. return this;
  2721. };
  2722. /**
  2723. * Sets all the matrix elements to zero.
  2724. * Returns the Matrix.
  2725. */
  2726. Matrix.prototype.reset = function () {
  2727. for (var index = 0; index < 16; index++) {
  2728. this.m[index] = 0.0;
  2729. }
  2730. return this;
  2731. };
  2732. /**
  2733. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2734. */
  2735. Matrix.prototype.add = function (other) {
  2736. var result = new Matrix();
  2737. this.addToRef(other, result);
  2738. return result;
  2739. };
  2740. /**
  2741. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2742. * Returns the Matrix.
  2743. */
  2744. Matrix.prototype.addToRef = function (other, result) {
  2745. for (var index = 0; index < 16; index++) {
  2746. result.m[index] = this.m[index] + other.m[index];
  2747. }
  2748. return this;
  2749. };
  2750. /**
  2751. * Adds in place the passed matrix to the current Matrix.
  2752. * Returns the updated Matrix.
  2753. */
  2754. Matrix.prototype.addToSelf = function (other) {
  2755. for (var index = 0; index < 16; index++) {
  2756. this.m[index] += other.m[index];
  2757. }
  2758. return this;
  2759. };
  2760. /**
  2761. * Sets the passed matrix with the current inverted Matrix.
  2762. * Returns the unmodified current Matrix.
  2763. */
  2764. Matrix.prototype.invertToRef = function (other) {
  2765. var l1 = this.m[0];
  2766. var l2 = this.m[1];
  2767. var l3 = this.m[2];
  2768. var l4 = this.m[3];
  2769. var l5 = this.m[4];
  2770. var l6 = this.m[5];
  2771. var l7 = this.m[6];
  2772. var l8 = this.m[7];
  2773. var l9 = this.m[8];
  2774. var l10 = this.m[9];
  2775. var l11 = this.m[10];
  2776. var l12 = this.m[11];
  2777. var l13 = this.m[12];
  2778. var l14 = this.m[13];
  2779. var l15 = this.m[14];
  2780. var l16 = this.m[15];
  2781. var l17 = (l11 * l16) - (l12 * l15);
  2782. var l18 = (l10 * l16) - (l12 * l14);
  2783. var l19 = (l10 * l15) - (l11 * l14);
  2784. var l20 = (l9 * l16) - (l12 * l13);
  2785. var l21 = (l9 * l15) - (l11 * l13);
  2786. var l22 = (l9 * l14) - (l10 * l13);
  2787. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2788. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2789. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2790. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2791. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2792. var l28 = (l7 * l16) - (l8 * l15);
  2793. var l29 = (l6 * l16) - (l8 * l14);
  2794. var l30 = (l6 * l15) - (l7 * l14);
  2795. var l31 = (l5 * l16) - (l8 * l13);
  2796. var l32 = (l5 * l15) - (l7 * l13);
  2797. var l33 = (l5 * l14) - (l6 * l13);
  2798. var l34 = (l7 * l12) - (l8 * l11);
  2799. var l35 = (l6 * l12) - (l8 * l10);
  2800. var l36 = (l6 * l11) - (l7 * l10);
  2801. var l37 = (l5 * l12) - (l8 * l9);
  2802. var l38 = (l5 * l11) - (l7 * l9);
  2803. var l39 = (l5 * l10) - (l6 * l9);
  2804. other.m[0] = l23 * l27;
  2805. other.m[4] = l24 * l27;
  2806. other.m[8] = l25 * l27;
  2807. other.m[12] = l26 * l27;
  2808. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2809. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2810. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2811. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2812. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2813. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2814. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2815. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2816. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2817. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2818. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2819. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2820. return this;
  2821. };
  2822. /**
  2823. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2824. * Returns the updated Matrix.
  2825. */
  2826. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2827. this.m[12] = x;
  2828. this.m[13] = y;
  2829. this.m[14] = z;
  2830. return this;
  2831. };
  2832. /**
  2833. * Inserts the translation vector in the current Matrix.
  2834. * Returns the updated Matrix.
  2835. */
  2836. Matrix.prototype.setTranslation = function (vector3) {
  2837. this.m[12] = vector3.x;
  2838. this.m[13] = vector3.y;
  2839. this.m[14] = vector3.z;
  2840. return this;
  2841. };
  2842. /**
  2843. * Returns a new Vector3 as the extracted translation from the Matrix.
  2844. */
  2845. Matrix.prototype.getTranslation = function () {
  2846. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2847. };
  2848. /**
  2849. * Fill a Vector3 with the extracted translation from the Matrix.
  2850. */
  2851. Matrix.prototype.getTranslationToRef = function (result) {
  2852. result.x = this.m[12];
  2853. result.y = this.m[13];
  2854. result.z = this.m[14];
  2855. return this;
  2856. };
  2857. /**
  2858. * Remove rotation and scaling part from the Matrix.
  2859. * Returns the updated Matrix.
  2860. */
  2861. Matrix.prototype.removeRotationAndScaling = function () {
  2862. this.setRowFromFloats(0, 1, 0, 0, 0);
  2863. this.setRowFromFloats(1, 0, 1, 0, 0);
  2864. this.setRowFromFloats(2, 0, 0, 1, 0);
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2869. */
  2870. Matrix.prototype.multiply = function (other) {
  2871. var result = new Matrix();
  2872. this.multiplyToRef(other, result);
  2873. return result;
  2874. };
  2875. /**
  2876. * Updates the current Matrix from the passed one values.
  2877. * Returns the updated Matrix.
  2878. */
  2879. Matrix.prototype.copyFrom = function (other) {
  2880. for (var index = 0; index < 16; index++) {
  2881. this.m[index] = other.m[index];
  2882. }
  2883. return this;
  2884. };
  2885. /**
  2886. * Populates the passed array from the starting index with the Matrix values.
  2887. * Returns the Matrix.
  2888. */
  2889. Matrix.prototype.copyToArray = function (array, offset) {
  2890. if (offset === void 0) { offset = 0; }
  2891. for (var index = 0; index < 16; index++) {
  2892. array[offset + index] = this.m[index];
  2893. }
  2894. return this;
  2895. };
  2896. /**
  2897. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2898. */
  2899. Matrix.prototype.multiplyToRef = function (other, result) {
  2900. this.multiplyToArray(other, result.m, 0);
  2901. return this;
  2902. };
  2903. /**
  2904. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2905. */
  2906. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2907. var tm0 = this.m[0];
  2908. var tm1 = this.m[1];
  2909. var tm2 = this.m[2];
  2910. var tm3 = this.m[3];
  2911. var tm4 = this.m[4];
  2912. var tm5 = this.m[5];
  2913. var tm6 = this.m[6];
  2914. var tm7 = this.m[7];
  2915. var tm8 = this.m[8];
  2916. var tm9 = this.m[9];
  2917. var tm10 = this.m[10];
  2918. var tm11 = this.m[11];
  2919. var tm12 = this.m[12];
  2920. var tm13 = this.m[13];
  2921. var tm14 = this.m[14];
  2922. var tm15 = this.m[15];
  2923. var om0 = other.m[0];
  2924. var om1 = other.m[1];
  2925. var om2 = other.m[2];
  2926. var om3 = other.m[3];
  2927. var om4 = other.m[4];
  2928. var om5 = other.m[5];
  2929. var om6 = other.m[6];
  2930. var om7 = other.m[7];
  2931. var om8 = other.m[8];
  2932. var om9 = other.m[9];
  2933. var om10 = other.m[10];
  2934. var om11 = other.m[11];
  2935. var om12 = other.m[12];
  2936. var om13 = other.m[13];
  2937. var om14 = other.m[14];
  2938. var om15 = other.m[15];
  2939. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2940. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2941. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2942. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2943. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2944. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2945. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2946. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2947. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2948. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2949. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2950. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2951. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2952. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2953. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2954. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2955. return this;
  2956. };
  2957. /**
  2958. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2959. */
  2960. Matrix.prototype.equals = function (value) {
  2961. return value &&
  2962. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2963. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2964. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2965. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2966. };
  2967. /**
  2968. * Returns a new Matrix from the current Matrix.
  2969. */
  2970. Matrix.prototype.clone = function () {
  2971. 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]);
  2972. };
  2973. /**
  2974. * Returns the string "Matrix"
  2975. */
  2976. Matrix.prototype.getClassName = function () {
  2977. return "Matrix";
  2978. };
  2979. /**
  2980. * Returns the Matrix hash code.
  2981. */
  2982. Matrix.prototype.getHashCode = function () {
  2983. var hash = this.m[0] || 0;
  2984. for (var i = 1; i < 16; i++) {
  2985. hash = (hash * 397) ^ (this.m[i] || 0);
  2986. }
  2987. return hash;
  2988. };
  2989. /**
  2990. * Decomposes the current Matrix into :
  2991. * - a scale vector3 passed as a reference to update,
  2992. * - a rotation quaternion passed as a reference to update,
  2993. * - a translation vector3 passed as a reference to update.
  2994. * Returns the boolean `true`.
  2995. */
  2996. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2997. translation.x = this.m[12];
  2998. translation.y = this.m[13];
  2999. translation.z = this.m[14];
  3000. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3001. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3002. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3003. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3004. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3005. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3006. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3007. rotation.x = 0;
  3008. rotation.y = 0;
  3009. rotation.z = 0;
  3010. rotation.w = 1;
  3011. return false;
  3012. }
  3013. 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, MathTmp.Matrix[0]);
  3014. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3015. return true;
  3016. };
  3017. /**
  3018. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3019. */
  3020. Matrix.prototype.getRotationMatrix = function () {
  3021. var result = Matrix.Identity();
  3022. this.getRotationMatrixToRef(result);
  3023. return result;
  3024. };
  3025. /**
  3026. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3027. * Returns the current Matrix.
  3028. */
  3029. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3030. var m = this.m;
  3031. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3032. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3033. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3034. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3035. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3036. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3037. 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);
  3038. return this;
  3039. };
  3040. // Statics
  3041. /**
  3042. * Returns a new Matrix set from the starting index of the passed array.
  3043. */
  3044. Matrix.FromArray = function (array, offset) {
  3045. var result = new Matrix();
  3046. if (!offset) {
  3047. offset = 0;
  3048. }
  3049. Matrix.FromArrayToRef(array, offset, result);
  3050. return result;
  3051. };
  3052. /**
  3053. * Sets the passed "result" matrix from the starting index of the passed array.
  3054. */
  3055. Matrix.FromArrayToRef = function (array, offset, result) {
  3056. for (var index = 0; index < 16; index++) {
  3057. result.m[index] = array[index + offset];
  3058. }
  3059. };
  3060. /**
  3061. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3062. */
  3063. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3064. for (var index = 0; index < 16; index++) {
  3065. result.m[index] = array[index + offset] * scale;
  3066. }
  3067. };
  3068. /**
  3069. * Sets the passed matrix "result" with the 16 passed floats.
  3070. */
  3071. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3072. result.m[0] = initialM11;
  3073. result.m[1] = initialM12;
  3074. result.m[2] = initialM13;
  3075. result.m[3] = initialM14;
  3076. result.m[4] = initialM21;
  3077. result.m[5] = initialM22;
  3078. result.m[6] = initialM23;
  3079. result.m[7] = initialM24;
  3080. result.m[8] = initialM31;
  3081. result.m[9] = initialM32;
  3082. result.m[10] = initialM33;
  3083. result.m[11] = initialM34;
  3084. result.m[12] = initialM41;
  3085. result.m[13] = initialM42;
  3086. result.m[14] = initialM43;
  3087. result.m[15] = initialM44;
  3088. };
  3089. /**
  3090. * Returns the index-th row of the current matrix as a new Vector4.
  3091. */
  3092. Matrix.prototype.getRow = function (index) {
  3093. if (index < 0 || index > 3) {
  3094. return null;
  3095. }
  3096. var i = index * 4;
  3097. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3098. };
  3099. /**
  3100. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3101. * Returns the updated Matrix.
  3102. */
  3103. Matrix.prototype.setRow = function (index, row) {
  3104. if (index < 0 || index > 3) {
  3105. return this;
  3106. }
  3107. var i = index * 4;
  3108. this.m[i + 0] = row.x;
  3109. this.m[i + 1] = row.y;
  3110. this.m[i + 2] = row.z;
  3111. this.m[i + 3] = row.w;
  3112. return this;
  3113. };
  3114. /**
  3115. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3116. * Returns the updated Matrix.
  3117. */
  3118. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3119. if (index < 0 || index > 3) {
  3120. return this;
  3121. }
  3122. var i = index * 4;
  3123. this.m[i + 0] = x;
  3124. this.m[i + 1] = y;
  3125. this.m[i + 2] = z;
  3126. this.m[i + 3] = w;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Matrix set from the 16 passed floats.
  3131. */
  3132. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3133. var result = new Matrix();
  3134. result.m[0] = initialM11;
  3135. result.m[1] = initialM12;
  3136. result.m[2] = initialM13;
  3137. result.m[3] = initialM14;
  3138. result.m[4] = initialM21;
  3139. result.m[5] = initialM22;
  3140. result.m[6] = initialM23;
  3141. result.m[7] = initialM24;
  3142. result.m[8] = initialM31;
  3143. result.m[9] = initialM32;
  3144. result.m[10] = initialM33;
  3145. result.m[11] = initialM34;
  3146. result.m[12] = initialM41;
  3147. result.m[13] = initialM42;
  3148. result.m[14] = initialM43;
  3149. result.m[15] = initialM44;
  3150. return result;
  3151. };
  3152. /**
  3153. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3154. */
  3155. Matrix.Compose = function (scale, rotation, translation) {
  3156. var result = Matrix.Identity();
  3157. Matrix.ComposeToRef(scale, rotation, translation, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3162. */
  3163. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3164. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3165. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3166. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3167. result.setTranslation(translation);
  3168. };
  3169. /**
  3170. * Returns a new indentity Matrix.
  3171. */
  3172. Matrix.Identity = function () {
  3173. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3174. };
  3175. /**
  3176. * Sets the passed "result" as an identity matrix.
  3177. */
  3178. Matrix.IdentityToRef = function (result) {
  3179. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3180. };
  3181. /**
  3182. * Returns a new zero Matrix.
  3183. */
  3184. Matrix.Zero = function () {
  3185. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3186. };
  3187. /**
  3188. * Returns a new rotation matrix for "angle" radians around the X axis.
  3189. */
  3190. Matrix.RotationX = function (angle) {
  3191. var result = new Matrix();
  3192. Matrix.RotationXToRef(angle, result);
  3193. return result;
  3194. };
  3195. /**
  3196. * Returns a new Matrix as the passed inverted one.
  3197. */
  3198. Matrix.Invert = function (source) {
  3199. var result = new Matrix();
  3200. source.invertToRef(result);
  3201. return result;
  3202. };
  3203. /**
  3204. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3205. */
  3206. Matrix.RotationXToRef = function (angle, result) {
  3207. var s = Math.sin(angle);
  3208. var c = Math.cos(angle);
  3209. result.m[0] = 1.0;
  3210. result.m[15] = 1.0;
  3211. result.m[5] = c;
  3212. result.m[10] = c;
  3213. result.m[9] = -s;
  3214. result.m[6] = s;
  3215. result.m[1] = 0.0;
  3216. result.m[2] = 0.0;
  3217. result.m[3] = 0.0;
  3218. result.m[4] = 0.0;
  3219. result.m[7] = 0.0;
  3220. result.m[8] = 0.0;
  3221. result.m[11] = 0.0;
  3222. result.m[12] = 0.0;
  3223. result.m[13] = 0.0;
  3224. result.m[14] = 0.0;
  3225. };
  3226. /**
  3227. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3228. */
  3229. Matrix.RotationY = function (angle) {
  3230. var result = new Matrix();
  3231. Matrix.RotationYToRef(angle, result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3236. */
  3237. Matrix.RotationYToRef = function (angle, result) {
  3238. var s = Math.sin(angle);
  3239. var c = Math.cos(angle);
  3240. result.m[5] = 1.0;
  3241. result.m[15] = 1.0;
  3242. result.m[0] = c;
  3243. result.m[2] = -s;
  3244. result.m[8] = s;
  3245. result.m[10] = c;
  3246. result.m[1] = 0.0;
  3247. result.m[3] = 0.0;
  3248. result.m[4] = 0.0;
  3249. result.m[6] = 0.0;
  3250. result.m[7] = 0.0;
  3251. result.m[9] = 0.0;
  3252. result.m[11] = 0.0;
  3253. result.m[12] = 0.0;
  3254. result.m[13] = 0.0;
  3255. result.m[14] = 0.0;
  3256. };
  3257. /**
  3258. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3259. */
  3260. Matrix.RotationZ = function (angle) {
  3261. var result = new Matrix();
  3262. Matrix.RotationZToRef(angle, result);
  3263. return result;
  3264. };
  3265. /**
  3266. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3267. */
  3268. Matrix.RotationZToRef = function (angle, result) {
  3269. var s = Math.sin(angle);
  3270. var c = Math.cos(angle);
  3271. result.m[10] = 1.0;
  3272. result.m[15] = 1.0;
  3273. result.m[0] = c;
  3274. result.m[1] = s;
  3275. result.m[4] = -s;
  3276. result.m[5] = c;
  3277. result.m[2] = 0.0;
  3278. result.m[3] = 0.0;
  3279. result.m[6] = 0.0;
  3280. result.m[7] = 0.0;
  3281. result.m[8] = 0.0;
  3282. result.m[9] = 0.0;
  3283. result.m[11] = 0.0;
  3284. result.m[12] = 0.0;
  3285. result.m[13] = 0.0;
  3286. result.m[14] = 0.0;
  3287. };
  3288. /**
  3289. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3290. */
  3291. Matrix.RotationAxis = function (axis, angle) {
  3292. var result = Matrix.Zero();
  3293. Matrix.RotationAxisToRef(axis, angle, result);
  3294. return result;
  3295. };
  3296. /**
  3297. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3298. */
  3299. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3300. var s = Math.sin(-angle);
  3301. var c = Math.cos(-angle);
  3302. var c1 = 1 - c;
  3303. axis.normalize();
  3304. result.m[0] = (axis.x * axis.x) * c1 + c;
  3305. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3306. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3307. result.m[3] = 0.0;
  3308. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3309. result.m[5] = (axis.y * axis.y) * c1 + c;
  3310. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3311. result.m[7] = 0.0;
  3312. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3313. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3314. result.m[10] = (axis.z * axis.z) * c1 + c;
  3315. result.m[11] = 0.0;
  3316. result.m[15] = 1.0;
  3317. };
  3318. /**
  3319. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3320. */
  3321. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3322. var result = new Matrix();
  3323. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3328. */
  3329. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3330. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3331. this._tempQuaternion.toRotationMatrix(result);
  3332. };
  3333. /**
  3334. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3335. */
  3336. Matrix.Scaling = function (x, y, z) {
  3337. var result = Matrix.Zero();
  3338. Matrix.ScalingToRef(x, y, z, result);
  3339. return result;
  3340. };
  3341. /**
  3342. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3343. */
  3344. Matrix.ScalingToRef = function (x, y, z, result) {
  3345. result.m[0] = x;
  3346. result.m[1] = 0.0;
  3347. result.m[2] = 0.0;
  3348. result.m[3] = 0.0;
  3349. result.m[4] = 0.0;
  3350. result.m[5] = y;
  3351. result.m[6] = 0.0;
  3352. result.m[7] = 0.0;
  3353. result.m[8] = 0.0;
  3354. result.m[9] = 0.0;
  3355. result.m[10] = z;
  3356. result.m[11] = 0.0;
  3357. result.m[12] = 0.0;
  3358. result.m[13] = 0.0;
  3359. result.m[14] = 0.0;
  3360. result.m[15] = 1.0;
  3361. };
  3362. /**
  3363. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3364. */
  3365. Matrix.Translation = function (x, y, z) {
  3366. var result = Matrix.Identity();
  3367. Matrix.TranslationToRef(x, y, z, result);
  3368. return result;
  3369. };
  3370. /**
  3371. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3372. */
  3373. Matrix.TranslationToRef = function (x, y, z, result) {
  3374. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3375. };
  3376. /**
  3377. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3378. */
  3379. Matrix.Lerp = function (startValue, endValue, gradient) {
  3380. var result = Matrix.Zero();
  3381. for (var index = 0; index < 16; index++) {
  3382. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3383. }
  3384. return result;
  3385. };
  3386. /**
  3387. * Returns a new Matrix whose values are computed by :
  3388. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3389. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3390. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3391. */
  3392. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3393. var startScale = new Vector3(0, 0, 0);
  3394. var startRotation = new Quaternion();
  3395. var startTranslation = new Vector3(0, 0, 0);
  3396. startValue.decompose(startScale, startRotation, startTranslation);
  3397. var endScale = new Vector3(0, 0, 0);
  3398. var endRotation = new Quaternion();
  3399. var endTranslation = new Vector3(0, 0, 0);
  3400. endValue.decompose(endScale, endRotation, endTranslation);
  3401. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3402. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3403. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3404. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3405. };
  3406. /**
  3407. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3408. * This methods works for a Left-Handed system.
  3409. */
  3410. Matrix.LookAtLH = function (eye, target, up) {
  3411. var result = Matrix.Zero();
  3412. Matrix.LookAtLHToRef(eye, target, up, result);
  3413. return result;
  3414. };
  3415. /**
  3416. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3417. * This methods works for a Left-Handed system.
  3418. */
  3419. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3420. // Z axis
  3421. target.subtractToRef(eye, this._zAxis);
  3422. this._zAxis.normalize();
  3423. // X axis
  3424. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3425. if (this._xAxis.lengthSquared() === 0) {
  3426. this._xAxis.x = 1.0;
  3427. }
  3428. else {
  3429. this._xAxis.normalize();
  3430. }
  3431. // Y axis
  3432. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3433. this._yAxis.normalize();
  3434. // Eye angles
  3435. var ex = -Vector3.Dot(this._xAxis, eye);
  3436. var ey = -Vector3.Dot(this._yAxis, eye);
  3437. var ez = -Vector3.Dot(this._zAxis, eye);
  3438. 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);
  3439. };
  3440. /**
  3441. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3442. * This methods works for a Right-Handed system.
  3443. */
  3444. Matrix.LookAtRH = function (eye, target, up) {
  3445. var result = Matrix.Zero();
  3446. Matrix.LookAtRHToRef(eye, target, up, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3451. * This methods works for a Left-Handed system.
  3452. */
  3453. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3454. // Z axis
  3455. eye.subtractToRef(target, this._zAxis);
  3456. this._zAxis.normalize();
  3457. // X axis
  3458. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3459. if (this._xAxis.lengthSquared() === 0) {
  3460. this._xAxis.x = 1.0;
  3461. }
  3462. else {
  3463. this._xAxis.normalize();
  3464. }
  3465. // Y axis
  3466. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3467. this._yAxis.normalize();
  3468. // Eye angles
  3469. var ex = -Vector3.Dot(this._xAxis, eye);
  3470. var ey = -Vector3.Dot(this._yAxis, eye);
  3471. var ez = -Vector3.Dot(this._zAxis, eye);
  3472. 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);
  3473. };
  3474. /**
  3475. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3476. */
  3477. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3478. var matrix = Matrix.Zero();
  3479. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3480. return matrix;
  3481. };
  3482. /**
  3483. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3484. */
  3485. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3486. var n = znear;
  3487. var f = zfar;
  3488. var a = 2.0 / width;
  3489. var b = 2.0 / height;
  3490. var c = 2.0 / (f - n);
  3491. var d = -(f + n) / (f - n);
  3492. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3493. };
  3494. /**
  3495. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3496. */
  3497. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3498. var matrix = Matrix.Zero();
  3499. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3500. return matrix;
  3501. };
  3502. /**
  3503. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3504. */
  3505. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3506. var n = znear;
  3507. var f = zfar;
  3508. var a = 2.0 / (right - left);
  3509. var b = 2.0 / (top - bottom);
  3510. var c = 2.0 / (f - n);
  3511. var d = -(f + n) / (f - n);
  3512. var i0 = (left + right) / (left - right);
  3513. var i1 = (top + bottom) / (bottom - top);
  3514. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3515. };
  3516. /**
  3517. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3518. */
  3519. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3520. var matrix = Matrix.Zero();
  3521. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3522. return matrix;
  3523. };
  3524. /**
  3525. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3526. */
  3527. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3528. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3529. result.m[10] *= -1.0;
  3530. };
  3531. /**
  3532. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3533. */
  3534. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3535. var matrix = Matrix.Zero();
  3536. var n = znear;
  3537. var f = zfar;
  3538. var a = 2.0 * n / width;
  3539. var b = 2.0 * n / height;
  3540. var c = (f + n) / (f - n);
  3541. var d = -2.0 * f * n / (f - n);
  3542. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3543. return matrix;
  3544. };
  3545. /**
  3546. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3547. */
  3548. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3549. var matrix = Matrix.Zero();
  3550. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3551. return matrix;
  3552. };
  3553. /**
  3554. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3555. */
  3556. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3557. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3558. var n = znear;
  3559. var f = zfar;
  3560. var t = 1.0 / (Math.tan(fov * 0.5));
  3561. var a = isVerticalFovFixed ? (t / aspect) : t;
  3562. var b = isVerticalFovFixed ? t : (t * aspect);
  3563. var c = (f + n) / (f - n);
  3564. var d = -2.0 * f * n / (f - n);
  3565. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3566. };
  3567. /**
  3568. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3569. */
  3570. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3571. var matrix = Matrix.Zero();
  3572. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3573. return matrix;
  3574. };
  3575. /**
  3576. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3577. */
  3578. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3579. //alternatively this could be expressed as:
  3580. // m = PerspectiveFovLHToRef
  3581. // m[10] *= -1.0;
  3582. // m[11] *= -1.0;
  3583. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3584. var n = znear;
  3585. var f = zfar;
  3586. var t = 1.0 / (Math.tan(fov * 0.5));
  3587. var a = isVerticalFovFixed ? (t / aspect) : t;
  3588. var b = isVerticalFovFixed ? t : (t * aspect);
  3589. var c = -(f + n) / (f - n);
  3590. var d = -2 * f * n / (f - n);
  3591. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3595. */
  3596. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3597. if (rightHanded === void 0) { rightHanded = false; }
  3598. var rightHandedFactor = rightHanded ? -1 : 1;
  3599. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3600. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3601. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3602. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3603. var xScale = 2.0 / (leftTan + rightTan);
  3604. var yScale = 2.0 / (upTan + downTan);
  3605. result.m[0] = xScale;
  3606. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3607. result.m[5] = yScale;
  3608. result.m[6] = result.m[7] = 0.0;
  3609. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3610. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3611. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3612. // result.m[10] = -zfar / (znear - zfar);
  3613. result.m[11] = 1.0 * rightHandedFactor;
  3614. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3615. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3616. // result.m[14] = (znear * zfar) / (znear - zfar);
  3617. };
  3618. /**
  3619. * Returns the final transformation matrix : world * view * projection * viewport
  3620. */
  3621. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3622. var cw = viewport.width;
  3623. var ch = viewport.height;
  3624. var cx = viewport.x;
  3625. var cy = viewport.y;
  3626. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3627. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3628. };
  3629. /**
  3630. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3631. */
  3632. Matrix.GetAsMatrix2x2 = function (matrix) {
  3633. return new Float32Array([
  3634. matrix.m[0], matrix.m[1],
  3635. matrix.m[4], matrix.m[5]
  3636. ]);
  3637. };
  3638. /**
  3639. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3640. */
  3641. Matrix.GetAsMatrix3x3 = function (matrix) {
  3642. return new Float32Array([
  3643. matrix.m[0], matrix.m[1], matrix.m[2],
  3644. matrix.m[4], matrix.m[5], matrix.m[6],
  3645. matrix.m[8], matrix.m[9], matrix.m[10]
  3646. ]);
  3647. };
  3648. /**
  3649. * Compute the transpose of the passed Matrix.
  3650. * Returns a new Matrix.
  3651. */
  3652. Matrix.Transpose = function (matrix) {
  3653. var result = new Matrix();
  3654. result.m[0] = matrix.m[0];
  3655. result.m[1] = matrix.m[4];
  3656. result.m[2] = matrix.m[8];
  3657. result.m[3] = matrix.m[12];
  3658. result.m[4] = matrix.m[1];
  3659. result.m[5] = matrix.m[5];
  3660. result.m[6] = matrix.m[9];
  3661. result.m[7] = matrix.m[13];
  3662. result.m[8] = matrix.m[2];
  3663. result.m[9] = matrix.m[6];
  3664. result.m[10] = matrix.m[10];
  3665. result.m[11] = matrix.m[14];
  3666. result.m[12] = matrix.m[3];
  3667. result.m[13] = matrix.m[7];
  3668. result.m[14] = matrix.m[11];
  3669. result.m[15] = matrix.m[15];
  3670. return result;
  3671. };
  3672. /**
  3673. * Returns a new Matrix as the reflection matrix across the passed plane.
  3674. */
  3675. Matrix.Reflection = function (plane) {
  3676. var matrix = new Matrix();
  3677. Matrix.ReflectionToRef(plane, matrix);
  3678. return matrix;
  3679. };
  3680. /**
  3681. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3682. */
  3683. Matrix.ReflectionToRef = function (plane, result) {
  3684. plane.normalize();
  3685. var x = plane.normal.x;
  3686. var y = plane.normal.y;
  3687. var z = plane.normal.z;
  3688. var temp = -2 * x;
  3689. var temp2 = -2 * y;
  3690. var temp3 = -2 * z;
  3691. result.m[0] = (temp * x) + 1;
  3692. result.m[1] = temp2 * x;
  3693. result.m[2] = temp3 * x;
  3694. result.m[3] = 0.0;
  3695. result.m[4] = temp * y;
  3696. result.m[5] = (temp2 * y) + 1;
  3697. result.m[6] = temp3 * y;
  3698. result.m[7] = 0.0;
  3699. result.m[8] = temp * z;
  3700. result.m[9] = temp2 * z;
  3701. result.m[10] = (temp3 * z) + 1;
  3702. result.m[11] = 0.0;
  3703. result.m[12] = temp * plane.d;
  3704. result.m[13] = temp2 * plane.d;
  3705. result.m[14] = temp3 * plane.d;
  3706. result.m[15] = 1.0;
  3707. };
  3708. /**
  3709. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3710. */
  3711. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3712. mat.m[0] = xaxis.x;
  3713. mat.m[1] = xaxis.y;
  3714. mat.m[2] = xaxis.z;
  3715. mat.m[3] = 0.0;
  3716. mat.m[4] = yaxis.x;
  3717. mat.m[5] = yaxis.y;
  3718. mat.m[6] = yaxis.z;
  3719. mat.m[7] = 0.0;
  3720. mat.m[8] = zaxis.x;
  3721. mat.m[9] = zaxis.y;
  3722. mat.m[10] = zaxis.z;
  3723. mat.m[11] = 0.0;
  3724. mat.m[12] = 0.0;
  3725. mat.m[13] = 0.0;
  3726. mat.m[14] = 0.0;
  3727. mat.m[15] = 1.0;
  3728. };
  3729. /**
  3730. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3731. */
  3732. Matrix.FromQuaternionToRef = function (quat, result) {
  3733. var xx = quat.x * quat.x;
  3734. var yy = quat.y * quat.y;
  3735. var zz = quat.z * quat.z;
  3736. var xy = quat.x * quat.y;
  3737. var zw = quat.z * quat.w;
  3738. var zx = quat.z * quat.x;
  3739. var yw = quat.y * quat.w;
  3740. var yz = quat.y * quat.z;
  3741. var xw = quat.x * quat.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0.0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0.0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0.0;
  3754. result.m[12] = 0.0;
  3755. result.m[13] = 0.0;
  3756. result.m[14] = 0.0;
  3757. result.m[15] = 1.0;
  3758. };
  3759. return Matrix;
  3760. }());
  3761. Matrix._tempQuaternion = new Quaternion();
  3762. Matrix._xAxis = Vector3.Zero();
  3763. Matrix._yAxis = Vector3.Zero();
  3764. Matrix._zAxis = Vector3.Zero();
  3765. BABYLON.Matrix = Matrix;
  3766. var Plane = (function () {
  3767. /**
  3768. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3769. */
  3770. function Plane(a, b, c, d) {
  3771. this.normal = new Vector3(a, b, c);
  3772. this.d = d;
  3773. }
  3774. /**
  3775. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3776. */
  3777. Plane.prototype.asArray = function () {
  3778. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3779. };
  3780. // Methods
  3781. /**
  3782. * Returns a new plane copied from the current Plane.
  3783. */
  3784. Plane.prototype.clone = function () {
  3785. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3786. };
  3787. /**
  3788. * Returns the string "Plane".
  3789. */
  3790. Plane.prototype.getClassName = function () {
  3791. return "Plane";
  3792. };
  3793. /**
  3794. * Returns the Plane hash code.
  3795. */
  3796. Plane.prototype.getHashCode = function () {
  3797. var hash = this.normal.getHashCode();
  3798. hash = (hash * 397) ^ (this.d || 0);
  3799. return hash;
  3800. };
  3801. /**
  3802. * Normalize the current Plane in place.
  3803. * Returns the updated Plane.
  3804. */
  3805. Plane.prototype.normalize = function () {
  3806. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3807. var magnitude = 0.0;
  3808. if (norm !== 0) {
  3809. magnitude = 1.0 / norm;
  3810. }
  3811. this.normal.x *= magnitude;
  3812. this.normal.y *= magnitude;
  3813. this.normal.z *= magnitude;
  3814. this.d *= magnitude;
  3815. return this;
  3816. };
  3817. /**
  3818. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3819. */
  3820. Plane.prototype.transform = function (transformation) {
  3821. var transposedMatrix = Matrix.Transpose(transformation);
  3822. var x = this.normal.x;
  3823. var y = this.normal.y;
  3824. var z = this.normal.z;
  3825. var d = this.d;
  3826. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3827. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3828. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3829. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3830. return new Plane(normalX, normalY, normalZ, finalD);
  3831. };
  3832. /**
  3833. * Returns the dot product (float) of the point coordinates and the plane normal.
  3834. */
  3835. Plane.prototype.dotCoordinate = function (point) {
  3836. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3837. };
  3838. /**
  3839. * Updates the current Plane from the plane defined by the three passed points.
  3840. * Returns the updated Plane.
  3841. */
  3842. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3843. var x1 = point2.x - point1.x;
  3844. var y1 = point2.y - point1.y;
  3845. var z1 = point2.z - point1.z;
  3846. var x2 = point3.x - point1.x;
  3847. var y2 = point3.y - point1.y;
  3848. var z2 = point3.z - point1.z;
  3849. var yz = (y1 * z2) - (z1 * y2);
  3850. var xz = (z1 * x2) - (x1 * z2);
  3851. var xy = (x1 * y2) - (y1 * x2);
  3852. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3853. var invPyth;
  3854. if (pyth !== 0) {
  3855. invPyth = 1.0 / pyth;
  3856. }
  3857. else {
  3858. invPyth = 0.0;
  3859. }
  3860. this.normal.x = yz * invPyth;
  3861. this.normal.y = xz * invPyth;
  3862. this.normal.z = xy * invPyth;
  3863. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3864. return this;
  3865. };
  3866. /**
  3867. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3868. */
  3869. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3870. var dot = Vector3.Dot(this.normal, direction);
  3871. return (dot <= epsilon);
  3872. };
  3873. /**
  3874. * Returns the signed distance (float) from the passed point to the Plane.
  3875. */
  3876. Plane.prototype.signedDistanceTo = function (point) {
  3877. return Vector3.Dot(point, this.normal) + this.d;
  3878. };
  3879. // Statics
  3880. /**
  3881. * Returns a new Plane from the passed array.
  3882. */
  3883. Plane.FromArray = function (array) {
  3884. return new Plane(array[0], array[1], array[2], array[3]);
  3885. };
  3886. /**
  3887. * Returns a new Plane defined by the three passed points.
  3888. */
  3889. Plane.FromPoints = function (point1, point2, point3) {
  3890. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3891. result.copyFromPoints(point1, point2, point3);
  3892. return result;
  3893. };
  3894. /**
  3895. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3896. * Note : the vector "normal" is updated because normalized.
  3897. */
  3898. Plane.FromPositionAndNormal = function (origin, normal) {
  3899. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3900. normal.normalize();
  3901. result.normal = normal;
  3902. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3903. return result;
  3904. };
  3905. /**
  3906. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3907. */
  3908. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3909. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3910. return Vector3.Dot(point, normal) + d;
  3911. };
  3912. return Plane;
  3913. }());
  3914. BABYLON.Plane = Plane;
  3915. var Viewport = (function () {
  3916. /**
  3917. * Creates a Viewport object located at (x, y) and sized (width, height).
  3918. */
  3919. function Viewport(x, y, width, height) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.width = width;
  3923. this.height = height;
  3924. }
  3925. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3926. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3927. };
  3928. /**
  3929. * Returns a new Viewport copied from the current one.
  3930. */
  3931. Viewport.prototype.clone = function () {
  3932. return new Viewport(this.x, this.y, this.width, this.height);
  3933. };
  3934. return Viewport;
  3935. }());
  3936. BABYLON.Viewport = Viewport;
  3937. var Frustum = (function () {
  3938. function Frustum() {
  3939. }
  3940. /**
  3941. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3942. */
  3943. Frustum.GetPlanes = function (transform) {
  3944. var frustumPlanes = [];
  3945. for (var index = 0; index < 6; index++) {
  3946. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3947. }
  3948. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3949. return frustumPlanes;
  3950. };
  3951. /**
  3952. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3953. */
  3954. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3955. // Near
  3956. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3957. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3958. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3959. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3960. frustumPlanes[0].normalize();
  3961. // Far
  3962. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3963. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3964. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3965. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3966. frustumPlanes[1].normalize();
  3967. // Left
  3968. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3969. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3970. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3971. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3972. frustumPlanes[2].normalize();
  3973. // Right
  3974. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3975. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3976. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3977. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3978. frustumPlanes[3].normalize();
  3979. // Top
  3980. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3981. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3982. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3983. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3984. frustumPlanes[4].normalize();
  3985. // Bottom
  3986. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3987. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3988. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3989. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3990. frustumPlanes[5].normalize();
  3991. };
  3992. return Frustum;
  3993. }());
  3994. BABYLON.Frustum = Frustum;
  3995. var Space;
  3996. (function (Space) {
  3997. Space[Space["LOCAL"] = 0] = "LOCAL";
  3998. Space[Space["WORLD"] = 1] = "WORLD";
  3999. Space[Space["BONE"] = 2] = "BONE";
  4000. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4001. var Axis = (function () {
  4002. function Axis() {
  4003. }
  4004. return Axis;
  4005. }());
  4006. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4007. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4008. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4009. BABYLON.Axis = Axis;
  4010. ;
  4011. var BezierCurve = (function () {
  4012. function BezierCurve() {
  4013. }
  4014. /**
  4015. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4016. */
  4017. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4018. // Extract X (which is equal to time here)
  4019. var f0 = 1 - 3 * x2 + 3 * x1;
  4020. var f1 = 3 * x2 - 6 * x1;
  4021. var f2 = 3 * x1;
  4022. var refinedT = t;
  4023. for (var i = 0; i < 5; i++) {
  4024. var refinedT2 = refinedT * refinedT;
  4025. var refinedT3 = refinedT2 * refinedT;
  4026. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4027. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4028. refinedT -= (x - t) * slope;
  4029. refinedT = Math.min(1, Math.max(0, refinedT));
  4030. }
  4031. // Resolve cubic bezier for the given x
  4032. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4033. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4034. Math.pow(refinedT, 3);
  4035. };
  4036. return BezierCurve;
  4037. }());
  4038. BABYLON.BezierCurve = BezierCurve;
  4039. var Orientation;
  4040. (function (Orientation) {
  4041. Orientation[Orientation["CW"] = 0] = "CW";
  4042. Orientation[Orientation["CCW"] = 1] = "CCW";
  4043. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4044. var Angle = (function () {
  4045. /**
  4046. * Creates an Angle object of "radians" radians (float).
  4047. */
  4048. function Angle(radians) {
  4049. var _this = this;
  4050. /**
  4051. * Returns the Angle value in degrees (float).
  4052. */
  4053. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4054. /**
  4055. * Returns the Angle value in radians (float).
  4056. */
  4057. this.radians = function () { return _this._radians; };
  4058. this._radians = radians;
  4059. if (this._radians < 0.0)
  4060. this._radians += (2.0 * Math.PI);
  4061. }
  4062. /**
  4063. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4064. */
  4065. Angle.BetweenTwoPoints = function (a, b) {
  4066. var delta = b.subtract(a);
  4067. var theta = Math.atan2(delta.y, delta.x);
  4068. return new Angle(theta);
  4069. };
  4070. /**
  4071. * Returns a new Angle object from the passed float in radians.
  4072. */
  4073. Angle.FromRadians = function (radians) {
  4074. return new Angle(radians);
  4075. };
  4076. /**
  4077. * Returns a new Angle object from the passed float in degrees.
  4078. */
  4079. Angle.FromDegrees = function (degrees) {
  4080. return new Angle(degrees * Math.PI / 180.0);
  4081. };
  4082. return Angle;
  4083. }());
  4084. BABYLON.Angle = Angle;
  4085. var Arc2 = (function () {
  4086. /**
  4087. * Creates an Arc object from the three passed points : start, middle and end.
  4088. */
  4089. function Arc2(startPoint, midPoint, endPoint) {
  4090. this.startPoint = startPoint;
  4091. this.midPoint = midPoint;
  4092. this.endPoint = endPoint;
  4093. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4094. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4095. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4096. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4097. 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);
  4098. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4099. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4100. var a1 = this.startAngle.degrees();
  4101. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4102. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4103. // angles correction
  4104. if (a2 - a1 > +180.0)
  4105. a2 -= 360.0;
  4106. if (a2 - a1 < -180.0)
  4107. a2 += 360.0;
  4108. if (a3 - a2 > +180.0)
  4109. a3 -= 360.0;
  4110. if (a3 - a2 < -180.0)
  4111. a3 += 360.0;
  4112. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4113. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4114. }
  4115. return Arc2;
  4116. }());
  4117. BABYLON.Arc2 = Arc2;
  4118. var Path2 = (function () {
  4119. /**
  4120. * Creates a Path2 object from the starting 2D coordinates x and y.
  4121. */
  4122. function Path2(x, y) {
  4123. this._points = new Array();
  4124. this._length = 0.0;
  4125. this.closed = false;
  4126. this._points.push(new Vector2(x, y));
  4127. }
  4128. /**
  4129. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4130. * Returns the updated Path2.
  4131. */
  4132. Path2.prototype.addLineTo = function (x, y) {
  4133. if (closed) {
  4134. //Tools.Error("cannot add lines to closed paths");
  4135. return this;
  4136. }
  4137. var newPoint = new Vector2(x, y);
  4138. var previousPoint = this._points[this._points.length - 1];
  4139. this._points.push(newPoint);
  4140. this._length += newPoint.subtract(previousPoint).length();
  4141. return this;
  4142. };
  4143. /**
  4144. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4145. * Returns the updated Path2.
  4146. */
  4147. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4148. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4149. if (closed) {
  4150. //Tools.Error("cannot add arcs to closed paths");
  4151. return this;
  4152. }
  4153. var startPoint = this._points[this._points.length - 1];
  4154. var midPoint = new Vector2(midX, midY);
  4155. var endPoint = new Vector2(endX, endY);
  4156. var arc = new Arc2(startPoint, midPoint, endPoint);
  4157. var increment = arc.angle.radians() / numberOfSegments;
  4158. if (arc.orientation === Orientation.CW)
  4159. increment *= -1;
  4160. var currentAngle = arc.startAngle.radians() + increment;
  4161. for (var i = 0; i < numberOfSegments; i++) {
  4162. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4163. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4164. this.addLineTo(x, y);
  4165. currentAngle += increment;
  4166. }
  4167. return this;
  4168. };
  4169. /**
  4170. * Closes the Path2.
  4171. * Returns the Path2.
  4172. */
  4173. Path2.prototype.close = function () {
  4174. this.closed = true;
  4175. return this;
  4176. };
  4177. /**
  4178. * Returns the Path2 total length (float).
  4179. */
  4180. Path2.prototype.length = function () {
  4181. var result = this._length;
  4182. if (!this.closed) {
  4183. var lastPoint = this._points[this._points.length - 1];
  4184. var firstPoint = this._points[0];
  4185. result += (firstPoint.subtract(lastPoint).length());
  4186. }
  4187. return result;
  4188. };
  4189. /**
  4190. * Returns the Path2 internal array of points.
  4191. */
  4192. Path2.prototype.getPoints = function () {
  4193. return this._points;
  4194. };
  4195. /**
  4196. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4197. */
  4198. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4199. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4200. //Tools.Error("normalized length position should be between 0 and 1.");
  4201. return Vector2.Zero();
  4202. }
  4203. var lengthPosition = normalizedLengthPosition * this.length();
  4204. var previousOffset = 0;
  4205. for (var i = 0; i < this._points.length; i++) {
  4206. var j = (i + 1) % this._points.length;
  4207. var a = this._points[i];
  4208. var b = this._points[j];
  4209. var bToA = b.subtract(a);
  4210. var nextOffset = (bToA.length() + previousOffset);
  4211. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4212. var dir = bToA.normalize();
  4213. var localOffset = lengthPosition - previousOffset;
  4214. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4215. }
  4216. previousOffset = nextOffset;
  4217. }
  4218. //Tools.Error("internal error");
  4219. return Vector2.Zero();
  4220. };
  4221. /**
  4222. * Returns a new Path2 starting at the coordinates (x, y).
  4223. */
  4224. Path2.StartingAt = function (x, y) {
  4225. return new Path2(x, y);
  4226. };
  4227. return Path2;
  4228. }());
  4229. BABYLON.Path2 = Path2;
  4230. var Path3D = (function () {
  4231. /**
  4232. * new Path3D(path, normal, raw)
  4233. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4234. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4235. * path : an array of Vector3, the curve axis of the Path3D
  4236. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4237. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4238. */
  4239. function Path3D(path, firstNormal, raw) {
  4240. this.path = path;
  4241. this._curve = new Array();
  4242. this._distances = new Array();
  4243. this._tangents = new Array();
  4244. this._normals = new Array();
  4245. this._binormals = new Array();
  4246. for (var p = 0; p < path.length; p++) {
  4247. this._curve[p] = path[p].clone(); // hard copy
  4248. }
  4249. this._raw = raw || false;
  4250. this._compute(firstNormal);
  4251. }
  4252. /**
  4253. * Returns the Path3D array of successive Vector3 designing its curve.
  4254. */
  4255. Path3D.prototype.getCurve = function () {
  4256. return this._curve;
  4257. };
  4258. /**
  4259. * Returns an array populated with tangent vectors on each Path3D curve point.
  4260. */
  4261. Path3D.prototype.getTangents = function () {
  4262. return this._tangents;
  4263. };
  4264. /**
  4265. * Returns an array populated with normal vectors on each Path3D curve point.
  4266. */
  4267. Path3D.prototype.getNormals = function () {
  4268. return this._normals;
  4269. };
  4270. /**
  4271. * Returns an array populated with binormal vectors on each Path3D curve point.
  4272. */
  4273. Path3D.prototype.getBinormals = function () {
  4274. return this._binormals;
  4275. };
  4276. /**
  4277. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4278. */
  4279. Path3D.prototype.getDistances = function () {
  4280. return this._distances;
  4281. };
  4282. /**
  4283. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4284. * Returns the same object updated.
  4285. */
  4286. Path3D.prototype.update = function (path, firstNormal) {
  4287. for (var p = 0; p < path.length; p++) {
  4288. this._curve[p].x = path[p].x;
  4289. this._curve[p].y = path[p].y;
  4290. this._curve[p].z = path[p].z;
  4291. }
  4292. this._compute(firstNormal);
  4293. return this;
  4294. };
  4295. // private function compute() : computes tangents, normals and binormals
  4296. Path3D.prototype._compute = function (firstNormal) {
  4297. var l = this._curve.length;
  4298. // first and last tangents
  4299. this._tangents[0] = this._getFirstNonNullVector(0);
  4300. if (!this._raw) {
  4301. this._tangents[0].normalize();
  4302. }
  4303. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4304. if (!this._raw) {
  4305. this._tangents[l - 1].normalize();
  4306. }
  4307. // normals and binormals at first point : arbitrary vector with _normalVector()
  4308. var tg0 = this._tangents[0];
  4309. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4310. this._normals[0] = pp0;
  4311. if (!this._raw) {
  4312. this._normals[0].normalize();
  4313. }
  4314. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4315. if (!this._raw) {
  4316. this._binormals[0].normalize();
  4317. }
  4318. this._distances[0] = 0.0;
  4319. // normals and binormals : next points
  4320. var prev; // previous vector (segment)
  4321. var cur; // current vector (segment)
  4322. var curTang; // current tangent
  4323. // previous normal
  4324. var prevBinor; // previous binormal
  4325. for (var i = 1; i < l; i++) {
  4326. // tangents
  4327. prev = this._getLastNonNullVector(i);
  4328. if (i < l - 1) {
  4329. cur = this._getFirstNonNullVector(i);
  4330. this._tangents[i] = prev.add(cur);
  4331. this._tangents[i].normalize();
  4332. }
  4333. this._distances[i] = this._distances[i - 1] + prev.length();
  4334. // normals and binormals
  4335. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4336. curTang = this._tangents[i];
  4337. prevBinor = this._binormals[i - 1];
  4338. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4339. if (!this._raw) {
  4340. this._normals[i].normalize();
  4341. }
  4342. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4343. if (!this._raw) {
  4344. this._binormals[i].normalize();
  4345. }
  4346. }
  4347. };
  4348. // private function getFirstNonNullVector(index)
  4349. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4350. Path3D.prototype._getFirstNonNullVector = function (index) {
  4351. var i = 1;
  4352. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4353. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4354. i++;
  4355. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4356. }
  4357. return nNVector;
  4358. };
  4359. // private function getLastNonNullVector(index)
  4360. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4361. Path3D.prototype._getLastNonNullVector = function (index) {
  4362. var i = 1;
  4363. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4364. while (nLVector.length() === 0 && index > i + 1) {
  4365. i++;
  4366. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4367. }
  4368. return nLVector;
  4369. };
  4370. // private function normalVector(v0, vt, va) :
  4371. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4372. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4373. Path3D.prototype._normalVector = function (v0, vt, va) {
  4374. var normal0;
  4375. var tgl = vt.length();
  4376. if (tgl === 0.0) {
  4377. tgl = 1.0;
  4378. }
  4379. if (va === undefined || va === null) {
  4380. var point;
  4381. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4382. point = new Vector3(0.0, -1.0, 0.0);
  4383. }
  4384. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4385. point = new Vector3(1.0, 0.0, 0.0);
  4386. }
  4387. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4388. point = new Vector3(0.0, 0.0, 1.0);
  4389. }
  4390. normal0 = Vector3.Cross(vt, point);
  4391. }
  4392. else {
  4393. normal0 = Vector3.Cross(vt, va);
  4394. Vector3.CrossToRef(normal0, vt, normal0);
  4395. }
  4396. normal0.normalize();
  4397. return normal0;
  4398. };
  4399. return Path3D;
  4400. }());
  4401. BABYLON.Path3D = Path3D;
  4402. var Curve3 = (function () {
  4403. /**
  4404. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4405. * A Curve3 is designed from a series of successive Vector3.
  4406. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4407. */
  4408. function Curve3(points) {
  4409. this._length = 0.0;
  4410. this._points = points;
  4411. this._length = this._computeLength(points);
  4412. }
  4413. /**
  4414. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4415. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4416. * @param v1 (Vector3) the control point
  4417. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4418. * @param nbPoints (integer) the wanted number of points in the curve
  4419. */
  4420. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4421. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4422. var bez = new Array();
  4423. var equation = function (t, val0, val1, val2) {
  4424. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4425. return res;
  4426. };
  4427. for (var i = 0; i <= nbPoints; i++) {
  4428. 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)));
  4429. }
  4430. return new Curve3(bez);
  4431. };
  4432. /**
  4433. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4434. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4435. * @param v1 (Vector3) the first control point
  4436. * @param v2 (Vector3) the second control point
  4437. * @param v3 (Vector3) the end point of the Cubic Bezier
  4438. * @param nbPoints (integer) the wanted number of points in the curve
  4439. */
  4440. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4441. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4442. var bez = new Array();
  4443. var equation = function (t, val0, val1, val2, val3) {
  4444. 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;
  4445. return res;
  4446. };
  4447. for (var i = 0; i <= nbPoints; i++) {
  4448. 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)));
  4449. }
  4450. return new Curve3(bez);
  4451. };
  4452. /**
  4453. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4454. * @param p1 (Vector3) the origin point of the Hermite Spline
  4455. * @param t1 (Vector3) the tangent vector at the origin point
  4456. * @param p2 (Vector3) the end point of the Hermite Spline
  4457. * @param t2 (Vector3) the tangent vector at the end point
  4458. * @param nbPoints (integer) the wanted number of points in the curve
  4459. */
  4460. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4461. var hermite = new Array();
  4462. var step = 1.0 / nbPoints;
  4463. for (var i = 0; i <= nbPoints; i++) {
  4464. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4465. }
  4466. return new Curve3(hermite);
  4467. };
  4468. /**
  4469. * Returns a Curve3 object along a CatmullRom Spline curve :
  4470. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4471. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4472. */
  4473. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4474. var totalPoints = new Array();
  4475. totalPoints.push(points[0].clone());
  4476. Array.prototype.push.apply(totalPoints, points);
  4477. totalPoints.push(points[points.length - 1].clone());
  4478. var catmullRom = new Array();
  4479. var step = 1.0 / nbPoints;
  4480. for (var i = 0; i < totalPoints.length - 3; i++) {
  4481. var amount = 0.0;
  4482. for (var c = 0; c < nbPoints; c++) {
  4483. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4484. amount += step;
  4485. }
  4486. }
  4487. i--;
  4488. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4489. return new Curve3(catmullRom);
  4490. };
  4491. /**
  4492. * Returns the Curve3 stored array of successive Vector3
  4493. */
  4494. Curve3.prototype.getPoints = function () {
  4495. return this._points;
  4496. };
  4497. /**
  4498. * Returns the computed length (float) of the curve.
  4499. */
  4500. Curve3.prototype.length = function () {
  4501. return this._length;
  4502. };
  4503. /**
  4504. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4505. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4506. * curveA and curveB keep unchanged.
  4507. */
  4508. Curve3.prototype.continue = function (curve) {
  4509. var lastPoint = this._points[this._points.length - 1];
  4510. var continuedPoints = this._points.slice();
  4511. var curvePoints = curve.getPoints();
  4512. for (var i = 1; i < curvePoints.length; i++) {
  4513. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4514. }
  4515. var continuedCurve = new Curve3(continuedPoints);
  4516. return continuedCurve;
  4517. };
  4518. Curve3.prototype._computeLength = function (path) {
  4519. var l = 0;
  4520. for (var i = 1; i < path.length; i++) {
  4521. l += (path[i].subtract(path[i - 1])).length();
  4522. }
  4523. return l;
  4524. };
  4525. return Curve3;
  4526. }());
  4527. BABYLON.Curve3 = Curve3;
  4528. // SphericalHarmonics
  4529. var SphericalHarmonics = (function () {
  4530. function SphericalHarmonics() {
  4531. this.L00 = Vector3.Zero();
  4532. this.L1_1 = Vector3.Zero();
  4533. this.L10 = Vector3.Zero();
  4534. this.L11 = Vector3.Zero();
  4535. this.L2_2 = Vector3.Zero();
  4536. this.L2_1 = Vector3.Zero();
  4537. this.L20 = Vector3.Zero();
  4538. this.L21 = Vector3.Zero();
  4539. this.L22 = Vector3.Zero();
  4540. }
  4541. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4542. var colorVector = new Vector3(color.r, color.g, color.b);
  4543. var c = colorVector.scale(deltaSolidAngle);
  4544. this.L00 = this.L00.add(c.scale(0.282095));
  4545. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4546. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4547. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4548. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4549. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4550. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4551. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4552. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4553. };
  4554. SphericalHarmonics.prototype.scale = function (scale) {
  4555. this.L00 = this.L00.scale(scale);
  4556. this.L1_1 = this.L1_1.scale(scale);
  4557. this.L10 = this.L10.scale(scale);
  4558. this.L11 = this.L11.scale(scale);
  4559. this.L2_2 = this.L2_2.scale(scale);
  4560. this.L2_1 = this.L2_1.scale(scale);
  4561. this.L20 = this.L20.scale(scale);
  4562. this.L21 = this.L21.scale(scale);
  4563. this.L22 = this.L22.scale(scale);
  4564. };
  4565. return SphericalHarmonics;
  4566. }());
  4567. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4568. // SphericalPolynomial
  4569. var SphericalPolynomial = (function () {
  4570. function SphericalPolynomial() {
  4571. this.x = Vector3.Zero();
  4572. this.y = Vector3.Zero();
  4573. this.z = Vector3.Zero();
  4574. this.xx = Vector3.Zero();
  4575. this.yy = Vector3.Zero();
  4576. this.zz = Vector3.Zero();
  4577. this.xy = Vector3.Zero();
  4578. this.yz = Vector3.Zero();
  4579. this.zx = Vector3.Zero();
  4580. }
  4581. SphericalPolynomial.prototype.addAmbient = function (color) {
  4582. var colorVector = new Vector3(color.r, color.g, color.b);
  4583. this.xx = this.xx.add(colorVector);
  4584. this.yy = this.yy.add(colorVector);
  4585. this.zz = this.zz.add(colorVector);
  4586. };
  4587. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4588. var result = new SphericalPolynomial();
  4589. result.x = harmonics.L11.scale(1.02333);
  4590. result.y = harmonics.L1_1.scale(1.02333);
  4591. result.z = harmonics.L10.scale(1.02333);
  4592. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4593. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4594. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4595. result.yz = harmonics.L2_1.scale(0.858086);
  4596. result.zx = harmonics.L21.scale(0.858086);
  4597. result.xy = harmonics.L2_2.scale(0.858086);
  4598. return result;
  4599. };
  4600. return SphericalPolynomial;
  4601. }());
  4602. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4603. // Vertex formats
  4604. var PositionNormalVertex = (function () {
  4605. function PositionNormalVertex(position, normal) {
  4606. if (position === void 0) { position = Vector3.Zero(); }
  4607. if (normal === void 0) { normal = Vector3.Up(); }
  4608. this.position = position;
  4609. this.normal = normal;
  4610. }
  4611. PositionNormalVertex.prototype.clone = function () {
  4612. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4613. };
  4614. return PositionNormalVertex;
  4615. }());
  4616. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4617. var PositionNormalTextureVertex = (function () {
  4618. function PositionNormalTextureVertex(position, normal, uv) {
  4619. if (position === void 0) { position = Vector3.Zero(); }
  4620. if (normal === void 0) { normal = Vector3.Up(); }
  4621. if (uv === void 0) { uv = Vector2.Zero(); }
  4622. this.position = position;
  4623. this.normal = normal;
  4624. this.uv = uv;
  4625. }
  4626. PositionNormalTextureVertex.prototype.clone = function () {
  4627. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4628. };
  4629. return PositionNormalTextureVertex;
  4630. }());
  4631. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4632. // Temporary pre-allocated objects for engine internal use
  4633. // usage in any internal function :
  4634. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4635. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4636. var Tmp = (function () {
  4637. function Tmp() {
  4638. }
  4639. return Tmp;
  4640. }());
  4641. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4642. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4643. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4644. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4645. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4646. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4647. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4648. Matrix.Zero(), Matrix.Zero(),
  4649. Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4651. BABYLON.Tmp = Tmp;
  4652. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4653. var MathTmp = (function () {
  4654. function MathTmp() {
  4655. }
  4656. return MathTmp;
  4657. }());
  4658. MathTmp.Vector3 = [Vector3.Zero()];
  4659. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4660. MathTmp.Quaternion = [Quaternion.Zero()];
  4661. })(BABYLON || (BABYLON = {}));
  4662. //# sourceMappingURL=babylon.math.js.map
  4663. //# sourceMappingURL=babylon.mixins.js.map
  4664. var BABYLON;
  4665. (function (BABYLON) {
  4666. function generateSerializableMember(type, sourceName) {
  4667. return function (target, propertyKey) {
  4668. if (!target.__serializableMembers) {
  4669. target.__serializableMembers = {};
  4670. }
  4671. if (!target.__serializableMembers[propertyKey]) {
  4672. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4673. }
  4674. };
  4675. }
  4676. function serialize(sourceName) {
  4677. return generateSerializableMember(0, sourceName); // value member
  4678. }
  4679. BABYLON.serialize = serialize;
  4680. function serializeAsTexture(sourceName) {
  4681. return generateSerializableMember(1, sourceName); // texture member
  4682. }
  4683. BABYLON.serializeAsTexture = serializeAsTexture;
  4684. function serializeAsColor3(sourceName) {
  4685. return generateSerializableMember(2, sourceName); // color3 member
  4686. }
  4687. BABYLON.serializeAsColor3 = serializeAsColor3;
  4688. function serializeAsFresnelParameters(sourceName) {
  4689. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4690. }
  4691. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4692. function serializeAsVector2(sourceName) {
  4693. return generateSerializableMember(4, sourceName); // vector2 member
  4694. }
  4695. BABYLON.serializeAsVector2 = serializeAsVector2;
  4696. function serializeAsVector3(sourceName) {
  4697. return generateSerializableMember(5, sourceName); // vector3 member
  4698. }
  4699. BABYLON.serializeAsVector3 = serializeAsVector3;
  4700. function serializeAsMeshReference(sourceName) {
  4701. return generateSerializableMember(6, sourceName); // mesh reference member
  4702. }
  4703. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4704. function serializeAsColorCurves(sourceName) {
  4705. return generateSerializableMember(7, sourceName); // color curves
  4706. }
  4707. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4708. var SerializationHelper = (function () {
  4709. function SerializationHelper() {
  4710. }
  4711. SerializationHelper.Serialize = function (entity, serializationObject) {
  4712. if (!serializationObject) {
  4713. serializationObject = {};
  4714. }
  4715. // Tags
  4716. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4717. // Properties
  4718. for (var property in entity.__serializableMembers) {
  4719. var propertyDescriptor = entity.__serializableMembers[property];
  4720. var targetPropertyName = propertyDescriptor.sourceName || property;
  4721. var propertyType = propertyDescriptor.type;
  4722. var sourceProperty = entity[property];
  4723. if (sourceProperty !== undefined && sourceProperty !== null) {
  4724. switch (propertyType) {
  4725. case 0:
  4726. serializationObject[targetPropertyName] = sourceProperty;
  4727. break;
  4728. case 1:
  4729. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4730. break;
  4731. case 2:
  4732. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4733. break;
  4734. case 3:
  4735. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4736. break;
  4737. case 4:
  4738. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4739. break;
  4740. case 5:
  4741. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4742. break;
  4743. case 6:
  4744. serializationObject[targetPropertyName] = sourceProperty.id;
  4745. break;
  4746. case 7:
  4747. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4748. break;
  4749. }
  4750. }
  4751. }
  4752. return serializationObject;
  4753. };
  4754. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4755. var destination = creationFunction();
  4756. // Tags
  4757. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4758. // Properties
  4759. for (var property in destination.__serializableMembers) {
  4760. var propertyDescriptor = destination.__serializableMembers[property];
  4761. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4762. var propertyType = propertyDescriptor.type;
  4763. if (sourceProperty !== undefined && sourceProperty !== null) {
  4764. switch (propertyType) {
  4765. case 0:
  4766. destination[property] = sourceProperty;
  4767. break;
  4768. case 1:
  4769. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4770. break;
  4771. case 2:
  4772. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4773. break;
  4774. case 3:
  4775. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4776. break;
  4777. case 4:
  4778. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4779. break;
  4780. case 5:
  4781. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4782. break;
  4783. case 6:
  4784. destination[property] = scene.getLastMeshByID(sourceProperty);
  4785. break;
  4786. case 7:
  4787. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4788. break;
  4789. }
  4790. }
  4791. }
  4792. return destination;
  4793. };
  4794. SerializationHelper.Clone = function (creationFunction, source) {
  4795. var destination = creationFunction();
  4796. // Tags
  4797. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4798. // Properties
  4799. for (var property in destination.__serializableMembers) {
  4800. var propertyDescriptor = destination.__serializableMembers[property];
  4801. var sourceProperty = source[property];
  4802. var propertyType = propertyDescriptor.type;
  4803. if (sourceProperty !== undefined && sourceProperty !== null) {
  4804. switch (propertyType) {
  4805. case 0: // Value
  4806. case 6:
  4807. destination[property] = sourceProperty;
  4808. break;
  4809. case 1: // Texture
  4810. case 2: // Color3
  4811. case 3: // FresnelParameters
  4812. case 4: // Vector2
  4813. case 5: // Vector3
  4814. case 7:
  4815. destination[property] = sourceProperty.clone();
  4816. break;
  4817. }
  4818. }
  4819. }
  4820. return destination;
  4821. };
  4822. return SerializationHelper;
  4823. }());
  4824. BABYLON.SerializationHelper = SerializationHelper;
  4825. })(BABYLON || (BABYLON = {}));
  4826. //# sourceMappingURL=babylon.decorators.js.map
  4827. var BABYLON;
  4828. (function (BABYLON) {
  4829. /**
  4830. * A class serves as a medium between the observable and its observers
  4831. */
  4832. var EventState = (function () {
  4833. /**
  4834. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4835. */
  4836. function EventState(mask, skipNextObservers) {
  4837. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4838. this.initalize(mask, skipNextObservers);
  4839. }
  4840. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4841. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4842. this.mask = mask;
  4843. this.skipNextObservers = skipNextObservers;
  4844. return this;
  4845. };
  4846. return EventState;
  4847. }());
  4848. BABYLON.EventState = EventState;
  4849. /**
  4850. * Represent an Observer registered to a given Observable object.
  4851. */
  4852. var Observer = (function () {
  4853. function Observer(callback, mask) {
  4854. this.callback = callback;
  4855. this.mask = mask;
  4856. }
  4857. return Observer;
  4858. }());
  4859. BABYLON.Observer = Observer;
  4860. /**
  4861. * The Observable class is a simple implementation of the Observable pattern.
  4862. * 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.
  4863. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4864. * 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).
  4865. * 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.
  4866. */
  4867. var Observable = (function () {
  4868. function Observable() {
  4869. this._observers = new Array();
  4870. this._eventState = new EventState(0);
  4871. }
  4872. /**
  4873. * Create a new Observer with the specified callback
  4874. * @param callback the callback that will be executed for that Observer
  4875. * @param mask the mask used to filter observers
  4876. * @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.
  4877. */
  4878. Observable.prototype.add = function (callback, mask, insertFirst) {
  4879. if (mask === void 0) { mask = -1; }
  4880. if (insertFirst === void 0) { insertFirst = false; }
  4881. if (!callback) {
  4882. return null;
  4883. }
  4884. var observer = new Observer(callback, mask);
  4885. if (insertFirst) {
  4886. this._observers.unshift(observer);
  4887. }
  4888. else {
  4889. this._observers.push(observer);
  4890. }
  4891. return observer;
  4892. };
  4893. /**
  4894. * Remove an Observer from the Observable object
  4895. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4896. */
  4897. Observable.prototype.remove = function (observer) {
  4898. var index = this._observers.indexOf(observer);
  4899. if (index !== -1) {
  4900. this._observers.splice(index, 1);
  4901. return true;
  4902. }
  4903. return false;
  4904. };
  4905. /**
  4906. * Remove a callback from the Observable object
  4907. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4908. */
  4909. Observable.prototype.removeCallback = function (callback) {
  4910. for (var index = 0; index < this._observers.length; index++) {
  4911. if (this._observers[index].callback === callback) {
  4912. this._observers.splice(index, 1);
  4913. return true;
  4914. }
  4915. }
  4916. return false;
  4917. };
  4918. /**
  4919. * Notify all Observers by calling their respective callback with the given data
  4920. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4921. * @param eventData
  4922. * @param mask
  4923. */
  4924. Observable.prototype.notifyObservers = function (eventData, mask) {
  4925. if (mask === void 0) { mask = -1; }
  4926. var state = this._eventState;
  4927. state.mask = mask;
  4928. state.skipNextObservers = false;
  4929. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4930. var obs = _a[_i];
  4931. if (obs.mask & mask) {
  4932. obs.callback(eventData, state);
  4933. }
  4934. if (state.skipNextObservers) {
  4935. return false;
  4936. }
  4937. }
  4938. return true;
  4939. };
  4940. /**
  4941. * return true is the Observable has at least one Observer registered
  4942. */
  4943. Observable.prototype.hasObservers = function () {
  4944. return this._observers.length > 0;
  4945. };
  4946. /**
  4947. * Clear the list of observers
  4948. */
  4949. Observable.prototype.clear = function () {
  4950. this._observers = new Array();
  4951. };
  4952. /**
  4953. * Clone the current observable
  4954. */
  4955. Observable.prototype.clone = function () {
  4956. var result = new Observable();
  4957. result._observers = this._observers.slice(0);
  4958. return result;
  4959. };
  4960. /**
  4961. * Does this observable handles observer registered with a given mask
  4962. * @param {number} trigger - the mask to be tested
  4963. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4964. **/
  4965. Observable.prototype.hasSpecificMask = function (mask) {
  4966. if (mask === void 0) { mask = -1; }
  4967. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4968. var obs = _a[_i];
  4969. if (obs.mask & mask && obs.mask === mask) {
  4970. return true;
  4971. }
  4972. }
  4973. return false;
  4974. };
  4975. return Observable;
  4976. }());
  4977. BABYLON.Observable = Observable;
  4978. })(BABYLON || (BABYLON = {}));
  4979. //# sourceMappingURL=babylon.observable.js.map
  4980. var BABYLON;
  4981. (function (BABYLON) {
  4982. var Database = (function () {
  4983. function Database(urlToScene, callbackManifestChecked) {
  4984. // Handling various flavors of prefixed version of IndexedDB
  4985. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4986. this.callbackManifestChecked = callbackManifestChecked;
  4987. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4988. this.db = null;
  4989. this.enableSceneOffline = false;
  4990. this.enableTexturesOffline = false;
  4991. this.manifestVersionFound = 0;
  4992. this.mustUpdateRessources = false;
  4993. this.hasReachedQuota = false;
  4994. if (!Database.IDBStorageEnabled) {
  4995. this.callbackManifestChecked(true);
  4996. }
  4997. else {
  4998. this.checkManifestFile();
  4999. }
  5000. }
  5001. Database.prototype.checkManifestFile = function () {
  5002. var _this = this;
  5003. function noManifestFile() {
  5004. that.enableSceneOffline = false;
  5005. that.enableTexturesOffline = false;
  5006. that.callbackManifestChecked(false);
  5007. }
  5008. var that = this;
  5009. var timeStampUsed = false;
  5010. var manifestURL = this.currentSceneUrl + ".manifest";
  5011. var xhr = new XMLHttpRequest();
  5012. if (navigator.onLine) {
  5013. // Adding a timestamp to by-pass browsers' cache
  5014. timeStampUsed = true;
  5015. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5016. }
  5017. xhr.open("GET", manifestURL, true);
  5018. xhr.addEventListener("load", function () {
  5019. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5020. try {
  5021. var manifestFile = JSON.parse(xhr.response);
  5022. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5023. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5024. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5025. _this.manifestVersionFound = manifestFile.version;
  5026. }
  5027. if (_this.callbackManifestChecked) {
  5028. _this.callbackManifestChecked(true);
  5029. }
  5030. }
  5031. catch (ex) {
  5032. noManifestFile();
  5033. }
  5034. }
  5035. else {
  5036. noManifestFile();
  5037. }
  5038. }, false);
  5039. xhr.addEventListener("error", function (event) {
  5040. if (timeStampUsed) {
  5041. timeStampUsed = false;
  5042. // Let's retry without the timeStamp
  5043. // It could fail when coupled with HTML5 Offline API
  5044. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5045. xhr.open("GET", retryManifestURL, true);
  5046. xhr.send();
  5047. }
  5048. else {
  5049. noManifestFile();
  5050. }
  5051. }, false);
  5052. try {
  5053. xhr.send();
  5054. }
  5055. catch (ex) {
  5056. BABYLON.Tools.Error("Error on XHR send request.");
  5057. that.callbackManifestChecked(false);
  5058. }
  5059. };
  5060. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5061. var _this = this;
  5062. function handleError() {
  5063. that.isSupported = false;
  5064. if (errorCallback)
  5065. errorCallback();
  5066. }
  5067. var that = this;
  5068. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5069. // Your browser doesn't support IndexedDB
  5070. this.isSupported = false;
  5071. if (errorCallback)
  5072. errorCallback();
  5073. }
  5074. else {
  5075. // If the DB hasn't been opened or created yet
  5076. if (!this.db) {
  5077. this.hasReachedQuota = false;
  5078. this.isSupported = true;
  5079. var request = this.idbFactory.open("babylonjs", 1);
  5080. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5081. request.onerror = function (event) {
  5082. handleError();
  5083. };
  5084. // executes when a version change transaction cannot complete due to other active transactions
  5085. request.onblocked = function (event) {
  5086. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5087. handleError();
  5088. };
  5089. // DB has been opened successfully
  5090. request.onsuccess = function (event) {
  5091. _this.db = request.result;
  5092. successCallback();
  5093. };
  5094. // Initialization of the DB. Creating Scenes & Textures stores
  5095. request.onupgradeneeded = function (event) {
  5096. _this.db = (event.target).result;
  5097. try {
  5098. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5099. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5100. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5101. }
  5102. catch (ex) {
  5103. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5104. handleError();
  5105. }
  5106. };
  5107. }
  5108. else {
  5109. if (successCallback)
  5110. successCallback();
  5111. }
  5112. }
  5113. };
  5114. Database.prototype.loadImageFromDB = function (url, image) {
  5115. var _this = this;
  5116. var completeURL = Database.ReturnFullUrlLocation(url);
  5117. var saveAndLoadImage = function () {
  5118. if (!_this.hasReachedQuota && _this.db !== null) {
  5119. // the texture is not yet in the DB, let's try to save it
  5120. _this._saveImageIntoDBAsync(completeURL, image);
  5121. }
  5122. else {
  5123. image.src = url;
  5124. }
  5125. };
  5126. if (!this.mustUpdateRessources) {
  5127. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5128. }
  5129. else {
  5130. saveAndLoadImage();
  5131. }
  5132. };
  5133. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5134. if (this.isSupported && this.db !== null) {
  5135. var texture;
  5136. var transaction = this.db.transaction(["textures"]);
  5137. transaction.onabort = function (event) {
  5138. image.src = url;
  5139. };
  5140. transaction.oncomplete = function (event) {
  5141. var blobTextureURL;
  5142. if (texture) {
  5143. var URL = window.URL || window.webkitURL;
  5144. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5145. image.onerror = function () {
  5146. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5147. image.src = url;
  5148. };
  5149. image.src = blobTextureURL;
  5150. }
  5151. else {
  5152. notInDBCallback();
  5153. }
  5154. };
  5155. var getRequest = transaction.objectStore("textures").get(url);
  5156. getRequest.onsuccess = function (event) {
  5157. texture = (event.target).result;
  5158. };
  5159. getRequest.onerror = function (event) {
  5160. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5161. image.src = url;
  5162. };
  5163. }
  5164. else {
  5165. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5166. image.src = url;
  5167. }
  5168. };
  5169. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5170. var _this = this;
  5171. if (this.isSupported) {
  5172. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5173. var generateBlobUrl = function () {
  5174. var blobTextureURL;
  5175. if (blob) {
  5176. var URL = window.URL || window.webkitURL;
  5177. try {
  5178. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5179. }
  5180. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5181. catch (ex) {
  5182. blobTextureURL = URL.createObjectURL(blob);
  5183. }
  5184. }
  5185. image.src = blobTextureURL;
  5186. };
  5187. if (Database.IsUASupportingBlobStorage) {
  5188. var xhr = new XMLHttpRequest(), blob;
  5189. xhr.open("GET", url, true);
  5190. xhr.responseType = "blob";
  5191. xhr.addEventListener("load", function () {
  5192. if (xhr.status === 200) {
  5193. // Blob as response (XHR2)
  5194. blob = xhr.response;
  5195. var transaction = _this.db.transaction(["textures"], "readwrite");
  5196. // the transaction could abort because of a QuotaExceededError error
  5197. transaction.onabort = function (event) {
  5198. try {
  5199. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5200. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5201. _this.hasReachedQuota = true;
  5202. }
  5203. }
  5204. catch (ex) { }
  5205. generateBlobUrl();
  5206. };
  5207. transaction.oncomplete = function (event) {
  5208. generateBlobUrl();
  5209. };
  5210. var newTexture = { textureUrl: url, data: blob };
  5211. try {
  5212. // Put the blob into the dabase
  5213. var addRequest = transaction.objectStore("textures").put(newTexture);
  5214. addRequest.onsuccess = function (event) {
  5215. };
  5216. addRequest.onerror = function (event) {
  5217. generateBlobUrl();
  5218. };
  5219. }
  5220. catch (ex) {
  5221. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5222. if (ex.code === 25) {
  5223. Database.IsUASupportingBlobStorage = false;
  5224. }
  5225. image.src = url;
  5226. }
  5227. }
  5228. else {
  5229. image.src = url;
  5230. }
  5231. }, false);
  5232. xhr.addEventListener("error", function (event) {
  5233. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5234. image.src = url;
  5235. }, false);
  5236. xhr.send();
  5237. }
  5238. else {
  5239. image.src = url;
  5240. }
  5241. }
  5242. else {
  5243. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5244. image.src = url;
  5245. }
  5246. };
  5247. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5248. var _this = this;
  5249. var updateVersion = function (event) {
  5250. // the version is not yet in the DB or we need to update it
  5251. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5252. };
  5253. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5254. };
  5255. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5256. var _this = this;
  5257. if (this.isSupported) {
  5258. var version;
  5259. try {
  5260. var transaction = this.db.transaction(["versions"]);
  5261. transaction.oncomplete = function (event) {
  5262. if (version) {
  5263. // If the version in the JSON file is > than the version in DB
  5264. if (_this.manifestVersionFound > version.data) {
  5265. _this.mustUpdateRessources = true;
  5266. updateInDBCallback();
  5267. }
  5268. else {
  5269. callback(version.data);
  5270. }
  5271. }
  5272. else {
  5273. _this.mustUpdateRessources = true;
  5274. updateInDBCallback();
  5275. }
  5276. };
  5277. transaction.onabort = function (event) {
  5278. callback(-1);
  5279. };
  5280. var getRequest = transaction.objectStore("versions").get(url);
  5281. getRequest.onsuccess = function (event) {
  5282. version = (event.target).result;
  5283. };
  5284. getRequest.onerror = function (event) {
  5285. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5286. callback(-1);
  5287. };
  5288. }
  5289. catch (ex) {
  5290. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5291. callback(-1);
  5292. }
  5293. }
  5294. else {
  5295. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5296. callback(-1);
  5297. }
  5298. };
  5299. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5300. var _this = this;
  5301. if (this.isSupported && !this.hasReachedQuota) {
  5302. try {
  5303. // Open a transaction to the database
  5304. var transaction = this.db.transaction(["versions"], "readwrite");
  5305. // the transaction could abort because of a QuotaExceededError error
  5306. transaction.onabort = function (event) {
  5307. try {
  5308. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5309. _this.hasReachedQuota = true;
  5310. }
  5311. }
  5312. catch (ex) { }
  5313. callback(-1);
  5314. };
  5315. transaction.oncomplete = function (event) {
  5316. callback(_this.manifestVersionFound);
  5317. };
  5318. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5319. // Put the scene into the database
  5320. var addRequest = transaction.objectStore("versions").put(newVersion);
  5321. addRequest.onsuccess = function (event) {
  5322. };
  5323. addRequest.onerror = function (event) {
  5324. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5325. };
  5326. }
  5327. catch (ex) {
  5328. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5329. callback(-1);
  5330. }
  5331. }
  5332. else {
  5333. callback(-1);
  5334. }
  5335. };
  5336. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5337. var _this = this;
  5338. var completeUrl = Database.ReturnFullUrlLocation(url);
  5339. var saveAndLoadFile = function (event) {
  5340. // the scene is not yet in the DB, let's try to save it
  5341. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5342. };
  5343. this._checkVersionFromDB(completeUrl, function (version) {
  5344. if (version !== -1) {
  5345. if (!_this.mustUpdateRessources) {
  5346. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5347. }
  5348. else {
  5349. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5350. }
  5351. }
  5352. else {
  5353. errorCallback();
  5354. }
  5355. });
  5356. };
  5357. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5358. if (this.isSupported) {
  5359. var targetStore;
  5360. if (url.indexOf(".babylon") !== -1) {
  5361. targetStore = "scenes";
  5362. }
  5363. else {
  5364. targetStore = "textures";
  5365. }
  5366. var file;
  5367. var transaction = this.db.transaction([targetStore]);
  5368. transaction.oncomplete = function (event) {
  5369. if (file) {
  5370. callback(file.data);
  5371. }
  5372. else {
  5373. notInDBCallback();
  5374. }
  5375. };
  5376. transaction.onabort = function (event) {
  5377. notInDBCallback();
  5378. };
  5379. var getRequest = transaction.objectStore(targetStore).get(url);
  5380. getRequest.onsuccess = function (event) {
  5381. file = (event.target).result;
  5382. };
  5383. getRequest.onerror = function (event) {
  5384. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5385. notInDBCallback();
  5386. };
  5387. }
  5388. else {
  5389. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5390. callback();
  5391. }
  5392. };
  5393. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5394. var _this = this;
  5395. if (this.isSupported) {
  5396. var targetStore;
  5397. if (url.indexOf(".babylon") !== -1) {
  5398. targetStore = "scenes";
  5399. }
  5400. else {
  5401. targetStore = "textures";
  5402. }
  5403. // Create XHR
  5404. var xhr = new XMLHttpRequest(), fileData;
  5405. xhr.open("GET", url, true);
  5406. if (useArrayBuffer) {
  5407. xhr.responseType = "arraybuffer";
  5408. }
  5409. xhr.onprogress = progressCallback;
  5410. xhr.addEventListener("load", function () {
  5411. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5412. // Blob as response (XHR2)
  5413. //fileData = xhr.responseText;
  5414. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5415. if (!_this.hasReachedQuota) {
  5416. // Open a transaction to the database
  5417. var transaction = _this.db.transaction([targetStore], "readwrite");
  5418. // the transaction could abort because of a QuotaExceededError error
  5419. transaction.onabort = function (event) {
  5420. try {
  5421. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5422. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5423. _this.hasReachedQuota = true;
  5424. }
  5425. }
  5426. catch (ex) { }
  5427. callback(fileData);
  5428. };
  5429. transaction.oncomplete = function (event) {
  5430. callback(fileData);
  5431. };
  5432. var newFile;
  5433. if (targetStore === "scenes") {
  5434. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5435. }
  5436. else {
  5437. newFile = { textureUrl: url, data: fileData };
  5438. }
  5439. try {
  5440. // Put the scene into the database
  5441. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5442. addRequest.onsuccess = function (event) {
  5443. };
  5444. addRequest.onerror = function (event) {
  5445. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5446. };
  5447. }
  5448. catch (ex) {
  5449. callback(fileData);
  5450. }
  5451. }
  5452. else {
  5453. callback(fileData);
  5454. }
  5455. }
  5456. else {
  5457. callback();
  5458. }
  5459. }, false);
  5460. xhr.addEventListener("error", function (event) {
  5461. BABYLON.Tools.Error("error on XHR request.");
  5462. callback();
  5463. }, false);
  5464. xhr.send();
  5465. }
  5466. else {
  5467. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5468. callback();
  5469. }
  5470. };
  5471. return Database;
  5472. }());
  5473. Database.IsUASupportingBlobStorage = true;
  5474. Database.IDBStorageEnabled = true;
  5475. Database.parseURL = function (url) {
  5476. var a = document.createElement('a');
  5477. a.href = url;
  5478. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5479. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5480. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5481. return absLocation;
  5482. };
  5483. Database.ReturnFullUrlLocation = function (url) {
  5484. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5485. return (Database.parseURL(window.location.href) + url);
  5486. }
  5487. else {
  5488. return url;
  5489. }
  5490. };
  5491. BABYLON.Database = Database;
  5492. })(BABYLON || (BABYLON = {}));
  5493. //# sourceMappingURL=babylon.database.js.map
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var Internals;
  5497. (function (Internals) {
  5498. /*
  5499. * Based on jsTGALoader - Javascript loader for TGA file
  5500. * By Vincent Thibault
  5501. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5502. */
  5503. var TGATools = (function () {
  5504. function TGATools() {
  5505. }
  5506. TGATools.GetTGAHeader = function (data) {
  5507. var offset = 0;
  5508. var header = {
  5509. id_length: data[offset++],
  5510. colormap_type: data[offset++],
  5511. image_type: data[offset++],
  5512. colormap_index: data[offset++] | data[offset++] << 8,
  5513. colormap_length: data[offset++] | data[offset++] << 8,
  5514. colormap_size: data[offset++],
  5515. origin: [
  5516. data[offset++] | data[offset++] << 8,
  5517. data[offset++] | data[offset++] << 8
  5518. ],
  5519. width: data[offset++] | data[offset++] << 8,
  5520. height: data[offset++] | data[offset++] << 8,
  5521. pixel_size: data[offset++],
  5522. flags: data[offset++]
  5523. };
  5524. return header;
  5525. };
  5526. TGATools.UploadContent = function (gl, data) {
  5527. // Not enough data to contain header ?
  5528. if (data.length < 19) {
  5529. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5530. return;
  5531. }
  5532. // Read Header
  5533. var offset = 18;
  5534. var header = TGATools.GetTGAHeader(data);
  5535. // Assume it's a valid Targa file.
  5536. if (header.id_length + offset > data.length) {
  5537. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5538. return;
  5539. }
  5540. // Skip not needed data
  5541. offset += header.id_length;
  5542. var use_rle = false;
  5543. var use_pal = false;
  5544. var use_rgb = false;
  5545. var use_grey = false;
  5546. // Get some informations.
  5547. switch (header.image_type) {
  5548. case TGATools._TYPE_RLE_INDEXED:
  5549. use_rle = true;
  5550. case TGATools._TYPE_INDEXED:
  5551. use_pal = true;
  5552. break;
  5553. case TGATools._TYPE_RLE_RGB:
  5554. use_rle = true;
  5555. case TGATools._TYPE_RGB:
  5556. use_rgb = true;
  5557. break;
  5558. case TGATools._TYPE_RLE_GREY:
  5559. use_rle = true;
  5560. case TGATools._TYPE_GREY:
  5561. use_grey = true;
  5562. break;
  5563. }
  5564. var pixel_data;
  5565. var numAlphaBits = header.flags & 0xf;
  5566. var pixel_size = header.pixel_size >> 3;
  5567. var pixel_total = header.width * header.height * pixel_size;
  5568. // Read palettes
  5569. var palettes;
  5570. if (use_pal) {
  5571. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5572. }
  5573. // Read LRE
  5574. if (use_rle) {
  5575. pixel_data = new Uint8Array(pixel_total);
  5576. var c, count, i;
  5577. var localOffset = 0;
  5578. var pixels = new Uint8Array(pixel_size);
  5579. while (offset < pixel_total && localOffset < pixel_total) {
  5580. c = data[offset++];
  5581. count = (c & 0x7f) + 1;
  5582. // RLE pixels
  5583. if (c & 0x80) {
  5584. // Bind pixel tmp array
  5585. for (i = 0; i < pixel_size; ++i) {
  5586. pixels[i] = data[offset++];
  5587. }
  5588. // Copy pixel array
  5589. for (i = 0; i < count; ++i) {
  5590. pixel_data.set(pixels, localOffset + i * pixel_size);
  5591. }
  5592. localOffset += pixel_size * count;
  5593. }
  5594. else {
  5595. count *= pixel_size;
  5596. for (i = 0; i < count; ++i) {
  5597. pixel_data[localOffset + i] = data[offset++];
  5598. }
  5599. localOffset += count;
  5600. }
  5601. }
  5602. }
  5603. else {
  5604. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5605. }
  5606. // Load to texture
  5607. var x_start, y_start, x_step, y_step, y_end, x_end;
  5608. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5609. default:
  5610. case TGATools._ORIGIN_UL:
  5611. x_start = 0;
  5612. x_step = 1;
  5613. x_end = header.width;
  5614. y_start = 0;
  5615. y_step = 1;
  5616. y_end = header.height;
  5617. break;
  5618. case TGATools._ORIGIN_BL:
  5619. x_start = 0;
  5620. x_step = 1;
  5621. x_end = header.width;
  5622. y_start = header.height - 1;
  5623. y_step = -1;
  5624. y_end = -1;
  5625. break;
  5626. case TGATools._ORIGIN_UR:
  5627. x_start = header.width - 1;
  5628. x_step = -1;
  5629. x_end = -1;
  5630. y_start = 0;
  5631. y_step = 1;
  5632. y_end = header.height;
  5633. break;
  5634. case TGATools._ORIGIN_BR:
  5635. x_start = header.width - 1;
  5636. x_step = -1;
  5637. x_end = -1;
  5638. y_start = header.height - 1;
  5639. y_step = -1;
  5640. y_end = -1;
  5641. break;
  5642. }
  5643. // Load the specify method
  5644. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5645. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5646. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5647. };
  5648. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5649. var image = pixel_data, colormap = palettes;
  5650. var width = header.width, height = header.height;
  5651. var color, i = 0, x, y;
  5652. var imageData = new Uint8Array(width * height * 4);
  5653. for (y = y_start; y !== y_end; y += y_step) {
  5654. for (x = x_start; x !== x_end; x += x_step, i++) {
  5655. color = image[i];
  5656. imageData[(x + width * y) * 4 + 3] = 255;
  5657. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5658. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5659. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5660. }
  5661. }
  5662. return imageData;
  5663. };
  5664. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5665. var image = pixel_data;
  5666. var width = header.width, height = header.height;
  5667. var color, i = 0, x, y;
  5668. var imageData = new Uint8Array(width * height * 4);
  5669. for (y = y_start; y !== y_end; y += y_step) {
  5670. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5671. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5672. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5673. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5674. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5675. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5676. }
  5677. }
  5678. return imageData;
  5679. };
  5680. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5681. var image = pixel_data;
  5682. var width = header.width, height = header.height;
  5683. var i = 0, x, y;
  5684. var imageData = new Uint8Array(width * height * 4);
  5685. for (y = y_start; y !== y_end; y += y_step) {
  5686. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5687. imageData[(x + width * y) * 4 + 3] = 255;
  5688. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5689. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5690. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5691. }
  5692. }
  5693. return imageData;
  5694. };
  5695. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5696. var image = pixel_data;
  5697. var width = header.width, height = header.height;
  5698. var i = 0, x, y;
  5699. var imageData = new Uint8Array(width * height * 4);
  5700. for (y = y_start; y !== y_end; y += y_step) {
  5701. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5702. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5703. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5704. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5705. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5706. }
  5707. }
  5708. return imageData;
  5709. };
  5710. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5711. var image = pixel_data;
  5712. var width = header.width, height = header.height;
  5713. var color, i = 0, x, y;
  5714. var imageData = new Uint8Array(width * height * 4);
  5715. for (y = y_start; y !== y_end; y += y_step) {
  5716. for (x = x_start; x !== x_end; x += x_step, i++) {
  5717. color = image[i];
  5718. imageData[(x + width * y) * 4 + 0] = color;
  5719. imageData[(x + width * y) * 4 + 1] = color;
  5720. imageData[(x + width * y) * 4 + 2] = color;
  5721. imageData[(x + width * y) * 4 + 3] = 255;
  5722. }
  5723. }
  5724. return imageData;
  5725. };
  5726. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5727. var image = pixel_data;
  5728. var width = header.width, height = header.height;
  5729. var i = 0, x, y;
  5730. var imageData = new Uint8Array(width * height * 4);
  5731. for (y = y_start; y !== y_end; y += y_step) {
  5732. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5733. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5734. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5735. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5736. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5737. }
  5738. }
  5739. return imageData;
  5740. };
  5741. return TGATools;
  5742. }());
  5743. TGATools._TYPE_NO_DATA = 0;
  5744. TGATools._TYPE_INDEXED = 1;
  5745. TGATools._TYPE_RGB = 2;
  5746. TGATools._TYPE_GREY = 3;
  5747. TGATools._TYPE_RLE_INDEXED = 9;
  5748. TGATools._TYPE_RLE_RGB = 10;
  5749. TGATools._TYPE_RLE_GREY = 11;
  5750. TGATools._ORIGIN_MASK = 0x30;
  5751. TGATools._ORIGIN_SHIFT = 0x04;
  5752. TGATools._ORIGIN_BL = 0x00;
  5753. TGATools._ORIGIN_BR = 0x01;
  5754. TGATools._ORIGIN_UL = 0x02;
  5755. TGATools._ORIGIN_UR = 0x03;
  5756. Internals.TGATools = TGATools;
  5757. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5758. })(BABYLON || (BABYLON = {}));
  5759. //# sourceMappingURL=babylon.tools.tga.js.map
  5760. var BABYLON;
  5761. (function (BABYLON) {
  5762. var SmartArray = (function () {
  5763. function SmartArray(capacity) {
  5764. this.length = 0;
  5765. this._duplicateId = 0;
  5766. this.data = new Array(capacity);
  5767. this._id = SmartArray._GlobalId++;
  5768. }
  5769. SmartArray.prototype.push = function (value) {
  5770. this.data[this.length++] = value;
  5771. if (this.length > this.data.length) {
  5772. this.data.length *= 2;
  5773. }
  5774. if (!value.__smartArrayFlags) {
  5775. value.__smartArrayFlags = {};
  5776. }
  5777. value.__smartArrayFlags[this._id] = this._duplicateId;
  5778. };
  5779. SmartArray.prototype.forEach = function (func) {
  5780. for (var index = 0; index < this.length; index++) {
  5781. func(this.data[index]);
  5782. }
  5783. };
  5784. SmartArray.prototype.pushNoDuplicate = function (value) {
  5785. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5786. return false;
  5787. }
  5788. this.push(value);
  5789. return true;
  5790. };
  5791. SmartArray.prototype.sort = function (compareFn) {
  5792. this.data.sort(compareFn);
  5793. };
  5794. SmartArray.prototype.reset = function () {
  5795. this.length = 0;
  5796. this._duplicateId++;
  5797. };
  5798. SmartArray.prototype.dispose = function () {
  5799. this.reset();
  5800. this.data.length = 0;
  5801. };
  5802. SmartArray.prototype.concat = function (array) {
  5803. if (array.length === 0) {
  5804. return;
  5805. }
  5806. if (this.length + array.length > this.data.length) {
  5807. this.data.length = (this.length + array.length) * 2;
  5808. }
  5809. for (var index = 0; index < array.length; index++) {
  5810. this.data[this.length++] = (array.data || array)[index];
  5811. }
  5812. };
  5813. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5814. if (array.length === 0) {
  5815. return;
  5816. }
  5817. if (this.length + array.length > this.data.length) {
  5818. this.data.length = (this.length + array.length) * 2;
  5819. }
  5820. for (var index = 0; index < array.length; index++) {
  5821. var item = (array.data || array)[index];
  5822. this.pushNoDuplicate(item);
  5823. }
  5824. };
  5825. SmartArray.prototype.indexOf = function (value) {
  5826. var position = this.data.indexOf(value);
  5827. if (position >= this.length) {
  5828. return -1;
  5829. }
  5830. return position;
  5831. };
  5832. return SmartArray;
  5833. }());
  5834. // Statics
  5835. SmartArray._GlobalId = 0;
  5836. BABYLON.SmartArray = SmartArray;
  5837. })(BABYLON || (BABYLON = {}));
  5838. //# sourceMappingURL=babylon.smartArray.js.map
  5839. var BABYLON;
  5840. (function (BABYLON) {
  5841. /**
  5842. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5843. * The underlying implementation relies on an associative array to ensure the best performances.
  5844. * The value can be anything including 'null' but except 'undefined'
  5845. */
  5846. var StringDictionary = (function () {
  5847. function StringDictionary() {
  5848. this._count = 0;
  5849. this._data = {};
  5850. }
  5851. /**
  5852. * This will clear this dictionary and copy the content from the 'source' one.
  5853. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5854. * @param source the dictionary to take the content from and copy to this dictionary
  5855. */
  5856. StringDictionary.prototype.copyFrom = function (source) {
  5857. var _this = this;
  5858. this.clear();
  5859. source.forEach(function (t, v) { return _this.add(t, v); });
  5860. };
  5861. /**
  5862. * Get a value based from its key
  5863. * @param key the given key to get the matching value from
  5864. * @return the value if found, otherwise undefined is returned
  5865. */
  5866. StringDictionary.prototype.get = function (key) {
  5867. var val = this._data[key];
  5868. if (val !== undefined) {
  5869. return val;
  5870. }
  5871. return undefined;
  5872. };
  5873. /**
  5874. * Get a value from its key or add it if it doesn't exist.
  5875. * This method will ensure you that a given key/data will be present in the dictionary.
  5876. * @param key the given key to get the matching value from
  5877. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5878. * The factory will only be invoked if there's no data for the given key.
  5879. * @return the value corresponding to the key.
  5880. */
  5881. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5882. var val = this.get(key);
  5883. if (val !== undefined) {
  5884. return val;
  5885. }
  5886. val = factory(key);
  5887. if (val) {
  5888. this.add(key, val);
  5889. }
  5890. return val;
  5891. };
  5892. /**
  5893. * Get a value from its key if present in the dictionary otherwise add it
  5894. * @param key the key to get the value from
  5895. * @param val if there's no such key/value pair in the dictionary add it with this value
  5896. * @return the value corresponding to the key
  5897. */
  5898. StringDictionary.prototype.getOrAdd = function (key, val) {
  5899. var curVal = this.get(key);
  5900. if (curVal !== undefined) {
  5901. return curVal;
  5902. }
  5903. this.add(key, val);
  5904. return val;
  5905. };
  5906. /**
  5907. * Check if there's a given key in the dictionary
  5908. * @param key the key to check for
  5909. * @return true if the key is present, false otherwise
  5910. */
  5911. StringDictionary.prototype.contains = function (key) {
  5912. return this._data[key] !== undefined;
  5913. };
  5914. /**
  5915. * Add a new key and its corresponding value
  5916. * @param key the key to add
  5917. * @param value the value corresponding to the key
  5918. * @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
  5919. */
  5920. StringDictionary.prototype.add = function (key, value) {
  5921. if (this._data[key] !== undefined) {
  5922. return false;
  5923. }
  5924. this._data[key] = value;
  5925. ++this._count;
  5926. return true;
  5927. };
  5928. StringDictionary.prototype.set = function (key, value) {
  5929. if (this._data[key] === undefined) {
  5930. return false;
  5931. }
  5932. this._data[key] = value;
  5933. return true;
  5934. };
  5935. /**
  5936. * Get the element of the given key and remove it from the dictionary
  5937. * @param key
  5938. */
  5939. StringDictionary.prototype.getAndRemove = function (key) {
  5940. var val = this.get(key);
  5941. if (val !== undefined) {
  5942. delete this._data[key];
  5943. --this._count;
  5944. return val;
  5945. }
  5946. return null;
  5947. };
  5948. /**
  5949. * Remove a key/value from the dictionary.
  5950. * @param key the key to remove
  5951. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5952. */
  5953. StringDictionary.prototype.remove = function (key) {
  5954. if (this.contains(key)) {
  5955. delete this._data[key];
  5956. --this._count;
  5957. return true;
  5958. }
  5959. return false;
  5960. };
  5961. /**
  5962. * Clear the whole content of the dictionary
  5963. */
  5964. StringDictionary.prototype.clear = function () {
  5965. this._data = {};
  5966. this._count = 0;
  5967. };
  5968. Object.defineProperty(StringDictionary.prototype, "count", {
  5969. get: function () {
  5970. return this._count;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. /**
  5976. * Execute a callback on each key/val of the dictionary.
  5977. * Note that you can remove any element in this dictionary in the callback implementation
  5978. * @param callback the callback to execute on a given key/value pair
  5979. */
  5980. StringDictionary.prototype.forEach = function (callback) {
  5981. for (var cur in this._data) {
  5982. var val = this._data[cur];
  5983. callback(cur, val);
  5984. }
  5985. };
  5986. /**
  5987. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5988. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5989. * Note that you can remove any element in this dictionary in the callback implementation
  5990. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5991. */
  5992. StringDictionary.prototype.first = function (callback) {
  5993. for (var cur in this._data) {
  5994. var val = this._data[cur];
  5995. var res = callback(cur, val);
  5996. if (res) {
  5997. return res;
  5998. }
  5999. }
  6000. return null;
  6001. };
  6002. return StringDictionary;
  6003. }());
  6004. BABYLON.StringDictionary = StringDictionary;
  6005. })(BABYLON || (BABYLON = {}));
  6006. //# sourceMappingURL=babylon.stringDictionary.js.map
  6007. var BABYLON;
  6008. (function (BABYLON) {
  6009. // Screenshots
  6010. var screenshotCanvas;
  6011. var cloneValue = function (source, destinationObject) {
  6012. if (!source)
  6013. return null;
  6014. if (source instanceof BABYLON.Mesh) {
  6015. return null;
  6016. }
  6017. if (source instanceof BABYLON.SubMesh) {
  6018. return source.clone(destinationObject);
  6019. }
  6020. else if (source.clone) {
  6021. return source.clone();
  6022. }
  6023. return null;
  6024. };
  6025. var Tools = (function () {
  6026. function Tools() {
  6027. }
  6028. ;
  6029. Tools.Instantiate = function (className) {
  6030. var arr = className.split(".");
  6031. var fn = (window || this);
  6032. for (var i = 0, len = arr.length; i < len; i++) {
  6033. fn = fn[arr[i]];
  6034. }
  6035. if (typeof fn !== "function") {
  6036. return null;
  6037. }
  6038. return fn;
  6039. };
  6040. Tools.SetImmediate = function (action) {
  6041. if (window.setImmediate) {
  6042. window.setImmediate(action);
  6043. }
  6044. else {
  6045. setTimeout(action, 1);
  6046. }
  6047. };
  6048. Tools.IsExponentOfTwo = function (value) {
  6049. var count = 1;
  6050. do {
  6051. count *= 2;
  6052. } while (count < value);
  6053. return count === value;
  6054. };
  6055. Tools.GetExponentOfTwo = function (value, max) {
  6056. var count = 1;
  6057. do {
  6058. count *= 2;
  6059. } while (count < value);
  6060. if (count > max)
  6061. count = max;
  6062. return count;
  6063. };
  6064. Tools.GetFilename = function (path) {
  6065. var index = path.lastIndexOf("/");
  6066. if (index < 0)
  6067. return path;
  6068. return path.substring(index + 1);
  6069. };
  6070. Tools.GetDOMTextContent = function (element) {
  6071. var result = "";
  6072. var child = element.firstChild;
  6073. while (child) {
  6074. if (child.nodeType === 3) {
  6075. result += child.textContent;
  6076. }
  6077. child = child.nextSibling;
  6078. }
  6079. return result;
  6080. };
  6081. Tools.ToDegrees = function (angle) {
  6082. return angle * 180 / Math.PI;
  6083. };
  6084. Tools.ToRadians = function (angle) {
  6085. return angle * Math.PI / 180;
  6086. };
  6087. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6088. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6089. var output = "";
  6090. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6091. var i = 0;
  6092. var bytes = new Uint8Array(buffer);
  6093. while (i < bytes.length) {
  6094. chr1 = bytes[i++];
  6095. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6096. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6097. enc1 = chr1 >> 2;
  6098. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6099. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6100. enc4 = chr3 & 63;
  6101. if (isNaN(chr2)) {
  6102. enc3 = enc4 = 64;
  6103. }
  6104. else if (isNaN(chr3)) {
  6105. enc4 = 64;
  6106. }
  6107. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6108. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6109. }
  6110. return "data:image/png;base64," + output;
  6111. };
  6112. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6113. if (bias === void 0) { bias = null; }
  6114. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6115. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6116. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6117. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6118. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6119. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6120. }
  6121. if (bias) {
  6122. minimum.x -= minimum.x * bias.x + bias.y;
  6123. minimum.y -= minimum.y * bias.x + bias.y;
  6124. minimum.z -= minimum.z * bias.x + bias.y;
  6125. maximum.x += maximum.x * bias.x + bias.y;
  6126. maximum.y += maximum.y * bias.x + bias.y;
  6127. maximum.z += maximum.z * bias.x + bias.y;
  6128. }
  6129. return {
  6130. minimum: minimum,
  6131. maximum: maximum
  6132. };
  6133. };
  6134. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6135. if (bias === void 0) { bias = null; }
  6136. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6137. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6138. if (!stride) {
  6139. stride = 3;
  6140. }
  6141. for (var index = start; index < start + count; index++) {
  6142. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6143. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6144. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6145. }
  6146. if (bias) {
  6147. minimum.x -= minimum.x * bias.x + bias.y;
  6148. minimum.y -= minimum.y * bias.x + bias.y;
  6149. minimum.z -= minimum.z * bias.x + bias.y;
  6150. maximum.x += maximum.x * bias.x + bias.y;
  6151. maximum.y += maximum.y * bias.x + bias.y;
  6152. maximum.z += maximum.z * bias.x + bias.y;
  6153. }
  6154. return {
  6155. minimum: minimum,
  6156. maximum: maximum
  6157. };
  6158. };
  6159. Tools.Vector2ArrayFeeder = function (array) {
  6160. return function (index) {
  6161. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6162. var length = isFloatArray ? array.length / 2 : array.length;
  6163. if (index >= length) {
  6164. return null;
  6165. }
  6166. if (isFloatArray) {
  6167. var fa = array;
  6168. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6169. }
  6170. var a = array;
  6171. return a[index];
  6172. };
  6173. };
  6174. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6175. if (bias === void 0) { bias = null; }
  6176. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6177. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6178. var i = 0;
  6179. var cur = feeder(i++);
  6180. while (cur) {
  6181. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6182. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6183. cur = feeder(i++);
  6184. }
  6185. if (bias) {
  6186. minimum.x -= minimum.x * bias.x + bias.y;
  6187. minimum.y -= minimum.y * bias.x + bias.y;
  6188. maximum.x += maximum.x * bias.x + bias.y;
  6189. maximum.y += maximum.y * bias.x + bias.y;
  6190. }
  6191. return {
  6192. minimum: minimum,
  6193. maximum: maximum
  6194. };
  6195. };
  6196. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6197. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6198. return undefined;
  6199. return Array.isArray(obj) ? obj : [obj];
  6200. };
  6201. // Misc.
  6202. Tools.GetPointerPrefix = function () {
  6203. var eventPrefix = "pointer";
  6204. // Check if pointer events are supported
  6205. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6206. eventPrefix = "mouse";
  6207. }
  6208. return eventPrefix;
  6209. };
  6210. /**
  6211. * @param func - the function to be called
  6212. * @param requester - the object that will request the next frame. Falls back to window.
  6213. */
  6214. Tools.QueueNewFrame = function (func, requester) {
  6215. if (requester === void 0) { requester = window; }
  6216. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6217. /*if(requester.isPresenting) {
  6218. return;
  6219. } else*/ if (requester.requestAnimationFrame)
  6220. requester.requestAnimationFrame(func);
  6221. else if (requester.msRequestAnimationFrame)
  6222. requester.msRequestAnimationFrame(func);
  6223. else if (requester.webkitRequestAnimationFrame)
  6224. requester.webkitRequestAnimationFrame(func);
  6225. else if (requester.mozRequestAnimationFrame)
  6226. requester.mozRequestAnimationFrame(func);
  6227. else if (requester.oRequestAnimationFrame)
  6228. requester.oRequestAnimationFrame(func);
  6229. else {
  6230. window.setTimeout(func, 16);
  6231. }
  6232. };
  6233. Tools.RequestFullscreen = function (element) {
  6234. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6235. if (!requestFunction)
  6236. return;
  6237. requestFunction.call(element);
  6238. };
  6239. Tools.ExitFullscreen = function () {
  6240. if (document.exitFullscreen) {
  6241. document.exitFullscreen();
  6242. }
  6243. else if (document.mozCancelFullScreen) {
  6244. document.mozCancelFullScreen();
  6245. }
  6246. else if (document.webkitCancelFullScreen) {
  6247. document.webkitCancelFullScreen();
  6248. }
  6249. else if (document.msCancelFullScreen) {
  6250. document.msCancelFullScreen();
  6251. }
  6252. };
  6253. Tools.SetCorsBehavior = function (url, img) {
  6254. if (Tools.CorsBehavior) {
  6255. switch (typeof (Tools.CorsBehavior)) {
  6256. case "function":
  6257. var result = Tools.CorsBehavior(url);
  6258. if (result) {
  6259. img.crossOrigin = result;
  6260. }
  6261. break;
  6262. case "string":
  6263. default:
  6264. img.crossOrigin = Tools.CorsBehavior;
  6265. break;
  6266. }
  6267. }
  6268. };
  6269. // External files
  6270. Tools.CleanUrl = function (url) {
  6271. url = url.replace(/#/mg, "%23");
  6272. return url;
  6273. };
  6274. Tools.LoadImage = function (url, onload, onerror, database) {
  6275. if (url instanceof ArrayBuffer) {
  6276. url = Tools.EncodeArrayBufferTobase64(url);
  6277. }
  6278. url = Tools.CleanUrl(url);
  6279. var img = new Image();
  6280. if (url.substr(0, 5) !== "data:") {
  6281. Tools.SetCorsBehavior(url, img);
  6282. }
  6283. img.onload = function () {
  6284. onload(img);
  6285. };
  6286. img.onerror = function (err) {
  6287. Tools.Error("Error while trying to load image: " + url);
  6288. if (Tools.UseFallbackTexture) {
  6289. img.src = Tools.fallbackTexture;
  6290. onload(img);
  6291. }
  6292. else {
  6293. onerror();
  6294. }
  6295. };
  6296. var noIndexedDB = function () {
  6297. img.src = url;
  6298. };
  6299. var loadFromIndexedDB = function () {
  6300. database.loadImageFromDB(url, img);
  6301. };
  6302. //ANY database to do!
  6303. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6304. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6305. }
  6306. else {
  6307. if (url.indexOf("file:") === -1) {
  6308. noIndexedDB();
  6309. }
  6310. else {
  6311. var textureName = url.substring(5).toLowerCase();
  6312. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6313. try {
  6314. var blobURL;
  6315. try {
  6316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6317. }
  6318. catch (ex) {
  6319. // Chrome doesn't support oneTimeOnly parameter
  6320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6321. }
  6322. img.src = blobURL;
  6323. }
  6324. catch (e) {
  6325. img.src = null;
  6326. }
  6327. }
  6328. else {
  6329. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6330. img.src = Tools.fallbackTexture;
  6331. }
  6332. }
  6333. }
  6334. return img;
  6335. };
  6336. //ANY
  6337. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6338. url = Tools.CleanUrl(url);
  6339. var noIndexedDB = function () {
  6340. var request = new XMLHttpRequest();
  6341. var loadUrl = Tools.BaseUrl + url;
  6342. request.open('GET', loadUrl, true);
  6343. if (useArrayBuffer) {
  6344. request.responseType = "arraybuffer";
  6345. }
  6346. request.onprogress = progressCallBack;
  6347. request.onreadystatechange = function () {
  6348. if (request.readyState === 4) {
  6349. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6350. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6351. callback(!useArrayBuffer ? request.responseText : request.response);
  6352. }
  6353. else {
  6354. if (onError) {
  6355. onError();
  6356. }
  6357. else {
  6358. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6359. }
  6360. }
  6361. }
  6362. };
  6363. request.send(null);
  6364. };
  6365. var loadFromIndexedDB = function () {
  6366. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6367. };
  6368. if (url.indexOf("file:") !== -1) {
  6369. var fileName = url.substring(5).toLowerCase();
  6370. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6371. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6372. }
  6373. else {
  6374. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6375. }
  6376. }
  6377. else {
  6378. // Caching all files
  6379. if (database && database.enableSceneOffline) {
  6380. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6381. }
  6382. else {
  6383. noIndexedDB();
  6384. }
  6385. }
  6386. };
  6387. /**
  6388. * Load a script (identified by an url). When the url returns, the
  6389. * content of this file is added into a new script element, attached to the DOM (body element)
  6390. */
  6391. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6392. var head = document.getElementsByTagName('head')[0];
  6393. var script = document.createElement('script');
  6394. script.type = 'text/javascript';
  6395. script.src = scriptUrl;
  6396. var self = this;
  6397. script.onload = function () {
  6398. if (onSuccess) {
  6399. onSuccess();
  6400. }
  6401. };
  6402. script.onerror = function () {
  6403. if (onError) {
  6404. onError();
  6405. }
  6406. };
  6407. head.appendChild(script);
  6408. };
  6409. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6410. var reader = new FileReader();
  6411. reader.onload = function (e) {
  6412. //target doesn't have result from ts 1.3
  6413. callback(e.target['result']);
  6414. };
  6415. reader.onprogress = progressCallback;
  6416. reader.readAsDataURL(fileToLoad);
  6417. };
  6418. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6419. var reader = new FileReader();
  6420. reader.onerror = function (e) {
  6421. Tools.Log("Error while reading file: " + fileToLoad.name);
  6422. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6423. };
  6424. reader.onload = function (e) {
  6425. //target doesn't have result from ts 1.3
  6426. callback(e.target['result']);
  6427. };
  6428. reader.onprogress = progressCallBack;
  6429. if (!useArrayBuffer) {
  6430. // Asynchronous read
  6431. reader.readAsText(fileToLoad);
  6432. }
  6433. else {
  6434. reader.readAsArrayBuffer(fileToLoad);
  6435. }
  6436. };
  6437. //returns a downloadable url to a file content.
  6438. Tools.FileAsURL = function (content) {
  6439. var fileBlob = new Blob([content]);
  6440. var url = window.URL || window.webkitURL;
  6441. var link = url.createObjectURL(fileBlob);
  6442. return link;
  6443. };
  6444. // Misc.
  6445. Tools.Format = function (value, decimals) {
  6446. if (decimals === void 0) { decimals = 2; }
  6447. return value.toFixed(decimals);
  6448. };
  6449. Tools.CheckExtends = function (v, min, max) {
  6450. if (v.x < min.x)
  6451. min.x = v.x;
  6452. if (v.y < min.y)
  6453. min.y = v.y;
  6454. if (v.z < min.z)
  6455. min.z = v.z;
  6456. if (v.x > max.x)
  6457. max.x = v.x;
  6458. if (v.y > max.y)
  6459. max.y = v.y;
  6460. if (v.z > max.z)
  6461. max.z = v.z;
  6462. };
  6463. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6464. for (var prop in source) {
  6465. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6466. continue;
  6467. }
  6468. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6469. continue;
  6470. }
  6471. var sourceValue = source[prop];
  6472. var typeOfSourceValue = typeof sourceValue;
  6473. if (typeOfSourceValue === "function") {
  6474. continue;
  6475. }
  6476. if (typeOfSourceValue === "object") {
  6477. if (sourceValue instanceof Array) {
  6478. destination[prop] = [];
  6479. if (sourceValue.length > 0) {
  6480. if (typeof sourceValue[0] == "object") {
  6481. for (var index = 0; index < sourceValue.length; index++) {
  6482. var clonedValue = cloneValue(sourceValue[index], destination);
  6483. if (destination[prop].indexOf(clonedValue) === -1) {
  6484. destination[prop].push(clonedValue);
  6485. }
  6486. }
  6487. }
  6488. else {
  6489. destination[prop] = sourceValue.slice(0);
  6490. }
  6491. }
  6492. }
  6493. else {
  6494. destination[prop] = cloneValue(sourceValue, destination);
  6495. }
  6496. }
  6497. else {
  6498. destination[prop] = sourceValue;
  6499. }
  6500. }
  6501. };
  6502. Tools.IsEmpty = function (obj) {
  6503. for (var i in obj) {
  6504. return false;
  6505. }
  6506. return true;
  6507. };
  6508. Tools.RegisterTopRootEvents = function (events) {
  6509. for (var index = 0; index < events.length; index++) {
  6510. var event = events[index];
  6511. window.addEventListener(event.name, event.handler, false);
  6512. try {
  6513. if (window.parent) {
  6514. window.parent.addEventListener(event.name, event.handler, false);
  6515. }
  6516. }
  6517. catch (e) {
  6518. }
  6519. }
  6520. };
  6521. Tools.UnregisterTopRootEvents = function (events) {
  6522. for (var index = 0; index < events.length; index++) {
  6523. var event = events[index];
  6524. window.removeEventListener(event.name, event.handler);
  6525. try {
  6526. if (window.parent) {
  6527. window.parent.removeEventListener(event.name, event.handler);
  6528. }
  6529. }
  6530. catch (e) {
  6531. }
  6532. }
  6533. };
  6534. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6535. if (mimeType === void 0) { mimeType = "image/png"; }
  6536. // Read the contents of the framebuffer
  6537. var numberOfChannelsByLine = width * 4;
  6538. var halfHeight = height / 2;
  6539. //Reading datas from WebGL
  6540. var data = engine.readPixels(0, 0, width, height);
  6541. //To flip image on Y axis.
  6542. for (var i = 0; i < halfHeight; i++) {
  6543. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6544. var currentCell = j + i * numberOfChannelsByLine;
  6545. var targetLine = height - i - 1;
  6546. var targetCell = j + targetLine * numberOfChannelsByLine;
  6547. var temp = data[currentCell];
  6548. data[currentCell] = data[targetCell];
  6549. data[targetCell] = temp;
  6550. }
  6551. }
  6552. // Create a 2D canvas to store the result
  6553. if (!screenshotCanvas) {
  6554. screenshotCanvas = document.createElement('canvas');
  6555. }
  6556. screenshotCanvas.width = width;
  6557. screenshotCanvas.height = height;
  6558. var context = screenshotCanvas.getContext('2d');
  6559. // Copy the pixels to a 2D canvas
  6560. var imageData = context.createImageData(width, height);
  6561. var castData = (imageData.data);
  6562. castData.set(data);
  6563. context.putImageData(imageData, 0, 0);
  6564. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6565. };
  6566. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6567. if (mimeType === void 0) { mimeType = "image/png"; }
  6568. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6569. if (successCallback) {
  6570. successCallback(base64Image);
  6571. }
  6572. else {
  6573. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6574. if (("download" in document.createElement("a"))) {
  6575. var a = window.document.createElement("a");
  6576. a.href = base64Image;
  6577. var date = new Date();
  6578. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6579. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6580. window.document.body.appendChild(a);
  6581. a.addEventListener("click", function () {
  6582. a.parentElement.removeChild(a);
  6583. });
  6584. a.click();
  6585. }
  6586. else {
  6587. var newWindow = window.open("");
  6588. var img = newWindow.document.createElement("img");
  6589. img.src = base64Image;
  6590. newWindow.document.body.appendChild(img);
  6591. }
  6592. }
  6593. };
  6594. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6595. if (mimeType === void 0) { mimeType = "image/png"; }
  6596. var width;
  6597. var height;
  6598. // If a precision value is specified
  6599. if (size.precision) {
  6600. width = Math.round(engine.getRenderWidth() * size.precision);
  6601. height = Math.round(width / engine.getAspectRatio(camera));
  6602. }
  6603. else if (size.width && size.height) {
  6604. width = size.width;
  6605. height = size.height;
  6606. }
  6607. else if (size.width && !size.height) {
  6608. width = size.width;
  6609. height = Math.round(width / engine.getAspectRatio(camera));
  6610. }
  6611. else if (size.height && !size.width) {
  6612. height = size.height;
  6613. width = Math.round(height * engine.getAspectRatio(camera));
  6614. }
  6615. else if (!isNaN(size)) {
  6616. height = size;
  6617. width = size;
  6618. }
  6619. else {
  6620. Tools.Error("Invalid 'size' parameter !");
  6621. return;
  6622. }
  6623. if (!screenshotCanvas) {
  6624. screenshotCanvas = document.createElement('canvas');
  6625. }
  6626. screenshotCanvas.width = width;
  6627. screenshotCanvas.height = height;
  6628. var renderContext = screenshotCanvas.getContext("2d");
  6629. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6630. var newWidth = width;
  6631. var newHeight = newWidth / ratio;
  6632. if (newHeight > height) {
  6633. newHeight = height;
  6634. newWidth = newHeight * ratio;
  6635. }
  6636. var offsetX = Math.max(0, width - newWidth) / 2;
  6637. var offsetY = Math.max(0, height - newHeight) / 2;
  6638. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6639. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6640. };
  6641. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6642. if (mimeType === void 0) { mimeType = "image/png"; }
  6643. if (samples === void 0) { samples = 1; }
  6644. var width;
  6645. var height;
  6646. //If a precision value is specified
  6647. if (size.precision) {
  6648. width = Math.round(engine.getRenderWidth() * size.precision);
  6649. height = Math.round(width / engine.getAspectRatio(camera));
  6650. size = { width: width, height: height };
  6651. }
  6652. else if (size.width && size.height) {
  6653. width = size.width;
  6654. height = size.height;
  6655. }
  6656. else if (size.width && !size.height) {
  6657. width = size.width;
  6658. height = Math.round(width / engine.getAspectRatio(camera));
  6659. size = { width: width, height: height };
  6660. }
  6661. else if (size.height && !size.width) {
  6662. height = size.height;
  6663. width = Math.round(height * engine.getAspectRatio(camera));
  6664. size = { width: width, height: height };
  6665. }
  6666. else if (!isNaN(size)) {
  6667. height = size;
  6668. width = size;
  6669. }
  6670. else {
  6671. Tools.Error("Invalid 'size' parameter !");
  6672. return;
  6673. }
  6674. var scene = camera.getScene();
  6675. var previousCamera = null;
  6676. if (scene.activeCamera !== camera) {
  6677. previousCamera = scene.activeCamera;
  6678. scene.activeCamera = camera;
  6679. }
  6680. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6681. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6682. texture.renderList = scene.meshes;
  6683. texture.samples = samples;
  6684. texture.onAfterRenderObservable.add(function () {
  6685. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6686. });
  6687. scene.incrementRenderId();
  6688. scene.resetCachedMaterial();
  6689. texture.render(true);
  6690. texture.dispose();
  6691. if (previousCamera) {
  6692. scene.activeCamera = previousCamera;
  6693. }
  6694. camera.getProjectionMatrix(true); // Force cache refresh;
  6695. };
  6696. // XHR response validator for local file scenario
  6697. Tools.ValidateXHRData = function (xhr, dataType) {
  6698. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6699. if (dataType === void 0) { dataType = 7; }
  6700. try {
  6701. if (dataType & 1) {
  6702. if (xhr.responseText && xhr.responseText.length > 0) {
  6703. return true;
  6704. }
  6705. else if (dataType === 1) {
  6706. return false;
  6707. }
  6708. }
  6709. if (dataType & 2) {
  6710. // Check header width and height since there is no "TGA" magic number
  6711. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6712. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6713. return true;
  6714. }
  6715. else if (dataType === 2) {
  6716. return false;
  6717. }
  6718. }
  6719. if (dataType & 4) {
  6720. // Check for the "DDS" magic number
  6721. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6722. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6723. return true;
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. }
  6729. }
  6730. catch (e) {
  6731. }
  6732. return false;
  6733. };
  6734. /**
  6735. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6736. * Be aware Math.random() could cause collisions, but:
  6737. * "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"
  6738. */
  6739. Tools.RandomId = function () {
  6740. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6741. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6742. return v.toString(16);
  6743. });
  6744. };
  6745. Object.defineProperty(Tools, "NoneLogLevel", {
  6746. get: function () {
  6747. return Tools._NoneLogLevel;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Tools, "MessageLogLevel", {
  6753. get: function () {
  6754. return Tools._MessageLogLevel;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Tools, "WarningLogLevel", {
  6760. get: function () {
  6761. return Tools._WarningLogLevel;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Tools, "ErrorLogLevel", {
  6767. get: function () {
  6768. return Tools._ErrorLogLevel;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Tools, "AllLogLevel", {
  6774. get: function () {
  6775. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Tools._AddLogEntry = function (entry) {
  6781. Tools._LogCache = entry + Tools._LogCache;
  6782. if (Tools.OnNewCacheEntry) {
  6783. Tools.OnNewCacheEntry(entry);
  6784. }
  6785. };
  6786. Tools._FormatMessage = function (message) {
  6787. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6788. var date = new Date();
  6789. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6790. };
  6791. Tools._LogDisabled = function (message) {
  6792. // nothing to do
  6793. };
  6794. Tools._LogEnabled = function (message) {
  6795. var formattedMessage = Tools._FormatMessage(message);
  6796. console.log("BJS - " + formattedMessage);
  6797. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6798. Tools._AddLogEntry(entry);
  6799. };
  6800. Tools._WarnDisabled = function (message) {
  6801. // nothing to do
  6802. };
  6803. Tools._WarnEnabled = function (message) {
  6804. var formattedMessage = Tools._FormatMessage(message);
  6805. console.warn("BJS - " + formattedMessage);
  6806. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6807. Tools._AddLogEntry(entry);
  6808. };
  6809. Tools._ErrorDisabled = function (message) {
  6810. // nothing to do
  6811. };
  6812. Tools._ErrorEnabled = function (message) {
  6813. Tools.errorsCount++;
  6814. var formattedMessage = Tools._FormatMessage(message);
  6815. console.error("BJS - " + formattedMessage);
  6816. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6817. Tools._AddLogEntry(entry);
  6818. };
  6819. Object.defineProperty(Tools, "LogCache", {
  6820. get: function () {
  6821. return Tools._LogCache;
  6822. },
  6823. enumerable: true,
  6824. configurable: true
  6825. });
  6826. Tools.ClearLogCache = function () {
  6827. Tools._LogCache = "";
  6828. Tools.errorsCount = 0;
  6829. };
  6830. Object.defineProperty(Tools, "LogLevels", {
  6831. set: function (level) {
  6832. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6833. Tools.Log = Tools._LogEnabled;
  6834. }
  6835. else {
  6836. Tools.Log = Tools._LogDisabled;
  6837. }
  6838. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6839. Tools.Warn = Tools._WarnEnabled;
  6840. }
  6841. else {
  6842. Tools.Warn = Tools._WarnDisabled;
  6843. }
  6844. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6845. Tools.Error = Tools._ErrorEnabled;
  6846. }
  6847. else {
  6848. Tools.Error = Tools._ErrorDisabled;
  6849. }
  6850. },
  6851. enumerable: true,
  6852. configurable: true
  6853. });
  6854. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6855. get: function () {
  6856. return Tools._PerformanceNoneLogLevel;
  6857. },
  6858. enumerable: true,
  6859. configurable: true
  6860. });
  6861. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6862. get: function () {
  6863. return Tools._PerformanceUserMarkLogLevel;
  6864. },
  6865. enumerable: true,
  6866. configurable: true
  6867. });
  6868. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6869. get: function () {
  6870. return Tools._PerformanceConsoleLogLevel;
  6871. },
  6872. enumerable: true,
  6873. configurable: true
  6874. });
  6875. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6876. set: function (level) {
  6877. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6878. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6879. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6880. return;
  6881. }
  6882. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6883. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6884. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6885. return;
  6886. }
  6887. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6888. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6889. },
  6890. enumerable: true,
  6891. configurable: true
  6892. });
  6893. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6894. };
  6895. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6896. };
  6897. Tools._StartUserMark = function (counterName, condition) {
  6898. if (condition === void 0) { condition = true; }
  6899. if (!condition || !Tools._performance.mark) {
  6900. return;
  6901. }
  6902. Tools._performance.mark(counterName + "-Begin");
  6903. };
  6904. Tools._EndUserMark = function (counterName, condition) {
  6905. if (condition === void 0) { condition = true; }
  6906. if (!condition || !Tools._performance.mark) {
  6907. return;
  6908. }
  6909. Tools._performance.mark(counterName + "-End");
  6910. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6911. };
  6912. Tools._StartPerformanceConsole = function (counterName, condition) {
  6913. if (condition === void 0) { condition = true; }
  6914. if (!condition) {
  6915. return;
  6916. }
  6917. Tools._StartUserMark(counterName, condition);
  6918. if (console.time) {
  6919. console.time(counterName);
  6920. }
  6921. };
  6922. Tools._EndPerformanceConsole = function (counterName, condition) {
  6923. if (condition === void 0) { condition = true; }
  6924. if (!condition) {
  6925. return;
  6926. }
  6927. Tools._EndUserMark(counterName, condition);
  6928. if (console.time) {
  6929. console.timeEnd(counterName);
  6930. }
  6931. };
  6932. Object.defineProperty(Tools, "Now", {
  6933. get: function () {
  6934. if (window.performance && window.performance.now) {
  6935. return window.performance.now();
  6936. }
  6937. return new Date().getTime();
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. /**
  6943. * This method will return the name of the class used to create the instance of the given object.
  6944. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6945. * @param object the object to get the class name from
  6946. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6947. */
  6948. Tools.getClassName = function (object, isType) {
  6949. if (isType === void 0) { isType = false; }
  6950. var name = null;
  6951. if (!isType && object.getClassName) {
  6952. name = object.getClassName();
  6953. }
  6954. else {
  6955. if (object instanceof Object) {
  6956. var classObj = isType ? object : Object.getPrototypeOf(object);
  6957. name = classObj.constructor["__bjsclassName__"];
  6958. }
  6959. if (!name) {
  6960. name = typeof object;
  6961. }
  6962. }
  6963. return name;
  6964. };
  6965. Tools.first = function (array, predicate) {
  6966. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6967. var el = array_1[_i];
  6968. if (predicate(el)) {
  6969. return el;
  6970. }
  6971. }
  6972. };
  6973. /**
  6974. * This method will return the name of the full name of the class, including its owning module (if any).
  6975. * 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).
  6976. * @param object the object to get the class name from
  6977. * @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.
  6978. */
  6979. Tools.getFullClassName = function (object, isType) {
  6980. if (isType === void 0) { isType = false; }
  6981. var className = null;
  6982. var moduleName = null;
  6983. if (!isType && object.getClassName) {
  6984. className = object.getClassName();
  6985. }
  6986. else {
  6987. if (object instanceof Object) {
  6988. var classObj = isType ? object : Object.getPrototypeOf(object);
  6989. className = classObj.constructor["__bjsclassName__"];
  6990. moduleName = classObj.constructor["__bjsmoduleName__"];
  6991. }
  6992. if (!className) {
  6993. className = typeof object;
  6994. }
  6995. }
  6996. if (!className) {
  6997. return null;
  6998. }
  6999. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7000. };
  7001. /**
  7002. * 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.
  7003. * @param array
  7004. */
  7005. Tools.arrayOrStringFeeder = function (array) {
  7006. return function (index) {
  7007. if (index >= array.length) {
  7008. return null;
  7009. }
  7010. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7011. if (val && val.getHashCode) {
  7012. val = val.getHashCode();
  7013. }
  7014. if (typeof val === "string") {
  7015. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7016. }
  7017. return val;
  7018. };
  7019. };
  7020. /**
  7021. * Compute the hashCode of a stream of number
  7022. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7023. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7024. * @return the hash code computed
  7025. */
  7026. Tools.hashCodeFromStream = function (feeder) {
  7027. // Based from here: http://stackoverflow.com/a/7616484/802124
  7028. var hash = 0;
  7029. var index = 0;
  7030. var chr = feeder(index++);
  7031. while (chr != null) {
  7032. hash = ((hash << 5) - hash) + chr;
  7033. hash |= 0; // Convert to 32bit integer
  7034. chr = feeder(index++);
  7035. }
  7036. return hash;
  7037. };
  7038. return Tools;
  7039. }());
  7040. Tools.BaseUrl = "";
  7041. Tools.CorsBehavior = "anonymous";
  7042. Tools.UseFallbackTexture = true;
  7043. // Used in case of a texture loading problem
  7044. 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";
  7045. // Logs
  7046. Tools._NoneLogLevel = 0;
  7047. Tools._MessageLogLevel = 1;
  7048. Tools._WarningLogLevel = 2;
  7049. Tools._ErrorLogLevel = 4;
  7050. Tools._LogCache = "";
  7051. Tools.errorsCount = 0;
  7052. Tools.Log = Tools._LogEnabled;
  7053. Tools.Warn = Tools._WarnEnabled;
  7054. Tools.Error = Tools._ErrorEnabled;
  7055. // Performances
  7056. Tools._PerformanceNoneLogLevel = 0;
  7057. Tools._PerformanceUserMarkLogLevel = 1;
  7058. Tools._PerformanceConsoleLogLevel = 2;
  7059. Tools._performance = window.performance;
  7060. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7061. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7062. BABYLON.Tools = Tools;
  7063. /**
  7064. * This class is used to track a performance counter which is number based.
  7065. * The user has access to many properties which give statistics of different nature
  7066. *
  7067. * The implementer can track two kinds of Performance Counter: time and count
  7068. * 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.
  7069. * 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.
  7070. */
  7071. var PerfCounter = (function () {
  7072. function PerfCounter() {
  7073. this._startMonitoringTime = 0;
  7074. this._min = 0;
  7075. this._max = 0;
  7076. this._average = 0;
  7077. this._lastSecAverage = 0;
  7078. this._current = 0;
  7079. this._totalValueCount = 0;
  7080. this._totalAccumulated = 0;
  7081. this._lastSecAccumulated = 0;
  7082. this._lastSecTime = 0;
  7083. this._lastSecValueCount = 0;
  7084. }
  7085. Object.defineProperty(PerfCounter.prototype, "min", {
  7086. /**
  7087. * Returns the smallest value ever
  7088. */
  7089. get: function () {
  7090. return this._min;
  7091. },
  7092. enumerable: true,
  7093. configurable: true
  7094. });
  7095. Object.defineProperty(PerfCounter.prototype, "max", {
  7096. /**
  7097. * Returns the biggest value ever
  7098. */
  7099. get: function () {
  7100. return this._max;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(PerfCounter.prototype, "average", {
  7106. /**
  7107. * Returns the average value since the performance counter is running
  7108. */
  7109. get: function () {
  7110. return this._average;
  7111. },
  7112. enumerable: true,
  7113. configurable: true
  7114. });
  7115. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7116. /**
  7117. * Returns the average value of the last second the counter was monitored
  7118. */
  7119. get: function () {
  7120. return this._lastSecAverage;
  7121. },
  7122. enumerable: true,
  7123. configurable: true
  7124. });
  7125. Object.defineProperty(PerfCounter.prototype, "current", {
  7126. /**
  7127. * Returns the current value
  7128. */
  7129. get: function () {
  7130. return this._current;
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. Object.defineProperty(PerfCounter.prototype, "total", {
  7136. get: function () {
  7137. return this._totalAccumulated;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. /**
  7143. * Call this method to start monitoring a new frame.
  7144. * 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.
  7145. */
  7146. PerfCounter.prototype.fetchNewFrame = function () {
  7147. this._totalValueCount++;
  7148. this._current = 0;
  7149. this._lastSecValueCount++;
  7150. };
  7151. /**
  7152. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7153. * @param newCount the count value to add to the monitored count
  7154. * @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.
  7155. */
  7156. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7157. if (!PerfCounter.Enabled) {
  7158. return;
  7159. }
  7160. this._current += newCount;
  7161. if (fetchResult) {
  7162. this._fetchResult();
  7163. }
  7164. };
  7165. /**
  7166. * Start monitoring this performance counter
  7167. */
  7168. PerfCounter.prototype.beginMonitoring = function () {
  7169. if (!PerfCounter.Enabled) {
  7170. return;
  7171. }
  7172. this._startMonitoringTime = Tools.Now;
  7173. };
  7174. /**
  7175. * Compute the time lapsed since the previous beginMonitoring() call.
  7176. * @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
  7177. */
  7178. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7179. if (newFrame === void 0) { newFrame = true; }
  7180. if (!PerfCounter.Enabled) {
  7181. return;
  7182. }
  7183. if (newFrame) {
  7184. this.fetchNewFrame();
  7185. }
  7186. var currentTime = Tools.Now;
  7187. this._current = currentTime - this._startMonitoringTime;
  7188. if (newFrame) {
  7189. this._fetchResult();
  7190. }
  7191. };
  7192. PerfCounter.prototype._fetchResult = function () {
  7193. this._totalAccumulated += this._current;
  7194. this._lastSecAccumulated += this._current;
  7195. // Min/Max update
  7196. this._min = Math.min(this._min, this._current);
  7197. this._max = Math.max(this._max, this._current);
  7198. this._average = this._totalAccumulated / this._totalValueCount;
  7199. // Reset last sec?
  7200. var now = Tools.Now;
  7201. if ((now - this._lastSecTime) > 1000) {
  7202. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7203. this._lastSecTime = now;
  7204. this._lastSecAccumulated = 0;
  7205. this._lastSecValueCount = 0;
  7206. }
  7207. };
  7208. return PerfCounter;
  7209. }());
  7210. PerfCounter.Enabled = true;
  7211. BABYLON.PerfCounter = PerfCounter;
  7212. /**
  7213. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7214. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7215. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7216. * @param name The name of the class, case should be preserved
  7217. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7218. */
  7219. function className(name, module) {
  7220. return function (target) {
  7221. target["__bjsclassName__"] = name;
  7222. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7223. };
  7224. }
  7225. BABYLON.className = className;
  7226. /**
  7227. * An implementation of a loop for asynchronous functions.
  7228. */
  7229. var AsyncLoop = (function () {
  7230. /**
  7231. * Constroctor.
  7232. * @param iterations the number of iterations.
  7233. * @param _fn the function to run each iteration
  7234. * @param _successCallback the callback that will be called upon succesful execution
  7235. * @param offset starting offset.
  7236. */
  7237. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7238. if (offset === void 0) { offset = 0; }
  7239. this.iterations = iterations;
  7240. this._fn = _fn;
  7241. this._successCallback = _successCallback;
  7242. this.index = offset - 1;
  7243. this._done = false;
  7244. }
  7245. /**
  7246. * Execute the next iteration. Must be called after the last iteration was finished.
  7247. */
  7248. AsyncLoop.prototype.executeNext = function () {
  7249. if (!this._done) {
  7250. if (this.index + 1 < this.iterations) {
  7251. ++this.index;
  7252. this._fn(this);
  7253. }
  7254. else {
  7255. this.breakLoop();
  7256. }
  7257. }
  7258. };
  7259. /**
  7260. * Break the loop and run the success callback.
  7261. */
  7262. AsyncLoop.prototype.breakLoop = function () {
  7263. this._done = true;
  7264. this._successCallback();
  7265. };
  7266. /**
  7267. * Helper function
  7268. */
  7269. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7270. if (offset === void 0) { offset = 0; }
  7271. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7272. loop.executeNext();
  7273. return loop;
  7274. };
  7275. /**
  7276. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7277. * @param iterations total number of iterations
  7278. * @param syncedIterations number of synchronous iterations in each async iteration.
  7279. * @param fn the function to call each iteration.
  7280. * @param callback a success call back that will be called when iterating stops.
  7281. * @param breakFunction a break condition (optional)
  7282. * @param timeout timeout settings for the setTimeout function. default - 0.
  7283. * @constructor
  7284. */
  7285. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7286. if (timeout === void 0) { timeout = 0; }
  7287. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7288. if (breakFunction && breakFunction())
  7289. loop.breakLoop();
  7290. else {
  7291. setTimeout(function () {
  7292. for (var i = 0; i < syncedIterations; ++i) {
  7293. var iteration = (loop.index * syncedIterations) + i;
  7294. if (iteration >= iterations)
  7295. break;
  7296. fn(iteration);
  7297. if (breakFunction && breakFunction()) {
  7298. loop.breakLoop();
  7299. break;
  7300. }
  7301. }
  7302. loop.executeNext();
  7303. }, timeout);
  7304. }
  7305. }, callback);
  7306. };
  7307. return AsyncLoop;
  7308. }());
  7309. BABYLON.AsyncLoop = AsyncLoop;
  7310. })(BABYLON || (BABYLON = {}));
  7311. //# sourceMappingURL=babylon.tools.js.map
  7312. var BABYLON;
  7313. (function (BABYLON) {
  7314. var Internals;
  7315. (function (Internals) {
  7316. var _AlphaState = (function () {
  7317. /**
  7318. * Initializes the state.
  7319. */
  7320. function _AlphaState() {
  7321. this._isAlphaBlendDirty = false;
  7322. this._isBlendFunctionParametersDirty = false;
  7323. this._alphaBlend = false;
  7324. this._blendFunctionParameters = new Array(4);
  7325. this.reset();
  7326. }
  7327. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7328. get: function () {
  7329. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7335. get: function () {
  7336. return this._alphaBlend;
  7337. },
  7338. set: function (value) {
  7339. if (this._alphaBlend === value) {
  7340. return;
  7341. }
  7342. this._alphaBlend = value;
  7343. this._isAlphaBlendDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7349. if (this._blendFunctionParameters[0] === value0 &&
  7350. this._blendFunctionParameters[1] === value1 &&
  7351. this._blendFunctionParameters[2] === value2 &&
  7352. this._blendFunctionParameters[3] === value3) {
  7353. return;
  7354. }
  7355. this._blendFunctionParameters[0] = value0;
  7356. this._blendFunctionParameters[1] = value1;
  7357. this._blendFunctionParameters[2] = value2;
  7358. this._blendFunctionParameters[3] = value3;
  7359. this._isBlendFunctionParametersDirty = true;
  7360. };
  7361. _AlphaState.prototype.reset = function () {
  7362. this._alphaBlend = false;
  7363. this._blendFunctionParameters[0] = null;
  7364. this._blendFunctionParameters[1] = null;
  7365. this._blendFunctionParameters[2] = null;
  7366. this._blendFunctionParameters[3] = null;
  7367. this._isAlphaBlendDirty = true;
  7368. this._isBlendFunctionParametersDirty = false;
  7369. };
  7370. _AlphaState.prototype.apply = function (gl) {
  7371. if (!this.isDirty) {
  7372. return;
  7373. }
  7374. // Alpha blend
  7375. if (this._isAlphaBlendDirty) {
  7376. if (this._alphaBlend) {
  7377. gl.enable(gl.BLEND);
  7378. }
  7379. else {
  7380. gl.disable(gl.BLEND);
  7381. }
  7382. this._isAlphaBlendDirty = false;
  7383. }
  7384. // Alpha function
  7385. if (this._isBlendFunctionParametersDirty) {
  7386. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7387. this._isBlendFunctionParametersDirty = false;
  7388. }
  7389. };
  7390. return _AlphaState;
  7391. }());
  7392. Internals._AlphaState = _AlphaState;
  7393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7394. })(BABYLON || (BABYLON = {}));
  7395. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7396. var BABYLON;
  7397. (function (BABYLON) {
  7398. var Internals;
  7399. (function (Internals) {
  7400. var _DepthCullingState = (function () {
  7401. /**
  7402. * Initializes the state.
  7403. */
  7404. function _DepthCullingState() {
  7405. this._isDepthTestDirty = false;
  7406. this._isDepthMaskDirty = false;
  7407. this._isDepthFuncDirty = false;
  7408. this._isCullFaceDirty = false;
  7409. this._isCullDirty = false;
  7410. this._isZOffsetDirty = false;
  7411. this.reset();
  7412. }
  7413. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7414. get: function () {
  7415. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7416. },
  7417. enumerable: true,
  7418. configurable: true
  7419. });
  7420. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7421. get: function () {
  7422. return this._zOffset;
  7423. },
  7424. set: function (value) {
  7425. if (this._zOffset === value) {
  7426. return;
  7427. }
  7428. this._zOffset = value;
  7429. this._isZOffsetDirty = true;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7435. get: function () {
  7436. return this._cullFace;
  7437. },
  7438. set: function (value) {
  7439. if (this._cullFace === value) {
  7440. return;
  7441. }
  7442. this._cullFace = value;
  7443. this._isCullFaceDirty = true;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7449. get: function () {
  7450. return this._cull;
  7451. },
  7452. set: function (value) {
  7453. if (this._cull === value) {
  7454. return;
  7455. }
  7456. this._cull = value;
  7457. this._isCullDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7463. get: function () {
  7464. return this._depthFunc;
  7465. },
  7466. set: function (value) {
  7467. if (this._depthFunc === value) {
  7468. return;
  7469. }
  7470. this._depthFunc = value;
  7471. this._isDepthFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7477. get: function () {
  7478. return this._depthMask;
  7479. },
  7480. set: function (value) {
  7481. if (this._depthMask === value) {
  7482. return;
  7483. }
  7484. this._depthMask = value;
  7485. this._isDepthMaskDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7491. get: function () {
  7492. return this._depthTest;
  7493. },
  7494. set: function (value) {
  7495. if (this._depthTest === value) {
  7496. return;
  7497. }
  7498. this._depthTest = value;
  7499. this._isDepthTestDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. _DepthCullingState.prototype.reset = function () {
  7505. this._depthMask = true;
  7506. this._depthTest = true;
  7507. this._depthFunc = null;
  7508. this._cullFace = null;
  7509. this._cull = null;
  7510. this._zOffset = 0;
  7511. this._isDepthTestDirty = true;
  7512. this._isDepthMaskDirty = true;
  7513. this._isDepthFuncDirty = false;
  7514. this._isCullFaceDirty = false;
  7515. this._isCullDirty = false;
  7516. this._isZOffsetDirty = false;
  7517. };
  7518. _DepthCullingState.prototype.apply = function (gl) {
  7519. if (!this.isDirty) {
  7520. return;
  7521. }
  7522. // Cull
  7523. if (this._isCullDirty) {
  7524. if (this.cull) {
  7525. gl.enable(gl.CULL_FACE);
  7526. }
  7527. else {
  7528. gl.disable(gl.CULL_FACE);
  7529. }
  7530. this._isCullDirty = false;
  7531. }
  7532. // Cull face
  7533. if (this._isCullFaceDirty) {
  7534. gl.cullFace(this.cullFace);
  7535. this._isCullFaceDirty = false;
  7536. }
  7537. // Depth mask
  7538. if (this._isDepthMaskDirty) {
  7539. gl.depthMask(this.depthMask);
  7540. this._isDepthMaskDirty = false;
  7541. }
  7542. // Depth test
  7543. if (this._isDepthTestDirty) {
  7544. if (this.depthTest) {
  7545. gl.enable(gl.DEPTH_TEST);
  7546. }
  7547. else {
  7548. gl.disable(gl.DEPTH_TEST);
  7549. }
  7550. this._isDepthTestDirty = false;
  7551. }
  7552. // Depth func
  7553. if (this._isDepthFuncDirty) {
  7554. gl.depthFunc(this.depthFunc);
  7555. this._isDepthFuncDirty = false;
  7556. }
  7557. // zOffset
  7558. if (this._isZOffsetDirty) {
  7559. if (this.zOffset) {
  7560. gl.enable(gl.POLYGON_OFFSET_FILL);
  7561. gl.polygonOffset(this.zOffset, 0);
  7562. }
  7563. else {
  7564. gl.disable(gl.POLYGON_OFFSET_FILL);
  7565. }
  7566. this._isZOffsetDirty = false;
  7567. }
  7568. };
  7569. return _DepthCullingState;
  7570. }());
  7571. Internals._DepthCullingState = _DepthCullingState;
  7572. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7573. })(BABYLON || (BABYLON = {}));
  7574. //# sourceMappingURL=babylon.depthCullingState.js.map
  7575. var BABYLON;
  7576. (function (BABYLON) {
  7577. var Internals;
  7578. (function (Internals) {
  7579. var _StencilState = (function () {
  7580. function _StencilState() {
  7581. this._isStencilTestDirty = false;
  7582. this._isStencilMaskDirty = false;
  7583. this._isStencilFuncDirty = false;
  7584. this._isStencilOpDirty = false;
  7585. this.reset();
  7586. }
  7587. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7588. get: function () {
  7589. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7595. get: function () {
  7596. return this._stencilFunc;
  7597. },
  7598. set: function (value) {
  7599. if (this._stencilFunc === value) {
  7600. return;
  7601. }
  7602. this._stencilFunc = value;
  7603. this._isStencilFuncDirty = true;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7609. get: function () {
  7610. return this._stencilFuncRef;
  7611. },
  7612. set: function (value) {
  7613. if (this._stencilFuncRef === value) {
  7614. return;
  7615. }
  7616. this._stencilFuncRef = value;
  7617. this._isStencilFuncDirty = true;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7623. get: function () {
  7624. return this._stencilFuncMask;
  7625. },
  7626. set: function (value) {
  7627. if (this._stencilFuncMask === value) {
  7628. return;
  7629. }
  7630. this._stencilFuncMask = value;
  7631. this._isStencilFuncDirty = true;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7637. get: function () {
  7638. return this._stencilOpStencilFail;
  7639. },
  7640. set: function (value) {
  7641. if (this._stencilOpStencilFail === value) {
  7642. return;
  7643. }
  7644. this._stencilOpStencilFail = value;
  7645. this._isStencilOpDirty = true;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7651. get: function () {
  7652. return this._stencilOpDepthFail;
  7653. },
  7654. set: function (value) {
  7655. if (this._stencilOpDepthFail === value) {
  7656. return;
  7657. }
  7658. this._stencilOpDepthFail = value;
  7659. this._isStencilOpDirty = true;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7665. get: function () {
  7666. return this._stencilOpStencilDepthPass;
  7667. },
  7668. set: function (value) {
  7669. if (this._stencilOpStencilDepthPass === value) {
  7670. return;
  7671. }
  7672. this._stencilOpStencilDepthPass = value;
  7673. this._isStencilOpDirty = true;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7679. get: function () {
  7680. return this._stencilMask;
  7681. },
  7682. set: function (value) {
  7683. if (this._stencilMask === value) {
  7684. return;
  7685. }
  7686. this._stencilMask = value;
  7687. this._isStencilMaskDirty = true;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7693. get: function () {
  7694. return this._stencilTest;
  7695. },
  7696. set: function (value) {
  7697. if (this._stencilTest === value) {
  7698. return;
  7699. }
  7700. this._stencilTest = value;
  7701. this._isStencilTestDirty = true;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. _StencilState.prototype.reset = function () {
  7707. this._stencilTest = false;
  7708. this._stencilMask = 0xFF;
  7709. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7710. this._stencilFuncRef = 1;
  7711. this._stencilFuncMask = 0xFF;
  7712. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7713. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7714. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7715. this._isStencilTestDirty = true;
  7716. this._isStencilMaskDirty = true;
  7717. this._isStencilFuncDirty = true;
  7718. this._isStencilOpDirty = true;
  7719. };
  7720. _StencilState.prototype.apply = function (gl) {
  7721. if (!this.isDirty) {
  7722. return;
  7723. }
  7724. // Stencil test
  7725. if (this._isStencilTestDirty) {
  7726. if (this.stencilTest) {
  7727. gl.enable(gl.STENCIL_TEST);
  7728. }
  7729. else {
  7730. gl.disable(gl.STENCIL_TEST);
  7731. }
  7732. this._isStencilTestDirty = false;
  7733. }
  7734. // Stencil mask
  7735. if (this._isStencilMaskDirty) {
  7736. gl.stencilMask(this.stencilMask);
  7737. this._isStencilMaskDirty = false;
  7738. }
  7739. // Stencil func
  7740. if (this._isStencilFuncDirty) {
  7741. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7742. this._isStencilFuncDirty = false;
  7743. }
  7744. // Stencil op
  7745. if (this._isStencilOpDirty) {
  7746. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7747. this._isStencilOpDirty = false;
  7748. }
  7749. };
  7750. return _StencilState;
  7751. }());
  7752. Internals._StencilState = _StencilState;
  7753. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7754. })(BABYLON || (BABYLON = {}));
  7755. //# sourceMappingURL=babylon.stencilState.js.map
  7756. var BABYLON;
  7757. (function (BABYLON) {
  7758. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7759. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7760. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7761. gl.compileShader(shader);
  7762. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7763. throw new Error(gl.getShaderInfoLog(shader));
  7764. }
  7765. return shader;
  7766. };
  7767. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7768. var magFilter = gl.NEAREST;
  7769. var minFilter = gl.NEAREST;
  7770. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7771. magFilter = gl.LINEAR;
  7772. if (generateMipMaps) {
  7773. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7774. }
  7775. else {
  7776. minFilter = gl.LINEAR;
  7777. }
  7778. }
  7779. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7780. magFilter = gl.LINEAR;
  7781. if (generateMipMaps) {
  7782. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7783. }
  7784. else {
  7785. minFilter = gl.LINEAR;
  7786. }
  7787. }
  7788. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7789. magFilter = gl.NEAREST;
  7790. if (generateMipMaps) {
  7791. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7792. }
  7793. else {
  7794. minFilter = gl.NEAREST;
  7795. }
  7796. }
  7797. return {
  7798. min: minFilter,
  7799. mag: magFilter
  7800. };
  7801. };
  7802. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7804. var engine = scene.getEngine();
  7805. if (!engine) {
  7806. return;
  7807. }
  7808. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7809. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7810. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7811. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7812. texture._baseWidth = width;
  7813. texture._baseHeight = height;
  7814. texture._width = potWidth;
  7815. texture._height = potHeight;
  7816. texture.isReady = true;
  7817. processFunction(potWidth, potHeight);
  7818. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7820. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7821. if (!noMipmap && !isCompressed) {
  7822. gl.generateMipmap(gl.TEXTURE_2D);
  7823. }
  7824. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7825. engine.resetTextureCache();
  7826. scene._removePendingData(texture);
  7827. texture.onLoadedCallbacks.forEach(function (callback) {
  7828. callback();
  7829. });
  7830. texture.onLoadedCallbacks = [];
  7831. };
  7832. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7833. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7834. var img;
  7835. var onload = function () {
  7836. loadedImages[index] = img;
  7837. loadedImages._internalCount++;
  7838. scene._removePendingData(img);
  7839. if (loadedImages._internalCount === 6) {
  7840. onfinish(loadedImages);
  7841. }
  7842. };
  7843. var onerror = function () {
  7844. scene._removePendingData(img);
  7845. if (onErrorCallBack) {
  7846. onErrorCallBack();
  7847. }
  7848. };
  7849. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7850. scene._addPendingData(img);
  7851. };
  7852. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7853. if (onError === void 0) { onError = null; }
  7854. var loadedImages = [];
  7855. loadedImages._internalCount = 0;
  7856. for (var index = 0; index < 6; index++) {
  7857. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7858. }
  7859. };
  7860. var InstancingAttributeInfo = (function () {
  7861. function InstancingAttributeInfo() {
  7862. }
  7863. return InstancingAttributeInfo;
  7864. }());
  7865. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7866. var EngineCapabilities = (function () {
  7867. function EngineCapabilities() {
  7868. }
  7869. return EngineCapabilities;
  7870. }());
  7871. BABYLON.EngineCapabilities = EngineCapabilities;
  7872. /**
  7873. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7874. */
  7875. var Engine = (function () {
  7876. /**
  7877. * @constructor
  7878. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7879. * @param {boolean} [antialias] - enable antialias
  7880. * @param options - further options to be sent to the getContext function
  7881. */
  7882. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7883. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7884. var _this = this;
  7885. // Public members
  7886. this.isFullscreen = false;
  7887. this.isPointerLock = false;
  7888. this.cullBackFaces = true;
  7889. this.renderEvenInBackground = true;
  7890. this.preventCacheWipeBetweenFrames = false;
  7891. // To enable/disable IDB support and avoid XHR on .manifest
  7892. this.enableOfflineSupport = true;
  7893. this.scenes = new Array();
  7894. this._windowIsBackground = false;
  7895. this._webGLVersion = 1.0;
  7896. this._badOS = false;
  7897. this._drawCalls = new BABYLON.PerfCounter();
  7898. this._renderingQueueLaunched = false;
  7899. this._activeRenderLoops = [];
  7900. // FPS
  7901. this.fpsRange = 60;
  7902. this.previousFramesDuration = [];
  7903. this.fps = 60;
  7904. this.deltaTime = 0;
  7905. // States
  7906. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7907. this._stencilState = new BABYLON.Internals._StencilState();
  7908. this._alphaState = new BABYLON.Internals._AlphaState();
  7909. this._alphaMode = Engine.ALPHA_DISABLE;
  7910. // Cache
  7911. this._loadedTexturesCache = new Array();
  7912. this._maxTextureChannels = 16;
  7913. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7914. this._compiledEffects = {};
  7915. this._vertexAttribArraysEnabled = [];
  7916. this._uintIndicesCurrentlySet = false;
  7917. this._currentBoundBuffer = new Array();
  7918. this._currentBufferPointers = [];
  7919. this._currentInstanceLocations = new Array();
  7920. this._currentInstanceBuffers = new Array();
  7921. this._vaoRecordInProgress = false;
  7922. this._mustWipeVertexAttributes = false;
  7923. // Hardware supported Compressed Textures
  7924. this._texturesSupported = new Array();
  7925. this._onVRFullScreenTriggered = function () {
  7926. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7927. //get the old size before we change
  7928. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7929. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7930. //get the width and height, change the render size
  7931. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7932. var width, height;
  7933. _this.setHardwareScalingLevel(1);
  7934. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7935. }
  7936. else {
  7937. //When the specs are implemented, need to uncomment this.
  7938. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7939. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7940. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7941. _this._vrDisplayEnabled = undefined;
  7942. }
  7943. };
  7944. this._renderingCanvas = canvas;
  7945. Engine.Instances.push(this);
  7946. this._externalData = new BABYLON.StringDictionary();
  7947. options = options || {};
  7948. if (antialias != null) {
  7949. options.antialias = antialias;
  7950. }
  7951. if (options.preserveDrawingBuffer === undefined) {
  7952. options.preserveDrawingBuffer = false;
  7953. }
  7954. if (options.audioEngine === undefined) {
  7955. options.audioEngine = true;
  7956. }
  7957. if (options.stencil === undefined) {
  7958. options.stencil = true;
  7959. }
  7960. // GL
  7961. if (!options.disableWebGL2Support) {
  7962. try {
  7963. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7964. if (this._gl) {
  7965. this._webGLVersion = 2.0;
  7966. }
  7967. }
  7968. catch (e) {
  7969. }
  7970. }
  7971. if (!this._gl) {
  7972. if (!canvas) {
  7973. throw new Error("The provided canvas is null or undefined.");
  7974. }
  7975. try {
  7976. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7977. }
  7978. catch (e) {
  7979. throw new Error("WebGL not supported");
  7980. }
  7981. }
  7982. if (!this._gl) {
  7983. throw new Error("WebGL not supported");
  7984. }
  7985. this._onBlur = function () {
  7986. _this._windowIsBackground = true;
  7987. };
  7988. this._onFocus = function () {
  7989. _this._windowIsBackground = false;
  7990. };
  7991. window.addEventListener("blur", this._onBlur);
  7992. window.addEventListener("focus", this._onFocus);
  7993. // Viewport
  7994. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7995. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7996. this.resize();
  7997. // Caps
  7998. this._isStencilEnable = options.stencil;
  7999. this._caps = new EngineCapabilities();
  8000. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8001. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8002. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8003. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8004. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8005. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8006. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8007. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8008. // Infos
  8009. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8010. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8011. if (rendererInfo != null) {
  8012. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8013. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8014. }
  8015. if (!this._glVendor) {
  8016. this._glVendor = "Unknown vendor";
  8017. }
  8018. if (!this._glRenderer) {
  8019. this._glRenderer = "Unknown renderer";
  8020. }
  8021. // Extensions
  8022. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8023. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8024. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8025. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8026. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8027. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8028. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8029. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  8030. 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');
  8031. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8032. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8033. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8034. this._caps.highPrecisionShaderSupported = true;
  8035. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8036. // Checks if some of the format renders first to allow the use of webgl inspector.
  8037. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8038. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8039. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8040. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8041. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8042. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8043. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8044. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8045. // Vertex array object
  8046. if (this._webGLVersion > 1) {
  8047. this._caps.vertexArrayObject = true;
  8048. }
  8049. else {
  8050. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8051. if (vertexArrayObjectExtension != null) {
  8052. this._caps.vertexArrayObject = true;
  8053. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8054. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8055. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8056. }
  8057. else {
  8058. this._caps.vertexArrayObject = false;
  8059. }
  8060. }
  8061. // Instances count
  8062. if (this._webGLVersion > 1) {
  8063. this._caps.instancedArrays = true;
  8064. }
  8065. else {
  8066. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8067. if (instanceExtension != null) {
  8068. this._caps.instancedArrays = true;
  8069. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8070. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8071. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8072. }
  8073. else {
  8074. this._caps.instancedArrays = false;
  8075. }
  8076. }
  8077. // Intelligently add supported compressed formats in order to check for.
  8078. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8079. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8080. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8081. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8082. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  8083. if (this._caps.astc)
  8084. this.texturesSupported.push('-astc.ktx');
  8085. if (this._caps.s3tc)
  8086. this.texturesSupported.push('-dxt.ktx');
  8087. if (this._caps.pvrtc)
  8088. this.texturesSupported.push('-pvrtc.ktx');
  8089. if (this._caps.etc2)
  8090. this.texturesSupported.push('-etc2.ktx');
  8091. if (this._caps.atc)
  8092. this.texturesSupported.push('-atc.ktx');
  8093. if (this._caps.etc1)
  8094. this.texturesSupported.push('-etc1.ktx');
  8095. if (this._gl.getShaderPrecisionFormat) {
  8096. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8097. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8098. }
  8099. // Depth buffer
  8100. this.setDepthBuffer(true);
  8101. this.setDepthFunctionToLessOrEqual();
  8102. this.setDepthWrite(true);
  8103. // Fullscreen
  8104. this._onFullscreenChange = function () {
  8105. if (document.fullscreen !== undefined) {
  8106. _this.isFullscreen = document.fullscreen;
  8107. }
  8108. else if (document.mozFullScreen !== undefined) {
  8109. _this.isFullscreen = document.mozFullScreen;
  8110. }
  8111. else if (document.webkitIsFullScreen !== undefined) {
  8112. _this.isFullscreen = document.webkitIsFullScreen;
  8113. }
  8114. else if (document.msIsFullScreen !== undefined) {
  8115. _this.isFullscreen = document.msIsFullScreen;
  8116. }
  8117. // Pointer lock
  8118. if (_this.isFullscreen && _this._pointerLockRequested) {
  8119. canvas.requestPointerLock = canvas.requestPointerLock ||
  8120. canvas.msRequestPointerLock ||
  8121. canvas.mozRequestPointerLock ||
  8122. canvas.webkitRequestPointerLock;
  8123. if (canvas.requestPointerLock) {
  8124. canvas.requestPointerLock();
  8125. }
  8126. }
  8127. };
  8128. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8129. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8130. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8131. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8132. // Pointer lock
  8133. this._onPointerLockChange = function () {
  8134. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8135. document.webkitPointerLockElement === canvas ||
  8136. document.msPointerLockElement === canvas ||
  8137. document.pointerLockElement === canvas);
  8138. };
  8139. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8140. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8141. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8142. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8143. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8144. Engine.audioEngine = new BABYLON.AudioEngine();
  8145. }
  8146. //default loading screen
  8147. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8148. //Load WebVR Devices
  8149. if (options.autoEnableWebVR) {
  8150. this.initWebVR();
  8151. }
  8152. //Detect if we are running on a faulty buggy OS.
  8153. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8154. //ua sniffing is the tool of the devil.
  8155. this._badOS = regexp.test(navigator.userAgent);
  8156. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8157. }
  8158. Object.defineProperty(Engine, "LastCreatedEngine", {
  8159. get: function () {
  8160. if (Engine.Instances.length === 0) {
  8161. return null;
  8162. }
  8163. return Engine.Instances[Engine.Instances.length - 1];
  8164. },
  8165. enumerable: true,
  8166. configurable: true
  8167. });
  8168. Object.defineProperty(Engine, "LastCreatedScene", {
  8169. get: function () {
  8170. var lastCreatedEngine = Engine.LastCreatedEngine;
  8171. if (!lastCreatedEngine) {
  8172. return null;
  8173. }
  8174. if (lastCreatedEngine.scenes.length === 0) {
  8175. return null;
  8176. }
  8177. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8178. },
  8179. enumerable: true,
  8180. configurable: true
  8181. });
  8182. Object.defineProperty(Engine, "NEVER", {
  8183. get: function () {
  8184. return Engine._NEVER;
  8185. },
  8186. enumerable: true,
  8187. configurable: true
  8188. });
  8189. Object.defineProperty(Engine, "ALWAYS", {
  8190. get: function () {
  8191. return Engine._ALWAYS;
  8192. },
  8193. enumerable: true,
  8194. configurable: true
  8195. });
  8196. Object.defineProperty(Engine, "LESS", {
  8197. get: function () {
  8198. return Engine._LESS;
  8199. },
  8200. enumerable: true,
  8201. configurable: true
  8202. });
  8203. Object.defineProperty(Engine, "EQUAL", {
  8204. get: function () {
  8205. return Engine._EQUAL;
  8206. },
  8207. enumerable: true,
  8208. configurable: true
  8209. });
  8210. Object.defineProperty(Engine, "LEQUAL", {
  8211. get: function () {
  8212. return Engine._LEQUAL;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(Engine, "GREATER", {
  8218. get: function () {
  8219. return Engine._GREATER;
  8220. },
  8221. enumerable: true,
  8222. configurable: true
  8223. });
  8224. Object.defineProperty(Engine, "GEQUAL", {
  8225. get: function () {
  8226. return Engine._GEQUAL;
  8227. },
  8228. enumerable: true,
  8229. configurable: true
  8230. });
  8231. Object.defineProperty(Engine, "NOTEQUAL", {
  8232. get: function () {
  8233. return Engine._NOTEQUAL;
  8234. },
  8235. enumerable: true,
  8236. configurable: true
  8237. });
  8238. Object.defineProperty(Engine, "KEEP", {
  8239. get: function () {
  8240. return Engine._KEEP;
  8241. },
  8242. enumerable: true,
  8243. configurable: true
  8244. });
  8245. Object.defineProperty(Engine, "REPLACE", {
  8246. get: function () {
  8247. return Engine._REPLACE;
  8248. },
  8249. enumerable: true,
  8250. configurable: true
  8251. });
  8252. Object.defineProperty(Engine, "INCR", {
  8253. get: function () {
  8254. return Engine._INCR;
  8255. },
  8256. enumerable: true,
  8257. configurable: true
  8258. });
  8259. Object.defineProperty(Engine, "DECR", {
  8260. get: function () {
  8261. return Engine._DECR;
  8262. },
  8263. enumerable: true,
  8264. configurable: true
  8265. });
  8266. Object.defineProperty(Engine, "INVERT", {
  8267. get: function () {
  8268. return Engine._INVERT;
  8269. },
  8270. enumerable: true,
  8271. configurable: true
  8272. });
  8273. Object.defineProperty(Engine, "INCR_WRAP", {
  8274. get: function () {
  8275. return Engine._INCR_WRAP;
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. Object.defineProperty(Engine, "DECR_WRAP", {
  8281. get: function () {
  8282. return Engine._DECR_WRAP;
  8283. },
  8284. enumerable: true,
  8285. configurable: true
  8286. });
  8287. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8288. get: function () {
  8289. return Engine._ALPHA_DISABLE;
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8295. get: function () {
  8296. return Engine._ALPHA_ONEONE;
  8297. },
  8298. enumerable: true,
  8299. configurable: true
  8300. });
  8301. Object.defineProperty(Engine, "ALPHA_ADD", {
  8302. get: function () {
  8303. return Engine._ALPHA_ADD;
  8304. },
  8305. enumerable: true,
  8306. configurable: true
  8307. });
  8308. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8309. get: function () {
  8310. return Engine._ALPHA_COMBINE;
  8311. },
  8312. enumerable: true,
  8313. configurable: true
  8314. });
  8315. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8316. get: function () {
  8317. return Engine._ALPHA_SUBTRACT;
  8318. },
  8319. enumerable: true,
  8320. configurable: true
  8321. });
  8322. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8323. get: function () {
  8324. return Engine._ALPHA_MULTIPLY;
  8325. },
  8326. enumerable: true,
  8327. configurable: true
  8328. });
  8329. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8330. get: function () {
  8331. return Engine._ALPHA_MAXIMIZED;
  8332. },
  8333. enumerable: true,
  8334. configurable: true
  8335. });
  8336. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8337. get: function () {
  8338. return Engine._ALPHA_PREMULTIPLIED;
  8339. },
  8340. enumerable: true,
  8341. configurable: true
  8342. });
  8343. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8344. get: function () {
  8345. return Engine._DELAYLOADSTATE_NONE;
  8346. },
  8347. enumerable: true,
  8348. configurable: true
  8349. });
  8350. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8351. get: function () {
  8352. return Engine._DELAYLOADSTATE_LOADED;
  8353. },
  8354. enumerable: true,
  8355. configurable: true
  8356. });
  8357. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8358. get: function () {
  8359. return Engine._DELAYLOADSTATE_LOADING;
  8360. },
  8361. enumerable: true,
  8362. configurable: true
  8363. });
  8364. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8365. get: function () {
  8366. return Engine._DELAYLOADSTATE_NOTLOADED;
  8367. },
  8368. enumerable: true,
  8369. configurable: true
  8370. });
  8371. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8372. get: function () {
  8373. return Engine._TEXTUREFORMAT_ALPHA;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8379. get: function () {
  8380. return Engine._TEXTUREFORMAT_LUMINANCE;
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8386. get: function () {
  8387. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8388. },
  8389. enumerable: true,
  8390. configurable: true
  8391. });
  8392. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8393. get: function () {
  8394. return Engine._TEXTUREFORMAT_RGB;
  8395. },
  8396. enumerable: true,
  8397. configurable: true
  8398. });
  8399. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8400. get: function () {
  8401. return Engine._TEXTUREFORMAT_RGBA;
  8402. },
  8403. enumerable: true,
  8404. configurable: true
  8405. });
  8406. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8407. get: function () {
  8408. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8409. },
  8410. enumerable: true,
  8411. configurable: true
  8412. });
  8413. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8414. get: function () {
  8415. return Engine._TEXTURETYPE_FLOAT;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8421. get: function () {
  8422. return Engine._TEXTURETYPE_HALF_FLOAT;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(Engine, "Version", {
  8428. get: function () {
  8429. return "3.0-alpha";
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8435. get: function () {
  8436. return this._texturesSupported;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8442. get: function () {
  8443. return this._textureFormatInUse;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8449. get: function () {
  8450. return this._webGLVersion;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8456. /**
  8457. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8458. */
  8459. get: function () {
  8460. return this._isStencilEnable;
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Engine.prototype._prepareWorkingCanvas = function () {
  8466. if (this._workingCanvas) {
  8467. return;
  8468. }
  8469. this._workingCanvas = document.createElement("canvas");
  8470. this._workingContext = this._workingCanvas.getContext("2d");
  8471. };
  8472. Engine.prototype.resetTextureCache = function () {
  8473. for (var index = 0; index < this._maxTextureChannels; index++) {
  8474. this._activeTexturesCache[index] = null;
  8475. }
  8476. };
  8477. Engine.prototype.getGlInfo = function () {
  8478. return {
  8479. vendor: this._glVendor,
  8480. renderer: this._glRenderer,
  8481. version: this._glVersion
  8482. };
  8483. };
  8484. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8485. if (useScreen === void 0) { useScreen = false; }
  8486. var viewport = camera.viewport;
  8487. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8488. };
  8489. Engine.prototype.getRenderWidth = function (useScreen) {
  8490. if (useScreen === void 0) { useScreen = false; }
  8491. if (!useScreen && this._currentRenderTarget) {
  8492. return this._currentRenderTarget._width;
  8493. }
  8494. return this._renderingCanvas.width;
  8495. };
  8496. Engine.prototype.getRenderHeight = function (useScreen) {
  8497. if (useScreen === void 0) { useScreen = false; }
  8498. if (!useScreen && this._currentRenderTarget) {
  8499. return this._currentRenderTarget._height;
  8500. }
  8501. return this._renderingCanvas.height;
  8502. };
  8503. Engine.prototype.getRenderingCanvas = function () {
  8504. return this._renderingCanvas;
  8505. };
  8506. Engine.prototype.getRenderingCanvasClientRect = function () {
  8507. return this._renderingCanvas.getBoundingClientRect();
  8508. };
  8509. Engine.prototype.setHardwareScalingLevel = function (level) {
  8510. this._hardwareScalingLevel = level;
  8511. this.resize();
  8512. };
  8513. Engine.prototype.getHardwareScalingLevel = function () {
  8514. return this._hardwareScalingLevel;
  8515. };
  8516. Engine.prototype.getLoadedTexturesCache = function () {
  8517. return this._loadedTexturesCache;
  8518. };
  8519. Engine.prototype.getCaps = function () {
  8520. return this._caps;
  8521. };
  8522. Object.defineProperty(Engine.prototype, "drawCalls", {
  8523. get: function () {
  8524. return this._drawCalls.current;
  8525. },
  8526. enumerable: true,
  8527. configurable: true
  8528. });
  8529. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8530. get: function () {
  8531. return this._drawCalls;
  8532. },
  8533. enumerable: true,
  8534. configurable: true
  8535. });
  8536. Engine.prototype.getDepthFunction = function () {
  8537. return this._depthCullingState.depthFunc;
  8538. };
  8539. Engine.prototype.setDepthFunction = function (depthFunc) {
  8540. this._depthCullingState.depthFunc = depthFunc;
  8541. };
  8542. Engine.prototype.setDepthFunctionToGreater = function () {
  8543. this._depthCullingState.depthFunc = this._gl.GREATER;
  8544. };
  8545. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8546. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8547. };
  8548. Engine.prototype.setDepthFunctionToLess = function () {
  8549. this._depthCullingState.depthFunc = this._gl.LESS;
  8550. };
  8551. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8552. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8553. };
  8554. Engine.prototype.getStencilBuffer = function () {
  8555. return this._stencilState.stencilTest;
  8556. };
  8557. Engine.prototype.setStencilBuffer = function (enable) {
  8558. this._stencilState.stencilTest = enable;
  8559. };
  8560. Engine.prototype.getStencilMask = function () {
  8561. return this._stencilState.stencilMask;
  8562. };
  8563. Engine.prototype.setStencilMask = function (mask) {
  8564. this._stencilState.stencilMask = mask;
  8565. };
  8566. Engine.prototype.getStencilFunction = function () {
  8567. return this._stencilState.stencilFunc;
  8568. };
  8569. Engine.prototype.getStencilFunctionReference = function () {
  8570. return this._stencilState.stencilFuncRef;
  8571. };
  8572. Engine.prototype.getStencilFunctionMask = function () {
  8573. return this._stencilState.stencilFuncMask;
  8574. };
  8575. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8576. this._stencilState.stencilFunc = stencilFunc;
  8577. };
  8578. Engine.prototype.setStencilFunctionReference = function (reference) {
  8579. this._stencilState.stencilFuncRef = reference;
  8580. };
  8581. Engine.prototype.setStencilFunctionMask = function (mask) {
  8582. this._stencilState.stencilFuncMask = mask;
  8583. };
  8584. Engine.prototype.getStencilOperationFail = function () {
  8585. return this._stencilState.stencilOpStencilFail;
  8586. };
  8587. Engine.prototype.getStencilOperationDepthFail = function () {
  8588. return this._stencilState.stencilOpDepthFail;
  8589. };
  8590. Engine.prototype.getStencilOperationPass = function () {
  8591. return this._stencilState.stencilOpStencilDepthPass;
  8592. };
  8593. Engine.prototype.setStencilOperationFail = function (operation) {
  8594. this._stencilState.stencilOpStencilFail = operation;
  8595. };
  8596. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8597. this._stencilState.stencilOpDepthFail = operation;
  8598. };
  8599. Engine.prototype.setStencilOperationPass = function (operation) {
  8600. this._stencilState.stencilOpStencilDepthPass = operation;
  8601. };
  8602. /**
  8603. * stop executing a render loop function and remove it from the execution array
  8604. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8605. */
  8606. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8607. if (!renderFunction) {
  8608. this._activeRenderLoops = [];
  8609. return;
  8610. }
  8611. var index = this._activeRenderLoops.indexOf(renderFunction);
  8612. if (index >= 0) {
  8613. this._activeRenderLoops.splice(index, 1);
  8614. }
  8615. };
  8616. Engine.prototype._renderLoop = function () {
  8617. var shouldRender = true;
  8618. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8619. shouldRender = false;
  8620. }
  8621. if (shouldRender) {
  8622. // Start new frame
  8623. this.beginFrame();
  8624. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8625. var renderFunction = this._activeRenderLoops[index];
  8626. renderFunction();
  8627. }
  8628. // Present
  8629. this.endFrame();
  8630. }
  8631. if (this._activeRenderLoops.length > 0) {
  8632. // Register new frame
  8633. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8634. }
  8635. else {
  8636. this._renderingQueueLaunched = false;
  8637. }
  8638. };
  8639. /**
  8640. * Register and execute a render loop. The engine can have more than one render function.
  8641. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8642. * @example
  8643. * engine.runRenderLoop(function () {
  8644. * scene.render()
  8645. * })
  8646. */
  8647. Engine.prototype.runRenderLoop = function (renderFunction) {
  8648. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8649. return;
  8650. }
  8651. this._activeRenderLoops.push(renderFunction);
  8652. if (!this._renderingQueueLaunched) {
  8653. this._renderingQueueLaunched = true;
  8654. this._bindedRenderFunction = this._renderLoop.bind(this);
  8655. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8656. }
  8657. };
  8658. /**
  8659. * Toggle full screen mode.
  8660. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8661. * @param {any} options - an options object to be sent to the requestFullscreen function
  8662. */
  8663. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8664. if (this.isFullscreen) {
  8665. BABYLON.Tools.ExitFullscreen();
  8666. }
  8667. else {
  8668. this._pointerLockRequested = requestPointerLock;
  8669. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8670. }
  8671. };
  8672. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8673. if (stencil === void 0) { stencil = false; }
  8674. this.applyStates();
  8675. var mode = 0;
  8676. if (backBuffer && color) {
  8677. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8678. mode |= this._gl.COLOR_BUFFER_BIT;
  8679. }
  8680. if (depth) {
  8681. this._gl.clearDepth(1.0);
  8682. mode |= this._gl.DEPTH_BUFFER_BIT;
  8683. }
  8684. if (stencil) {
  8685. this._gl.clearStencil(0);
  8686. mode |= this._gl.STENCIL_BUFFER_BIT;
  8687. }
  8688. this._gl.clear(mode);
  8689. };
  8690. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8691. var gl = this._gl;
  8692. // Save state
  8693. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8694. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8695. // Change state
  8696. gl.enable(gl.SCISSOR_TEST);
  8697. gl.scissor(x, y, width, height);
  8698. // Clear
  8699. this.clear(clearColor, true, true, true);
  8700. // Restore state
  8701. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8702. if (curScissor === true) {
  8703. gl.enable(gl.SCISSOR_TEST);
  8704. }
  8705. else {
  8706. gl.disable(gl.SCISSOR_TEST);
  8707. }
  8708. };
  8709. /**
  8710. * Set the WebGL's viewport
  8711. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8712. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8713. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8714. */
  8715. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8716. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8717. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8718. var x = viewport.x || 0;
  8719. var y = viewport.y || 0;
  8720. this._cachedViewport = viewport;
  8721. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8722. };
  8723. /**
  8724. * Directly set the WebGL Viewport
  8725. * The x, y, width & height are directly passed to the WebGL call
  8726. * @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.
  8727. */
  8728. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8729. var currentViewport = this._cachedViewport;
  8730. this._cachedViewport = null;
  8731. this._gl.viewport(x, y, width, height);
  8732. return currentViewport;
  8733. };
  8734. Engine.prototype.beginFrame = function () {
  8735. this._measureFps();
  8736. };
  8737. Engine.prototype.endFrame = function () {
  8738. //force a flush in case we are using a bad OS.
  8739. if (this._badOS) {
  8740. this.flushFramebuffer();
  8741. }
  8742. //submit frame to the vr device, if enabled
  8743. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8744. this._vrDisplayEnabled.submitFrame();
  8745. }
  8746. };
  8747. /**
  8748. * resize the view according to the canvas' size.
  8749. * @example
  8750. * window.addEventListener("resize", function () {
  8751. * engine.resize();
  8752. * });
  8753. */
  8754. Engine.prototype.resize = function () {
  8755. // We're not resizing the size of the canvas while in VR mode & presenting
  8756. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8757. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8758. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8759. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8760. }
  8761. };
  8762. /**
  8763. * force a specific size of the canvas
  8764. * @param {number} width - the new canvas' width
  8765. * @param {number} height - the new canvas' height
  8766. */
  8767. Engine.prototype.setSize = function (width, height) {
  8768. this._renderingCanvas.width = width;
  8769. this._renderingCanvas.height = height;
  8770. for (var index = 0; index < this.scenes.length; index++) {
  8771. var scene = this.scenes[index];
  8772. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8773. var cam = scene.cameras[camIndex];
  8774. cam._currentRenderId = 0;
  8775. }
  8776. }
  8777. };
  8778. //WebVR functions
  8779. Engine.prototype.initWebVR = function () {
  8780. if (!this.vrDisplaysPromise) {
  8781. this._getVRDisplays();
  8782. }
  8783. };
  8784. Engine.prototype.enableVR = function (vrDevice) {
  8785. this._vrDisplayEnabled = vrDevice;
  8786. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8787. };
  8788. Engine.prototype.disableVR = function () {
  8789. if (this._vrDisplayEnabled) {
  8790. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8791. }
  8792. };
  8793. Engine.prototype._getVRDisplays = function () {
  8794. var _this = this;
  8795. var getWebVRDevices = function (devices) {
  8796. var size = devices.length;
  8797. var i = 0;
  8798. _this._vrDisplays = devices.filter(function (device) {
  8799. return devices[i] instanceof VRDisplay;
  8800. });
  8801. return _this._vrDisplays;
  8802. };
  8803. //using a key due to typescript
  8804. if (navigator.getVRDisplays) {
  8805. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8806. }
  8807. };
  8808. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8809. this._currentRenderTarget = texture;
  8810. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8811. var gl = this._gl;
  8812. if (texture.isCube) {
  8813. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8814. }
  8815. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8816. this.wipeCaches();
  8817. };
  8818. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8819. if (this._currentFramebuffer !== framebuffer) {
  8820. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8821. this._currentFramebuffer = framebuffer;
  8822. }
  8823. };
  8824. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8825. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8826. this._currentRenderTarget = null;
  8827. // If MSAA, we need to bitblt back to main texture
  8828. var gl = this._gl;
  8829. if (texture._MSAAFramebuffer) {
  8830. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8831. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8832. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8833. }
  8834. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8835. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8836. gl.generateMipmap(gl.TEXTURE_2D);
  8837. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8838. }
  8839. if (onBeforeUnbind) {
  8840. if (texture._MSAAFramebuffer) {
  8841. // Bind the correct framebuffer
  8842. this.bindUnboundFramebuffer(texture._framebuffer);
  8843. }
  8844. onBeforeUnbind();
  8845. }
  8846. this.bindUnboundFramebuffer(null);
  8847. };
  8848. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8849. if (texture.generateMipMaps) {
  8850. var gl = this._gl;
  8851. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8852. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8853. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8854. }
  8855. };
  8856. Engine.prototype.flushFramebuffer = function () {
  8857. this._gl.flush();
  8858. };
  8859. Engine.prototype.restoreDefaultFramebuffer = function () {
  8860. this._currentRenderTarget = null;
  8861. this.bindUnboundFramebuffer(null);
  8862. this.setViewport(this._cachedViewport);
  8863. this.wipeCaches();
  8864. };
  8865. // VBOs
  8866. Engine.prototype._resetVertexBufferBinding = function () {
  8867. this.bindArrayBuffer(null);
  8868. this._cachedVertexBuffers = null;
  8869. };
  8870. Engine.prototype.createVertexBuffer = function (vertices) {
  8871. var vbo = this._gl.createBuffer();
  8872. this.bindArrayBuffer(vbo);
  8873. if (vertices instanceof Float32Array) {
  8874. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8875. }
  8876. else {
  8877. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8878. }
  8879. this._resetVertexBufferBinding();
  8880. vbo.references = 1;
  8881. return vbo;
  8882. };
  8883. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8884. var vbo = this._gl.createBuffer();
  8885. this.bindArrayBuffer(vbo);
  8886. if (vertices instanceof Float32Array) {
  8887. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8888. }
  8889. else {
  8890. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8891. }
  8892. this._resetVertexBufferBinding();
  8893. vbo.references = 1;
  8894. return vbo;
  8895. };
  8896. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8897. this.bindArrayBuffer(vertexBuffer);
  8898. if (offset === undefined) {
  8899. offset = 0;
  8900. }
  8901. if (count === undefined) {
  8902. if (vertices instanceof Float32Array) {
  8903. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8904. }
  8905. else {
  8906. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8907. }
  8908. }
  8909. else {
  8910. if (vertices instanceof Float32Array) {
  8911. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8912. }
  8913. else {
  8914. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8915. }
  8916. }
  8917. this._resetVertexBufferBinding();
  8918. };
  8919. Engine.prototype._resetIndexBufferBinding = function () {
  8920. this.bindIndexBuffer(null);
  8921. this._cachedIndexBuffer = null;
  8922. };
  8923. Engine.prototype.createIndexBuffer = function (indices) {
  8924. var vbo = this._gl.createBuffer();
  8925. this.bindIndexBuffer(vbo);
  8926. // Check for 32 bits indices
  8927. var arrayBuffer;
  8928. var need32Bits = false;
  8929. if (indices instanceof Uint16Array) {
  8930. arrayBuffer = indices;
  8931. }
  8932. else {
  8933. //check 32 bit support
  8934. if (this._caps.uintIndices) {
  8935. if (indices instanceof Uint32Array) {
  8936. arrayBuffer = indices;
  8937. need32Bits = true;
  8938. }
  8939. else {
  8940. //number[] or Int32Array, check if 32 bit is necessary
  8941. for (var index = 0; index < indices.length; index++) {
  8942. if (indices[index] > 65535) {
  8943. need32Bits = true;
  8944. break;
  8945. }
  8946. }
  8947. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8948. }
  8949. }
  8950. else {
  8951. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8952. arrayBuffer = new Uint16Array(indices);
  8953. }
  8954. }
  8955. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8956. this._resetIndexBufferBinding();
  8957. vbo.references = 1;
  8958. vbo.is32Bits = need32Bits;
  8959. return vbo;
  8960. };
  8961. Engine.prototype.bindArrayBuffer = function (buffer) {
  8962. if (!this._vaoRecordInProgress) {
  8963. this._unBindVertexArrayObject();
  8964. }
  8965. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8966. };
  8967. Engine.prototype.bindIndexBuffer = function (buffer) {
  8968. if (!this._vaoRecordInProgress) {
  8969. this._unBindVertexArrayObject();
  8970. }
  8971. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8972. };
  8973. Engine.prototype.bindBuffer = function (buffer, target) {
  8974. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8975. this._gl.bindBuffer(target, buffer);
  8976. this._currentBoundBuffer[target] = buffer;
  8977. }
  8978. };
  8979. Engine.prototype.updateArrayBuffer = function (data) {
  8980. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8981. };
  8982. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8983. var pointer = this._currentBufferPointers[indx];
  8984. var changed = false;
  8985. if (!pointer) {
  8986. changed = true;
  8987. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8988. }
  8989. else {
  8990. if (pointer.buffer !== buffer) {
  8991. pointer.buffer = buffer;
  8992. changed = true;
  8993. }
  8994. if (pointer.size !== size) {
  8995. pointer.size = size;
  8996. changed = true;
  8997. }
  8998. if (pointer.type !== type) {
  8999. pointer.type = type;
  9000. changed = true;
  9001. }
  9002. if (pointer.normalized !== normalized) {
  9003. pointer.normalized = normalized;
  9004. changed = true;
  9005. }
  9006. if (pointer.stride !== stride) {
  9007. pointer.stride = stride;
  9008. changed = true;
  9009. }
  9010. if (pointer.offset !== offset) {
  9011. pointer.offset = offset;
  9012. changed = true;
  9013. }
  9014. }
  9015. if (changed || this._vaoRecordInProgress) {
  9016. this.bindArrayBuffer(buffer);
  9017. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9018. }
  9019. };
  9020. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9021. if (indexBuffer == null) {
  9022. return;
  9023. }
  9024. if (this._cachedIndexBuffer !== indexBuffer) {
  9025. this._cachedIndexBuffer = indexBuffer;
  9026. this.bindIndexBuffer(indexBuffer);
  9027. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9028. }
  9029. };
  9030. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9031. var attributes = effect.getAttributesNames();
  9032. if (!this._vaoRecordInProgress) {
  9033. this._unBindVertexArrayObject();
  9034. }
  9035. this.unbindAllAttributes();
  9036. for (var index = 0; index < attributes.length; index++) {
  9037. var order = effect.getAttributeLocation(index);
  9038. if (order >= 0) {
  9039. var vertexBuffer = vertexBuffers[attributes[index]];
  9040. if (!vertexBuffer) {
  9041. continue;
  9042. }
  9043. this._gl.enableVertexAttribArray(order);
  9044. if (!this._vaoRecordInProgress) {
  9045. this._vertexAttribArraysEnabled[order] = true;
  9046. }
  9047. var buffer = vertexBuffer.getBuffer();
  9048. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9049. if (vertexBuffer.getIsInstanced()) {
  9050. this._gl.vertexAttribDivisor(order, 1);
  9051. if (!this._vaoRecordInProgress) {
  9052. this._currentInstanceLocations.push(order);
  9053. this._currentInstanceBuffers.push(buffer);
  9054. }
  9055. }
  9056. }
  9057. }
  9058. };
  9059. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9060. var vao = this._gl.createVertexArray();
  9061. this._vaoRecordInProgress = true;
  9062. this._gl.bindVertexArray(vao);
  9063. this._mustWipeVertexAttributes = true;
  9064. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9065. this.bindIndexBuffer(indexBuffer);
  9066. this._vaoRecordInProgress = false;
  9067. this._gl.bindVertexArray(null);
  9068. return vao;
  9069. };
  9070. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9071. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9072. this._cachedVertexArrayObject = vertexArrayObject;
  9073. this._gl.bindVertexArray(vertexArrayObject);
  9074. this._cachedVertexBuffers = null;
  9075. this._cachedIndexBuffer = null;
  9076. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9077. this._mustWipeVertexAttributes = true;
  9078. }
  9079. };
  9080. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9081. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9082. this._cachedVertexBuffers = vertexBuffer;
  9083. this._cachedEffectForVertexBuffers = effect;
  9084. var attributesCount = effect.getAttributesCount();
  9085. this._unBindVertexArrayObject();
  9086. this.unbindAllAttributes();
  9087. var offset = 0;
  9088. for (var index = 0; index < attributesCount; index++) {
  9089. if (index < vertexDeclaration.length) {
  9090. var order = effect.getAttributeLocation(index);
  9091. if (order >= 0) {
  9092. this._gl.enableVertexAttribArray(order);
  9093. this._vertexAttribArraysEnabled[order] = true;
  9094. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9095. }
  9096. offset += vertexDeclaration[index] * 4;
  9097. }
  9098. }
  9099. }
  9100. this._bindIndexBufferWithCache(indexBuffer);
  9101. };
  9102. Engine.prototype._unBindVertexArrayObject = function () {
  9103. if (!this._cachedVertexArrayObject) {
  9104. return;
  9105. }
  9106. this._cachedVertexArrayObject = null;
  9107. this._gl.bindVertexArray(null);
  9108. };
  9109. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9110. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9111. this._cachedVertexBuffers = vertexBuffers;
  9112. this._cachedEffectForVertexBuffers = effect;
  9113. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9114. }
  9115. this._bindIndexBufferWithCache(indexBuffer);
  9116. };
  9117. Engine.prototype.unbindInstanceAttributes = function () {
  9118. var boundBuffer;
  9119. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9120. var instancesBuffer = this._currentInstanceBuffers[i];
  9121. if (boundBuffer != instancesBuffer) {
  9122. boundBuffer = instancesBuffer;
  9123. this.bindArrayBuffer(instancesBuffer);
  9124. }
  9125. var offsetLocation = this._currentInstanceLocations[i];
  9126. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9127. }
  9128. this._currentInstanceBuffers.length = 0;
  9129. this._currentInstanceLocations.length = 0;
  9130. };
  9131. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9132. this._gl.deleteVertexArray(vao);
  9133. };
  9134. Engine.prototype._releaseBuffer = function (buffer) {
  9135. buffer.references--;
  9136. if (buffer.references === 0) {
  9137. this._gl.deleteBuffer(buffer);
  9138. return true;
  9139. }
  9140. return false;
  9141. };
  9142. Engine.prototype.createInstancesBuffer = function (capacity) {
  9143. var buffer = this._gl.createBuffer();
  9144. buffer.capacity = capacity;
  9145. this.bindArrayBuffer(buffer);
  9146. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9147. return buffer;
  9148. };
  9149. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9150. this._gl.deleteBuffer(buffer);
  9151. };
  9152. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9153. this.bindArrayBuffer(instancesBuffer);
  9154. if (data) {
  9155. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9156. }
  9157. if (offsetLocations[0].index !== undefined) {
  9158. var stride = 0;
  9159. for (var i = 0; i < offsetLocations.length; i++) {
  9160. var ai = offsetLocations[i];
  9161. stride += ai.attributeSize * 4;
  9162. }
  9163. for (var i = 0; i < offsetLocations.length; i++) {
  9164. var ai = offsetLocations[i];
  9165. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9166. this._gl.enableVertexAttribArray(ai.index);
  9167. this._vertexAttribArraysEnabled[ai.index] = true;
  9168. }
  9169. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9170. this._gl.vertexAttribDivisor(ai.index, 1);
  9171. this._currentInstanceLocations.push(ai.index);
  9172. this._currentInstanceBuffers.push(instancesBuffer);
  9173. }
  9174. }
  9175. else {
  9176. for (var index = 0; index < 4; index++) {
  9177. var offsetLocation = offsetLocations[index];
  9178. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9179. this._gl.enableVertexAttribArray(offsetLocation);
  9180. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9181. }
  9182. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9183. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9184. this._currentInstanceLocations.push(offsetLocation);
  9185. this._currentInstanceBuffers.push(instancesBuffer);
  9186. }
  9187. }
  9188. };
  9189. Engine.prototype.applyStates = function () {
  9190. this._depthCullingState.apply(this._gl);
  9191. this._stencilState.apply(this._gl);
  9192. this._alphaState.apply(this._gl);
  9193. };
  9194. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9195. // Apply states
  9196. this.applyStates();
  9197. this._drawCalls.addCount(1, false);
  9198. // Render
  9199. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9200. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9201. if (instancesCount) {
  9202. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9203. return;
  9204. }
  9205. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9206. };
  9207. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9208. // Apply states
  9209. this.applyStates();
  9210. this._drawCalls.addCount(1, false);
  9211. if (instancesCount) {
  9212. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9213. return;
  9214. }
  9215. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9216. };
  9217. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9218. // Apply states
  9219. this.applyStates();
  9220. this._drawCalls.addCount(1, false);
  9221. if (instancesCount) {
  9222. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9223. return;
  9224. }
  9225. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9226. };
  9227. // Shaders
  9228. Engine.prototype._releaseEffect = function (effect) {
  9229. if (this._compiledEffects[effect._key]) {
  9230. delete this._compiledEffects[effect._key];
  9231. if (effect.getProgram()) {
  9232. this._gl.deleteProgram(effect.getProgram());
  9233. }
  9234. }
  9235. };
  9236. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9237. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9238. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9239. var name = vertex + "+" + fragment + "@" + defines;
  9240. if (this._compiledEffects[name]) {
  9241. return this._compiledEffects[name];
  9242. }
  9243. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9244. effect._key = name;
  9245. this._compiledEffects[name] = effect;
  9246. return effect;
  9247. };
  9248. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9249. if (uniformsNames === void 0) { uniformsNames = []; }
  9250. if (samplers === void 0) { samplers = []; }
  9251. if (defines === void 0) { defines = ""; }
  9252. return this.createEffect({
  9253. vertex: "particles",
  9254. fragmentElement: fragmentName
  9255. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9256. };
  9257. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9258. context = context || this._gl;
  9259. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9260. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9261. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9262. var shaderProgram = context.createProgram();
  9263. context.attachShader(shaderProgram, vertexShader);
  9264. context.attachShader(shaderProgram, fragmentShader);
  9265. context.linkProgram(shaderProgram);
  9266. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9267. if (!linked) {
  9268. var error = context.getProgramInfoLog(shaderProgram);
  9269. if (error) {
  9270. throw new Error(error);
  9271. }
  9272. }
  9273. context.deleteShader(vertexShader);
  9274. context.deleteShader(fragmentShader);
  9275. return shaderProgram;
  9276. };
  9277. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9278. var results = [];
  9279. for (var index = 0; index < uniformsNames.length; index++) {
  9280. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9281. }
  9282. return results;
  9283. };
  9284. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9285. var results = [];
  9286. for (var index = 0; index < attributesNames.length; index++) {
  9287. try {
  9288. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9289. }
  9290. catch (e) {
  9291. results.push(-1);
  9292. }
  9293. }
  9294. return results;
  9295. };
  9296. Engine.prototype.enableEffect = function (effect) {
  9297. // Use program
  9298. this.setProgram(effect.getProgram());
  9299. this._currentEffect = effect;
  9300. if (effect.onBind) {
  9301. effect.onBind(effect);
  9302. }
  9303. };
  9304. Engine.prototype.setIntArray = function (uniform, array) {
  9305. if (!uniform)
  9306. return;
  9307. this._gl.uniform1iv(uniform, array);
  9308. };
  9309. Engine.prototype.setIntArray2 = function (uniform, array) {
  9310. if (!uniform || array.length % 2 !== 0)
  9311. return;
  9312. this._gl.uniform2iv(uniform, array);
  9313. };
  9314. Engine.prototype.setIntArray3 = function (uniform, array) {
  9315. if (!uniform || array.length % 3 !== 0)
  9316. return;
  9317. this._gl.uniform3iv(uniform, array);
  9318. };
  9319. Engine.prototype.setIntArray4 = function (uniform, array) {
  9320. if (!uniform || array.length % 4 !== 0)
  9321. return;
  9322. this._gl.uniform4iv(uniform, array);
  9323. };
  9324. Engine.prototype.setFloatArray = function (uniform, array) {
  9325. if (!uniform)
  9326. return;
  9327. this._gl.uniform1fv(uniform, array);
  9328. };
  9329. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9330. if (!uniform || array.length % 2 !== 0)
  9331. return;
  9332. this._gl.uniform2fv(uniform, array);
  9333. };
  9334. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9335. if (!uniform || array.length % 3 !== 0)
  9336. return;
  9337. this._gl.uniform3fv(uniform, array);
  9338. };
  9339. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9340. if (!uniform || array.length % 4 !== 0)
  9341. return;
  9342. this._gl.uniform4fv(uniform, array);
  9343. };
  9344. Engine.prototype.setArray = function (uniform, array) {
  9345. if (!uniform)
  9346. return;
  9347. this._gl.uniform1fv(uniform, array);
  9348. };
  9349. Engine.prototype.setArray2 = function (uniform, array) {
  9350. if (!uniform || array.length % 2 !== 0)
  9351. return;
  9352. this._gl.uniform2fv(uniform, array);
  9353. };
  9354. Engine.prototype.setArray3 = function (uniform, array) {
  9355. if (!uniform || array.length % 3 !== 0)
  9356. return;
  9357. this._gl.uniform3fv(uniform, array);
  9358. };
  9359. Engine.prototype.setArray4 = function (uniform, array) {
  9360. if (!uniform || array.length % 4 !== 0)
  9361. return;
  9362. this._gl.uniform4fv(uniform, array);
  9363. };
  9364. Engine.prototype.setMatrices = function (uniform, matrices) {
  9365. if (!uniform)
  9366. return;
  9367. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9368. };
  9369. Engine.prototype.setMatrix = function (uniform, matrix) {
  9370. if (!uniform)
  9371. return;
  9372. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9373. };
  9374. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9375. if (!uniform)
  9376. return;
  9377. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9378. };
  9379. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9380. if (!uniform)
  9381. return;
  9382. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9383. };
  9384. Engine.prototype.setFloat = function (uniform, value) {
  9385. if (!uniform)
  9386. return;
  9387. this._gl.uniform1f(uniform, value);
  9388. };
  9389. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9390. if (!uniform)
  9391. return;
  9392. this._gl.uniform2f(uniform, x, y);
  9393. };
  9394. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9395. if (!uniform)
  9396. return;
  9397. this._gl.uniform3f(uniform, x, y, z);
  9398. };
  9399. Engine.prototype.setBool = function (uniform, bool) {
  9400. if (!uniform)
  9401. return;
  9402. this._gl.uniform1i(uniform, bool);
  9403. };
  9404. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9405. if (!uniform)
  9406. return;
  9407. this._gl.uniform4f(uniform, x, y, z, w);
  9408. };
  9409. Engine.prototype.setColor3 = function (uniform, color3) {
  9410. if (!uniform)
  9411. return;
  9412. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9413. };
  9414. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9415. if (!uniform)
  9416. return;
  9417. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9418. };
  9419. // States
  9420. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9421. if (zOffset === void 0) { zOffset = 0; }
  9422. if (reverseSide === void 0) { reverseSide = false; }
  9423. // Culling
  9424. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9425. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9426. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9427. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9428. if (culling) {
  9429. this._depthCullingState.cullFace = cullFace;
  9430. this._depthCullingState.cull = true;
  9431. }
  9432. else {
  9433. this._depthCullingState.cull = false;
  9434. }
  9435. }
  9436. // Z offset
  9437. this._depthCullingState.zOffset = zOffset;
  9438. };
  9439. Engine.prototype.setDepthBuffer = function (enable) {
  9440. this._depthCullingState.depthTest = enable;
  9441. };
  9442. Engine.prototype.getDepthWrite = function () {
  9443. return this._depthCullingState.depthMask;
  9444. };
  9445. Engine.prototype.setDepthWrite = function (enable) {
  9446. this._depthCullingState.depthMask = enable;
  9447. };
  9448. Engine.prototype.setColorWrite = function (enable) {
  9449. this._gl.colorMask(enable, enable, enable, enable);
  9450. };
  9451. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9452. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9453. if (this._alphaMode === mode) {
  9454. return;
  9455. }
  9456. switch (mode) {
  9457. case Engine.ALPHA_DISABLE:
  9458. this._alphaState.alphaBlend = false;
  9459. break;
  9460. case Engine.ALPHA_PREMULTIPLIED:
  9461. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9462. this._alphaState.alphaBlend = true;
  9463. break;
  9464. case Engine.ALPHA_COMBINE:
  9465. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9466. this._alphaState.alphaBlend = true;
  9467. break;
  9468. case Engine.ALPHA_ONEONE:
  9469. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9470. this._alphaState.alphaBlend = true;
  9471. break;
  9472. case Engine.ALPHA_ADD:
  9473. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9474. this._alphaState.alphaBlend = true;
  9475. break;
  9476. case Engine.ALPHA_SUBTRACT:
  9477. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9478. this._alphaState.alphaBlend = true;
  9479. break;
  9480. case Engine.ALPHA_MULTIPLY:
  9481. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9482. this._alphaState.alphaBlend = true;
  9483. break;
  9484. case Engine.ALPHA_MAXIMIZED:
  9485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9486. this._alphaState.alphaBlend = true;
  9487. break;
  9488. }
  9489. if (!noDepthWriteChange) {
  9490. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9491. }
  9492. this._alphaMode = mode;
  9493. };
  9494. Engine.prototype.getAlphaMode = function () {
  9495. return this._alphaMode;
  9496. };
  9497. Engine.prototype.setAlphaTesting = function (enable) {
  9498. this._alphaTest = enable;
  9499. };
  9500. Engine.prototype.getAlphaTesting = function () {
  9501. return this._alphaTest;
  9502. };
  9503. // Textures
  9504. Engine.prototype.wipeCaches = function () {
  9505. if (this.preventCacheWipeBetweenFrames) {
  9506. return;
  9507. }
  9508. this.resetTextureCache();
  9509. this._currentEffect = null;
  9510. this._stencilState.reset();
  9511. this._depthCullingState.reset();
  9512. this.setDepthFunctionToLessOrEqual();
  9513. this._alphaState.reset();
  9514. this._cachedVertexBuffers = null;
  9515. this._cachedIndexBuffer = null;
  9516. this._cachedEffectForVertexBuffers = null;
  9517. this._unBindVertexArrayObject();
  9518. this.bindIndexBuffer(null);
  9519. this.bindArrayBuffer(null);
  9520. };
  9521. /**
  9522. * Set the compressed texture format to use, based on the formats you have, and the formats
  9523. * supported by the hardware / browser.
  9524. *
  9525. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9526. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9527. * to API arguments needed to compressed textures. This puts the burden on the container
  9528. * generator to house the arcane code for determining these for current & future formats.
  9529. *
  9530. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9531. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9532. *
  9533. * Note: The result of this call is not taken into account when a texture is base64.
  9534. *
  9535. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9536. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9537. *
  9538. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9539. * @returns The extension selected.
  9540. */
  9541. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9542. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9543. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9544. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9545. return this._textureFormatInUse = this._texturesSupported[i];
  9546. }
  9547. }
  9548. }
  9549. // actively set format to nothing, to allow this to be called more than once
  9550. // and possibly fail the 2nd time
  9551. return this._textureFormatInUse = null;
  9552. };
  9553. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9554. var _this = this;
  9555. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9556. if (onLoad === void 0) { onLoad = null; }
  9557. if (onError === void 0) { onError = null; }
  9558. if (buffer === void 0) { buffer = null; }
  9559. var texture = fallBack ? fallBack : this._gl.createTexture();
  9560. var extension;
  9561. var isKTX = false;
  9562. var fromData = false;
  9563. var url = String(urlArg);
  9564. if (url.substr(0, 5) === "data:") {
  9565. fromData = true;
  9566. }
  9567. if (!fromData) {
  9568. var lastDot = url.lastIndexOf('.');
  9569. extension = url.substring(lastDot).toLowerCase();
  9570. if (this._textureFormatInUse && !fromData && !fallBack) {
  9571. extension = this._textureFormatInUse;
  9572. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9573. isKTX = true;
  9574. }
  9575. }
  9576. else {
  9577. var oldUrl = url;
  9578. fromData = oldUrl.split(':');
  9579. url = oldUrl;
  9580. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9581. }
  9582. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9583. var isTGA = (extension === ".tga");
  9584. scene._addPendingData(texture);
  9585. texture.url = url;
  9586. texture.noMipmap = noMipmap;
  9587. texture.references = 1;
  9588. texture.samplingMode = samplingMode;
  9589. texture.onLoadedCallbacks = [];
  9590. if (onLoad) {
  9591. texture.onLoadedCallbacks.push(onLoad);
  9592. }
  9593. if (!fallBack)
  9594. this._loadedTexturesCache.push(texture);
  9595. var onerror = function () {
  9596. scene._removePendingData(texture);
  9597. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9598. if (isKTX) {
  9599. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9600. }
  9601. else if (onError) {
  9602. onError();
  9603. }
  9604. };
  9605. var callback;
  9606. if (isKTX || isTGA || isDDS) {
  9607. if (isKTX) {
  9608. callback = function (data) {
  9609. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9610. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9611. ktx.uploadLevels(_this._gl, !noMipmap);
  9612. }, samplingMode);
  9613. };
  9614. }
  9615. else if (isTGA) {
  9616. callback = function (arrayBuffer) {
  9617. var data = new Uint8Array(arrayBuffer);
  9618. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9619. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9620. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9621. }, samplingMode);
  9622. };
  9623. }
  9624. else if (isDDS) {
  9625. callback = function (data) {
  9626. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9627. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9628. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9629. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9630. }, samplingMode);
  9631. };
  9632. }
  9633. if (!(fromData instanceof Array))
  9634. BABYLON.Tools.LoadFile(url, function (data) {
  9635. callback(data);
  9636. }, null, scene.database, true, onerror);
  9637. else
  9638. callback(buffer);
  9639. }
  9640. else {
  9641. var onload = function (img) {
  9642. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9643. var isPot = (img.width === potWidth && img.height === potHeight);
  9644. if (!isPot) {
  9645. _this._prepareWorkingCanvas();
  9646. _this._workingCanvas.width = potWidth;
  9647. _this._workingCanvas.height = potHeight;
  9648. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9649. _this._workingContext.imageSmoothingEnabled = false;
  9650. _this._workingContext.mozImageSmoothingEnabled = false;
  9651. _this._workingContext.oImageSmoothingEnabled = false;
  9652. _this._workingContext.webkitImageSmoothingEnabled = false;
  9653. _this._workingContext.msImageSmoothingEnabled = false;
  9654. }
  9655. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9656. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9657. _this._workingContext.imageSmoothingEnabled = true;
  9658. _this._workingContext.mozImageSmoothingEnabled = true;
  9659. _this._workingContext.oImageSmoothingEnabled = true;
  9660. _this._workingContext.webkitImageSmoothingEnabled = true;
  9661. _this._workingContext.msImageSmoothingEnabled = true;
  9662. }
  9663. }
  9664. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9665. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9666. }, samplingMode);
  9667. };
  9668. if (!(fromData instanceof Array))
  9669. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9670. else
  9671. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9672. }
  9673. return texture;
  9674. };
  9675. Engine.prototype._getInternalFormat = function (format) {
  9676. var internalFormat = this._gl.RGBA;
  9677. switch (format) {
  9678. case Engine.TEXTUREFORMAT_ALPHA:
  9679. internalFormat = this._gl.ALPHA;
  9680. break;
  9681. case Engine.TEXTUREFORMAT_LUMINANCE:
  9682. internalFormat = this._gl.LUMINANCE;
  9683. break;
  9684. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9685. internalFormat = this._gl.LUMINANCE_ALPHA;
  9686. break;
  9687. case Engine.TEXTUREFORMAT_RGB:
  9688. internalFormat = this._gl.RGB;
  9689. break;
  9690. case Engine.TEXTUREFORMAT_RGBA:
  9691. internalFormat = this._gl.RGBA;
  9692. break;
  9693. }
  9694. return internalFormat;
  9695. };
  9696. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9697. if (compression === void 0) { compression = null; }
  9698. var internalFormat = this._getInternalFormat(format);
  9699. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9700. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9701. if (texture._width % 4 !== 0) {
  9702. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9703. }
  9704. if (compression) {
  9705. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9706. }
  9707. else {
  9708. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9709. }
  9710. if (texture.generateMipMaps) {
  9711. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9712. }
  9713. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9714. this.resetTextureCache();
  9715. texture.isReady = true;
  9716. };
  9717. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9718. if (compression === void 0) { compression = null; }
  9719. var texture = this._gl.createTexture();
  9720. texture._baseWidth = width;
  9721. texture._baseHeight = height;
  9722. texture._width = width;
  9723. texture._height = height;
  9724. texture.references = 1;
  9725. this.updateRawTexture(texture, data, format, invertY, compression);
  9726. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9727. // Filters
  9728. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9729. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9730. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9731. if (generateMipMaps) {
  9732. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9733. }
  9734. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9735. texture.samplingMode = samplingMode;
  9736. this._loadedTexturesCache.push(texture);
  9737. return texture;
  9738. };
  9739. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9740. var texture = this._gl.createTexture();
  9741. texture._baseWidth = width;
  9742. texture._baseHeight = height;
  9743. if (generateMipMaps) {
  9744. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9745. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9746. }
  9747. this.resetTextureCache();
  9748. texture._width = width;
  9749. texture._height = height;
  9750. texture.isReady = false;
  9751. texture.generateMipMaps = generateMipMaps;
  9752. texture.references = 1;
  9753. texture.samplingMode = samplingMode;
  9754. this.updateTextureSamplingMode(samplingMode, texture);
  9755. this._loadedTexturesCache.push(texture);
  9756. return texture;
  9757. };
  9758. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9759. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9760. if (texture.isCube) {
  9761. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9762. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9763. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9764. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9765. }
  9766. else {
  9767. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9768. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9769. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9770. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9771. }
  9772. texture.samplingMode = samplingMode;
  9773. };
  9774. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9775. if (premulAlpha === void 0) { premulAlpha = false; }
  9776. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9777. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9778. if (premulAlpha) {
  9779. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9780. }
  9781. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9782. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9783. if (texture.generateMipMaps) {
  9784. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9785. }
  9786. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9787. if (premulAlpha) {
  9788. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9789. }
  9790. this.resetTextureCache();
  9791. texture.isReady = true;
  9792. };
  9793. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9794. if (texture._isDisabled) {
  9795. return;
  9796. }
  9797. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9798. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9799. try {
  9800. // Testing video texture support
  9801. if (this._videoTextureSupported === undefined) {
  9802. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9803. if (this._gl.getError() !== 0) {
  9804. this._videoTextureSupported = false;
  9805. }
  9806. else {
  9807. this._videoTextureSupported = true;
  9808. }
  9809. }
  9810. // Copy video through the current working canvas if video texture is not supported
  9811. if (!this._videoTextureSupported) {
  9812. if (!texture._workingCanvas) {
  9813. texture._workingCanvas = document.createElement("canvas");
  9814. texture._workingContext = texture._workingCanvas.getContext("2d");
  9815. texture._workingCanvas.width = texture._width;
  9816. texture._workingCanvas.height = texture._height;
  9817. }
  9818. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9819. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9820. }
  9821. else {
  9822. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9823. }
  9824. if (texture.generateMipMaps) {
  9825. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9826. }
  9827. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9828. this.resetTextureCache();
  9829. texture.isReady = true;
  9830. }
  9831. catch (ex) {
  9832. // Something unexpected
  9833. // Let's disable the texture
  9834. texture._isDisabled = true;
  9835. }
  9836. };
  9837. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9838. // old version had a "generateMipMaps" arg instead of options.
  9839. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9840. // in the same way, generateDepthBuffer is defaulted to true
  9841. var generateMipMaps = false;
  9842. var generateDepthBuffer = true;
  9843. var generateStencilBuffer = false;
  9844. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9845. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9846. if (options !== undefined) {
  9847. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9848. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9849. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9850. type = options.type === undefined ? type : options.type;
  9851. if (options.samplingMode !== undefined) {
  9852. samplingMode = options.samplingMode;
  9853. }
  9854. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9855. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9856. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9857. }
  9858. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9859. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9860. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9861. }
  9862. }
  9863. var gl = this._gl;
  9864. var texture = gl.createTexture();
  9865. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9866. var width = size.width || size;
  9867. var height = size.height || size;
  9868. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9869. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9870. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9871. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9872. }
  9873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9875. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9877. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9878. // Create the framebuffer
  9879. var framebuffer = gl.createFramebuffer();
  9880. this.bindUnboundFramebuffer(framebuffer);
  9881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9882. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9883. if (generateMipMaps) {
  9884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9885. }
  9886. // Unbind
  9887. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9888. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9889. this.bindUnboundFramebuffer(null);
  9890. texture._framebuffer = framebuffer;
  9891. texture._baseWidth = width;
  9892. texture._baseHeight = height;
  9893. texture._width = width;
  9894. texture._height = height;
  9895. texture.isReady = true;
  9896. texture.samples = 1;
  9897. texture.generateMipMaps = generateMipMaps;
  9898. texture.references = 1;
  9899. texture.samplingMode = samplingMode;
  9900. texture.type = type;
  9901. texture._generateDepthBuffer = generateDepthBuffer;
  9902. texture._generateStencilBuffer = generateStencilBuffer;
  9903. this.resetTextureCache();
  9904. this._loadedTexturesCache.push(texture);
  9905. return texture;
  9906. };
  9907. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9908. if (samples === void 0) { samples = 1; }
  9909. var depthStencilBuffer = null;
  9910. var gl = this._gl;
  9911. // Create the depth/stencil buffer
  9912. if (generateStencilBuffer) {
  9913. depthStencilBuffer = gl.createRenderbuffer();
  9914. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9915. if (samples > 1) {
  9916. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9917. }
  9918. else {
  9919. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9920. }
  9921. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9922. }
  9923. else if (generateDepthBuffer) {
  9924. depthStencilBuffer = gl.createRenderbuffer();
  9925. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9926. if (samples > 1) {
  9927. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9928. }
  9929. else {
  9930. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9931. }
  9932. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9933. }
  9934. return depthStencilBuffer;
  9935. };
  9936. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9937. if (this.webGLVersion < 2) {
  9938. return 1;
  9939. }
  9940. if (texture.samples === samples) {
  9941. return samples;
  9942. }
  9943. var gl = this._gl;
  9944. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9945. // Dispose previous render buffers
  9946. if (texture._depthStencilBuffer) {
  9947. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9948. }
  9949. if (texture._MSAAFramebuffer) {
  9950. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9951. }
  9952. if (texture._MSAARenderBuffer) {
  9953. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9954. }
  9955. if (samples > 1) {
  9956. texture._MSAAFramebuffer = gl.createFramebuffer();
  9957. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9958. var colorRenderbuffer = gl.createRenderbuffer();
  9959. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9960. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9961. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9962. texture._MSAARenderBuffer = colorRenderbuffer;
  9963. }
  9964. else {
  9965. this.bindUnboundFramebuffer(texture._framebuffer);
  9966. }
  9967. texture.samples = samples;
  9968. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9969. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9970. this.bindUnboundFramebuffer(null);
  9971. return samples;
  9972. };
  9973. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9974. var gl = this._gl;
  9975. var texture = gl.createTexture();
  9976. var generateMipMaps = true;
  9977. var generateDepthBuffer = true;
  9978. var generateStencilBuffer = false;
  9979. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9980. if (options !== undefined) {
  9981. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9982. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9983. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9984. if (options.samplingMode !== undefined) {
  9985. samplingMode = options.samplingMode;
  9986. }
  9987. }
  9988. texture.isCube = true;
  9989. texture.references = 1;
  9990. texture.generateMipMaps = generateMipMaps;
  9991. texture.references = 1;
  9992. texture.samples = 1;
  9993. texture.samplingMode = samplingMode;
  9994. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9995. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9996. for (var face = 0; face < 6; face++) {
  9997. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9998. }
  9999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10003. // Create the framebuffer
  10004. var framebuffer = gl.createFramebuffer();
  10005. this.bindUnboundFramebuffer(framebuffer);
  10006. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10007. // Mipmaps
  10008. if (texture.generateMipMaps) {
  10009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10010. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10011. }
  10012. // Unbind
  10013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10014. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10015. this.bindUnboundFramebuffer(null);
  10016. texture._framebuffer = framebuffer;
  10017. texture._width = size;
  10018. texture._height = size;
  10019. texture.isReady = true;
  10020. this.resetTextureCache();
  10021. this._loadedTexturesCache.push(texture);
  10022. return texture;
  10023. };
  10024. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10025. var _this = this;
  10026. if (onLoad === void 0) { onLoad = null; }
  10027. if (onError === void 0) { onError = null; }
  10028. var gl = this._gl;
  10029. var texture = gl.createTexture();
  10030. texture.isCube = true;
  10031. texture.url = rootUrl;
  10032. texture.references = 1;
  10033. texture.onLoadedCallbacks = [];
  10034. var isKTX = false;
  10035. var lastDot = rootUrl.lastIndexOf('.');
  10036. var extension = rootUrl.substring(lastDot).toLowerCase();
  10037. if (this._textureFormatInUse) {
  10038. extension = this._textureFormatInUse;
  10039. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10040. isKTX = true;
  10041. }
  10042. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10043. if (isKTX) {
  10044. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10045. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10046. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10047. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10048. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10049. ktx.uploadLevels(_this._gl, !noMipmap);
  10050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10051. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10052. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10054. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10055. _this.resetTextureCache();
  10056. texture._width = ktx.pixelWidth;
  10057. texture._height = ktx.pixelHeight;
  10058. texture.isReady = true;
  10059. }, null, null, true, onError);
  10060. }
  10061. else if (isDDS) {
  10062. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10063. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10064. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10066. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10067. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10068. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10069. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10070. }
  10071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10075. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10076. _this.resetTextureCache();
  10077. texture._width = info.width;
  10078. texture._height = info.height;
  10079. texture.isReady = true;
  10080. }, null, null, true, onError);
  10081. }
  10082. else {
  10083. cascadeLoad(rootUrl, scene, function (imgs) {
  10084. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10085. var height = width;
  10086. _this._prepareWorkingCanvas();
  10087. _this._workingCanvas.width = width;
  10088. _this._workingCanvas.height = height;
  10089. var faces = [
  10090. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10091. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10092. ];
  10093. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10094. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10095. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10096. for (var index = 0; index < faces.length; index++) {
  10097. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10098. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10099. }
  10100. if (!noMipmap) {
  10101. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10102. }
  10103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10105. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10107. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10108. _this.resetTextureCache();
  10109. texture._width = width;
  10110. texture._height = height;
  10111. texture.isReady = true;
  10112. texture.onLoadedCallbacks.forEach(function (callback) {
  10113. callback();
  10114. });
  10115. if (onLoad) {
  10116. onLoad();
  10117. }
  10118. }, files, onError);
  10119. }
  10120. this._loadedTexturesCache.push(texture);
  10121. return texture;
  10122. };
  10123. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10124. texture._width = width;
  10125. texture._height = height;
  10126. texture._size = width * height;
  10127. texture._baseWidth = width;
  10128. texture._baseHeight = height;
  10129. };
  10130. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10131. var _this = this;
  10132. if (onLoad === void 0) { onLoad = null; }
  10133. if (onError === void 0) { onError = null; }
  10134. var gl = this._gl;
  10135. var texture = gl.createTexture();
  10136. scene._addPendingData(texture);
  10137. texture.isCube = true;
  10138. texture.references = 1;
  10139. texture.url = url;
  10140. var textureType = gl.UNSIGNED_BYTE;
  10141. if (type === Engine.TEXTURETYPE_FLOAT) {
  10142. textureType = gl.FLOAT;
  10143. }
  10144. var internalFormat = this._getInternalFormat(format);
  10145. var needConversion = false;
  10146. if (internalFormat === gl.RGB) {
  10147. internalFormat = gl.RGBA;
  10148. needConversion = true;
  10149. }
  10150. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10151. var width = size;
  10152. var height = width;
  10153. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10154. texture._width = width;
  10155. texture._height = height;
  10156. var onerror = function () {
  10157. scene._removePendingData(texture);
  10158. if (onError) {
  10159. onError();
  10160. }
  10161. };
  10162. var internalCallback = function (data) {
  10163. var rgbeDataArrays = callback(data);
  10164. var facesIndex = [
  10165. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10166. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10167. ];
  10168. width = texture._width;
  10169. height = texture._height;
  10170. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10171. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10172. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10173. if (mipmmapGenerator) {
  10174. var arrayTemp = [];
  10175. // Data are known to be in +X +Y +Z -X -Y -Z
  10176. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10177. arrayTemp.push(rgbeDataArrays[0]); // +X
  10178. arrayTemp.push(rgbeDataArrays[3]); // -X
  10179. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10180. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10181. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10182. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10183. var mipData = mipmmapGenerator(arrayTemp);
  10184. // mipData is order in +X -X +Y -Y +Z -Z
  10185. var mipFaces = [0, 2, 4, 1, 3, 5];
  10186. for (var level = 0; level < mipData.length; level++) {
  10187. var mipSize = width >> level;
  10188. for (var mipIndex in mipFaces) {
  10189. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10190. if (needConversion) {
  10191. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10192. }
  10193. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10194. }
  10195. }
  10196. }
  10197. else {
  10198. // Data are known to be in +X +Y +Z -X -Y -Z
  10199. for (var index = 0; index < facesIndex.length; index++) {
  10200. var faceData = rgbeDataArrays[index];
  10201. if (needConversion) {
  10202. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10203. }
  10204. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10205. }
  10206. if (!noMipmap && isPot) {
  10207. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10208. }
  10209. else {
  10210. noMipmap = true;
  10211. }
  10212. }
  10213. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10216. }
  10217. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10220. }
  10221. else {
  10222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10224. }
  10225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10227. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10228. texture.isReady = true;
  10229. _this.resetTextureCache();
  10230. scene._removePendingData(texture);
  10231. if (onLoad) {
  10232. onLoad();
  10233. }
  10234. };
  10235. BABYLON.Tools.LoadFile(url, function (data) {
  10236. internalCallback(data);
  10237. }, onerror, scene.database, true);
  10238. return texture;
  10239. };
  10240. ;
  10241. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10242. // Create new RGBA data container.
  10243. var rgbaData;
  10244. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10245. rgbaData = new Float32Array(width * height * 4);
  10246. }
  10247. else {
  10248. rgbaData = new Uint32Array(width * height * 4);
  10249. }
  10250. // Convert each pixel.
  10251. for (var x = 0; x < width; x++) {
  10252. for (var y = 0; y < height; y++) {
  10253. var index = (y * width + x) * 3;
  10254. var newIndex = (y * width + x) * 4;
  10255. // Map Old Value to new value.
  10256. rgbaData[newIndex + 0] = rgbData[index + 0];
  10257. rgbaData[newIndex + 1] = rgbData[index + 1];
  10258. rgbaData[newIndex + 2] = rgbData[index + 2];
  10259. // Add fully opaque alpha channel.
  10260. rgbaData[newIndex + 3] = 1;
  10261. }
  10262. }
  10263. return rgbaData;
  10264. };
  10265. Engine.prototype._releaseTexture = function (texture) {
  10266. var gl = this._gl;
  10267. if (texture._framebuffer) {
  10268. gl.deleteFramebuffer(texture._framebuffer);
  10269. }
  10270. if (texture._depthStencilBuffer) {
  10271. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10272. }
  10273. if (texture._MSAAFramebuffer) {
  10274. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10275. }
  10276. if (texture._MSAARenderBuffer) {
  10277. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10278. }
  10279. gl.deleteTexture(texture);
  10280. // Unbind channels
  10281. this.unbindAllTextures();
  10282. var index = this._loadedTexturesCache.indexOf(texture);
  10283. if (index !== -1) {
  10284. this._loadedTexturesCache.splice(index, 1);
  10285. }
  10286. };
  10287. Engine.prototype.setProgram = function (program) {
  10288. if (this._currentProgram !== program) {
  10289. this._gl.useProgram(program);
  10290. this._currentProgram = program;
  10291. }
  10292. };
  10293. Engine.prototype.bindSamplers = function (effect) {
  10294. this.setProgram(effect.getProgram());
  10295. var samplers = effect.getSamplers();
  10296. for (var index = 0; index < samplers.length; index++) {
  10297. var uniform = effect.getUniform(samplers[index]);
  10298. this._gl.uniform1i(uniform, index);
  10299. }
  10300. this._currentEffect = null;
  10301. };
  10302. Engine.prototype.activateTexture = function (texture) {
  10303. if (this._activeTexture !== texture) {
  10304. this._gl.activeTexture(texture);
  10305. this._activeTexture = texture;
  10306. }
  10307. };
  10308. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10309. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10310. this._gl.bindTexture(target, texture);
  10311. this._activeTexturesCache[this._activeTexture] = texture;
  10312. }
  10313. };
  10314. Engine.prototype._bindTexture = function (channel, texture) {
  10315. if (channel < 0) {
  10316. return;
  10317. }
  10318. this.activateTexture(this._gl.TEXTURE0 + channel);
  10319. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10320. };
  10321. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10322. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10323. };
  10324. Engine.prototype.unbindAllTextures = function () {
  10325. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10326. this.activateTexture(this._gl["TEXTURE" + channel]);
  10327. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10328. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10329. }
  10330. };
  10331. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10332. if (channel < 0) {
  10333. return;
  10334. }
  10335. this._gl.uniform1i(uniform, channel);
  10336. this._setTexture(channel, texture);
  10337. };
  10338. Engine.prototype._setTexture = function (channel, texture) {
  10339. // Not ready?
  10340. if (!texture || !texture.isReady()) {
  10341. if (this._activeTexturesCache[channel] != null) {
  10342. this.activateTexture(this._gl["TEXTURE" + channel]);
  10343. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10344. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10345. }
  10346. return;
  10347. }
  10348. // Video
  10349. var alreadyActivated = false;
  10350. if (texture instanceof BABYLON.VideoTexture) {
  10351. this.activateTexture(this._gl["TEXTURE" + channel]);
  10352. alreadyActivated = true;
  10353. texture.update();
  10354. }
  10355. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10356. texture.delayLoad();
  10357. return;
  10358. }
  10359. var internalTexture = texture.getInternalTexture();
  10360. if (this._activeTexturesCache[channel] === internalTexture) {
  10361. return;
  10362. }
  10363. if (!alreadyActivated) {
  10364. this.activateTexture(this._gl["TEXTURE" + channel]);
  10365. }
  10366. if (internalTexture.isCube) {
  10367. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10368. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10369. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10370. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10371. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10372. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10373. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10374. }
  10375. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10376. }
  10377. else {
  10378. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10379. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10380. internalTexture._cachedWrapU = texture.wrapU;
  10381. switch (texture.wrapU) {
  10382. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10383. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10384. break;
  10385. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10386. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10387. break;
  10388. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10389. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10390. break;
  10391. }
  10392. }
  10393. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10394. internalTexture._cachedWrapV = texture.wrapV;
  10395. switch (texture.wrapV) {
  10396. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10398. break;
  10399. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10400. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10401. break;
  10402. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10403. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10404. break;
  10405. }
  10406. }
  10407. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10408. }
  10409. };
  10410. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10411. if (channel < 0) {
  10412. return;
  10413. }
  10414. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10415. this._textureUnits = new Int32Array(textures.length);
  10416. }
  10417. for (var i = 0; i < textures.length; i++) {
  10418. this._textureUnits[i] = channel + i;
  10419. }
  10420. this._gl.uniform1iv(uniform, this._textureUnits);
  10421. for (var index = 0; index < textures.length; index++) {
  10422. this._setTexture(channel + index, textures[index]);
  10423. }
  10424. };
  10425. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10426. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10427. var value = texture.anisotropicFilteringLevel;
  10428. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10429. value = 1;
  10430. }
  10431. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10432. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10433. texture._cachedAnisotropicFilteringLevel = value;
  10434. }
  10435. };
  10436. Engine.prototype.readPixels = function (x, y, width, height) {
  10437. var data = new Uint8Array(height * width * 4);
  10438. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10439. return data;
  10440. };
  10441. /**
  10442. * Add an externaly attached data from its key.
  10443. * This method call will fail and return false, if such key already exists.
  10444. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10445. * @param key the unique key that identifies the data
  10446. * @param data the data object to associate to the key for this Engine instance
  10447. * @return true if no such key were already present and the data was added successfully, false otherwise
  10448. */
  10449. Engine.prototype.addExternalData = function (key, data) {
  10450. return this._externalData.add(key, data);
  10451. };
  10452. /**
  10453. * Get an externaly attached data from its key
  10454. * @param key the unique key that identifies the data
  10455. * @return the associated data, if present (can be null), or undefined if not present
  10456. */
  10457. Engine.prototype.getExternalData = function (key) {
  10458. return this._externalData.get(key);
  10459. };
  10460. /**
  10461. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10462. * @param key the unique key that identifies the data
  10463. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10464. * @return the associated data, can be null if the factory returned null.
  10465. */
  10466. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10467. return this._externalData.getOrAddWithFactory(key, factory);
  10468. };
  10469. /**
  10470. * Remove an externaly attached data from the Engine instance
  10471. * @param key the unique key that identifies the data
  10472. * @return true if the data was successfully removed, false if it doesn't exist
  10473. */
  10474. Engine.prototype.removeExternalData = function (key) {
  10475. return this._externalData.remove(key);
  10476. };
  10477. Engine.prototype.releaseInternalTexture = function (texture) {
  10478. if (!texture) {
  10479. return;
  10480. }
  10481. texture.references--;
  10482. // Final reference ?
  10483. if (texture.references === 0) {
  10484. var texturesCache = this.getLoadedTexturesCache();
  10485. var index = texturesCache.indexOf(texture);
  10486. if (index > -1) {
  10487. texturesCache.splice(index, 1);
  10488. }
  10489. this._releaseTexture(texture);
  10490. }
  10491. };
  10492. Engine.prototype.unbindAllAttributes = function () {
  10493. if (this._mustWipeVertexAttributes) {
  10494. this._mustWipeVertexAttributes = false;
  10495. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10496. this._gl.disableVertexAttribArray(i);
  10497. this._vertexAttribArraysEnabled[i] = false;
  10498. this._currentBufferPointers[i] = null;
  10499. }
  10500. return;
  10501. }
  10502. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10503. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10504. continue;
  10505. }
  10506. this._gl.disableVertexAttribArray(i);
  10507. this._vertexAttribArraysEnabled[i] = false;
  10508. this._currentBufferPointers[i] = null;
  10509. }
  10510. };
  10511. // Dispose
  10512. Engine.prototype.dispose = function () {
  10513. this.hideLoadingUI();
  10514. this.stopRenderLoop();
  10515. // Release scenes
  10516. while (this.scenes.length) {
  10517. this.scenes[0].dispose();
  10518. }
  10519. // Release audio engine
  10520. Engine.audioEngine.dispose();
  10521. // Release effects
  10522. for (var name in this._compiledEffects) {
  10523. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10524. }
  10525. // Unbind
  10526. this.unbindAllAttributes();
  10527. this._gl = null;
  10528. //WebVR
  10529. this.disableVR();
  10530. // Events
  10531. window.removeEventListener("blur", this._onBlur);
  10532. window.removeEventListener("focus", this._onFocus);
  10533. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10534. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10535. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10536. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10537. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10538. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10539. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10540. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10541. // Remove from Instances
  10542. var index = Engine.Instances.indexOf(this);
  10543. if (index >= 0) {
  10544. Engine.Instances.splice(index, 1);
  10545. }
  10546. };
  10547. // Loading screen
  10548. Engine.prototype.displayLoadingUI = function () {
  10549. this._loadingScreen.displayLoadingUI();
  10550. };
  10551. Engine.prototype.hideLoadingUI = function () {
  10552. this._loadingScreen.hideLoadingUI();
  10553. };
  10554. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10555. get: function () {
  10556. return this._loadingScreen;
  10557. },
  10558. set: function (loadingScreen) {
  10559. this._loadingScreen = loadingScreen;
  10560. },
  10561. enumerable: true,
  10562. configurable: true
  10563. });
  10564. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10565. set: function (text) {
  10566. this._loadingScreen.loadingUIText = text;
  10567. },
  10568. enumerable: true,
  10569. configurable: true
  10570. });
  10571. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10572. set: function (color) {
  10573. this._loadingScreen.loadingUIBackgroundColor = color;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Engine.prototype.attachContextLostEvent = function (callback) {
  10579. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10580. };
  10581. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10582. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10583. };
  10584. Engine.prototype.getVertexShaderSource = function (program) {
  10585. var shaders = this._gl.getAttachedShaders(program);
  10586. return this._gl.getShaderSource(shaders[0]);
  10587. };
  10588. Engine.prototype.getFragmentShaderSource = function (program) {
  10589. var shaders = this._gl.getAttachedShaders(program);
  10590. return this._gl.getShaderSource(shaders[1]);
  10591. };
  10592. // FPS
  10593. Engine.prototype.getFps = function () {
  10594. return this.fps;
  10595. };
  10596. Engine.prototype.getDeltaTime = function () {
  10597. return this.deltaTime;
  10598. };
  10599. Engine.prototype._measureFps = function () {
  10600. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10601. var length = this.previousFramesDuration.length;
  10602. if (length >= 2) {
  10603. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10604. }
  10605. if (length >= this.fpsRange) {
  10606. if (length > this.fpsRange) {
  10607. this.previousFramesDuration.splice(0, 1);
  10608. length = this.previousFramesDuration.length;
  10609. }
  10610. var sum = 0;
  10611. for (var id = 0; id < length - 1; id++) {
  10612. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10613. }
  10614. this.fps = 1000.0 / (sum / (length - 1));
  10615. }
  10616. };
  10617. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10618. if (this._webGLVersion > 1) {
  10619. return this._caps.colorBufferFloat;
  10620. }
  10621. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10622. };
  10623. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10624. if (this._webGLVersion > 1) {
  10625. return this._caps.colorBufferFloat;
  10626. }
  10627. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10628. };
  10629. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10630. Engine.prototype._canRenderToFramebuffer = function (type) {
  10631. var gl = this._gl;
  10632. //clear existing errors
  10633. while (gl.getError() !== gl.NO_ERROR) { }
  10634. var successful = true;
  10635. var texture = gl.createTexture();
  10636. gl.bindTexture(gl.TEXTURE_2D, texture);
  10637. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10640. var fb = gl.createFramebuffer();
  10641. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10642. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10643. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10644. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10645. successful = successful && (gl.getError() === gl.NO_ERROR);
  10646. //try render by clearing frame buffer's color buffer
  10647. if (successful) {
  10648. gl.clear(gl.COLOR_BUFFER_BIT);
  10649. successful = successful && (gl.getError() === gl.NO_ERROR);
  10650. }
  10651. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10652. if (successful) {
  10653. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10654. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10655. var readFormat = gl.RGBA;
  10656. var readType = gl.UNSIGNED_BYTE;
  10657. var buffer = new Uint8Array(4);
  10658. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10659. successful = successful && (gl.getError() === gl.NO_ERROR);
  10660. }
  10661. //clean up
  10662. gl.deleteTexture(texture);
  10663. gl.deleteFramebuffer(fb);
  10664. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10665. //clear accumulated errors
  10666. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10667. return successful;
  10668. };
  10669. Engine.prototype._getWebGLTextureType = function (type) {
  10670. if (type === Engine.TEXTURETYPE_FLOAT) {
  10671. return this._gl.FLOAT;
  10672. }
  10673. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10674. // Add Half Float Constant.
  10675. return Engine.HALF_FLOAT_OES;
  10676. }
  10677. return this._gl.UNSIGNED_BYTE;
  10678. };
  10679. ;
  10680. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10681. if (this._webGLVersion === 1) {
  10682. return this._gl.RGBA;
  10683. }
  10684. if (type === Engine.TEXTURETYPE_FLOAT) {
  10685. return Engine.RGBA32F;
  10686. }
  10687. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10688. return Engine.RGBA16F;
  10689. }
  10690. return this._gl.RGBA;
  10691. };
  10692. ;
  10693. // Statics
  10694. Engine.isSupported = function () {
  10695. try {
  10696. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10697. if (navigator.isCocoonJS) {
  10698. return true;
  10699. }
  10700. var tempcanvas = document.createElement("canvas");
  10701. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10702. return gl != null && !!window.WebGLRenderingContext;
  10703. }
  10704. catch (e) {
  10705. return false;
  10706. }
  10707. };
  10708. return Engine;
  10709. }());
  10710. Engine.Instances = new Array();
  10711. // Const statics
  10712. Engine._ALPHA_DISABLE = 0;
  10713. Engine._ALPHA_ADD = 1;
  10714. Engine._ALPHA_COMBINE = 2;
  10715. Engine._ALPHA_SUBTRACT = 3;
  10716. Engine._ALPHA_MULTIPLY = 4;
  10717. Engine._ALPHA_MAXIMIZED = 5;
  10718. Engine._ALPHA_ONEONE = 6;
  10719. Engine._ALPHA_PREMULTIPLIED = 7;
  10720. Engine._DELAYLOADSTATE_NONE = 0;
  10721. Engine._DELAYLOADSTATE_LOADED = 1;
  10722. Engine._DELAYLOADSTATE_LOADING = 2;
  10723. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10724. Engine._TEXTUREFORMAT_ALPHA = 0;
  10725. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10726. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10727. Engine._TEXTUREFORMAT_RGB = 4;
  10728. Engine._TEXTUREFORMAT_RGBA = 5;
  10729. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10730. Engine._TEXTURETYPE_FLOAT = 1;
  10731. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10732. // Depht or Stencil test Constants.
  10733. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10734. 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.
  10735. 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.
  10736. 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.
  10737. 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.
  10738. 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.
  10739. 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.
  10740. 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.
  10741. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10742. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10743. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10744. // Stencil Actions Constants.
  10745. Engine._KEEP = 0x1E00;
  10746. Engine._REPLACE = 0x1E01;
  10747. Engine._INCR = 0x1E02;
  10748. Engine._DECR = 0x1E03;
  10749. Engine._INVERT = 0x150A;
  10750. Engine._INCR_WRAP = 0x8507;
  10751. Engine._DECR_WRAP = 0x8508;
  10752. // Updatable statics so stick with vars here
  10753. Engine.CollisionsEpsilon = 0.001;
  10754. Engine.CodeRepository = "src/";
  10755. Engine.ShadersRepository = "src/Shaders/";
  10756. BABYLON.Engine = Engine;
  10757. })(BABYLON || (BABYLON = {}));
  10758. //# sourceMappingURL=babylon.engine.js.map
  10759. /// <reference path="Tools\babylon.decorators.ts" />
  10760. var BABYLON;
  10761. (function (BABYLON) {
  10762. /**
  10763. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10764. */
  10765. var Node = (function () {
  10766. /**
  10767. * @constructor
  10768. * @param {string} name - the name and id to be given to this node
  10769. * @param {BABYLON.Scene} the scene this node will be added to
  10770. */
  10771. function Node(name, scene) {
  10772. this.state = "";
  10773. this.metadata = null;
  10774. this.doNotSerialize = false;
  10775. this.animations = new Array();
  10776. this._ranges = {};
  10777. this._childrenFlag = -1;
  10778. this._isEnabled = true;
  10779. this._isReady = true;
  10780. this._currentRenderId = -1;
  10781. this._parentRenderId = -1;
  10782. /**
  10783. * An event triggered when the mesh is disposed.
  10784. * @type {BABYLON.Observable}
  10785. */
  10786. this.onDisposeObservable = new BABYLON.Observable();
  10787. this.name = name;
  10788. this.id = name;
  10789. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10790. this._initCache();
  10791. }
  10792. Object.defineProperty(Node.prototype, "parent", {
  10793. get: function () {
  10794. return this._parentNode;
  10795. },
  10796. set: function (parent) {
  10797. if (this._parentNode === parent) {
  10798. return;
  10799. }
  10800. if (this._parentNode) {
  10801. var index = this._parentNode._children.indexOf(this);
  10802. if (index !== -1) {
  10803. this._parentNode._children.splice(index, 1);
  10804. }
  10805. }
  10806. this._parentNode = parent;
  10807. if (this._parentNode) {
  10808. if (!this._parentNode._children) {
  10809. this._parentNode._children = new Array();
  10810. }
  10811. this._parentNode._children.push(this);
  10812. }
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Node.prototype.getClassName = function () {
  10818. return "Node";
  10819. };
  10820. Object.defineProperty(Node.prototype, "onDispose", {
  10821. set: function (callback) {
  10822. if (this._onDisposeObserver) {
  10823. this.onDisposeObservable.remove(this._onDisposeObserver);
  10824. }
  10825. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Node.prototype.getScene = function () {
  10831. return this._scene;
  10832. };
  10833. Node.prototype.getEngine = function () {
  10834. return this._scene.getEngine();
  10835. };
  10836. // override it in derived class
  10837. Node.prototype.getWorldMatrix = function () {
  10838. return BABYLON.Matrix.Identity();
  10839. };
  10840. // override it in derived class if you add new variables to the cache
  10841. // and call the parent class method
  10842. Node.prototype._initCache = function () {
  10843. this._cache = {};
  10844. this._cache.parent = undefined;
  10845. };
  10846. Node.prototype.updateCache = function (force) {
  10847. if (!force && this.isSynchronized())
  10848. return;
  10849. this._cache.parent = this.parent;
  10850. this._updateCache();
  10851. };
  10852. // override it in derived class if you add new variables to the cache
  10853. // and call the parent class method if !ignoreParentClass
  10854. Node.prototype._updateCache = function (ignoreParentClass) {
  10855. };
  10856. // override it in derived class if you add new variables to the cache
  10857. Node.prototype._isSynchronized = function () {
  10858. return true;
  10859. };
  10860. Node.prototype._markSyncedWithParent = function () {
  10861. this._parentRenderId = this.parent._currentRenderId;
  10862. };
  10863. Node.prototype.isSynchronizedWithParent = function () {
  10864. if (!this.parent) {
  10865. return true;
  10866. }
  10867. if (this._parentRenderId !== this.parent._currentRenderId) {
  10868. return false;
  10869. }
  10870. return this.parent.isSynchronized();
  10871. };
  10872. Node.prototype.isSynchronized = function (updateCache) {
  10873. var check = this.hasNewParent();
  10874. check = check || !this.isSynchronizedWithParent();
  10875. check = check || !this._isSynchronized();
  10876. if (updateCache)
  10877. this.updateCache(true);
  10878. return !check;
  10879. };
  10880. Node.prototype.hasNewParent = function (update) {
  10881. if (this._cache.parent === this.parent)
  10882. return false;
  10883. if (update)
  10884. this._cache.parent = this.parent;
  10885. return true;
  10886. };
  10887. /**
  10888. * Is this node ready to be used/rendered
  10889. * @return {boolean} is it ready
  10890. */
  10891. Node.prototype.isReady = function () {
  10892. return this._isReady;
  10893. };
  10894. /**
  10895. * Is this node enabled.
  10896. * If the node has a parent and is enabled, the parent will be inspected as well.
  10897. * @return {boolean} whether this node (and its parent) is enabled.
  10898. * @see setEnabled
  10899. */
  10900. Node.prototype.isEnabled = function () {
  10901. if (!this._isEnabled) {
  10902. return false;
  10903. }
  10904. if (this.parent) {
  10905. return this.parent.isEnabled();
  10906. }
  10907. return true;
  10908. };
  10909. /**
  10910. * Set the enabled state of this node.
  10911. * @param {boolean} value - the new enabled state
  10912. * @see isEnabled
  10913. */
  10914. Node.prototype.setEnabled = function (value) {
  10915. this._isEnabled = value;
  10916. };
  10917. /**
  10918. * Is this node a descendant of the given node.
  10919. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10920. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10921. * @see parent
  10922. */
  10923. Node.prototype.isDescendantOf = function (ancestor) {
  10924. if (this.parent) {
  10925. if (this.parent === ancestor) {
  10926. return true;
  10927. }
  10928. return this.parent.isDescendantOf(ancestor);
  10929. }
  10930. return false;
  10931. };
  10932. /**
  10933. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10934. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10935. * @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.
  10936. * @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.
  10937. */
  10938. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10939. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10940. if (!this._children) {
  10941. return;
  10942. }
  10943. for (var index = 0; index < this._children.length; index++) {
  10944. var item = this._children[index];
  10945. if (!predicate || predicate(item)) {
  10946. results.push(item);
  10947. }
  10948. if (!directDescendantsOnly) {
  10949. item._getDescendants(results, false, predicate);
  10950. }
  10951. }
  10952. };
  10953. /**
  10954. * Will return all nodes that have this node as ascendant.
  10955. * @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.
  10956. * @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.
  10957. * @return {BABYLON.Node[]} all children nodes of all types.
  10958. */
  10959. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10960. var results = [];
  10961. this._getDescendants(results, directDescendantsOnly, predicate);
  10962. return results;
  10963. };
  10964. /**
  10965. * Get all child-meshes of this node.
  10966. */
  10967. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10968. var results = [];
  10969. this._getDescendants(results, directDecendantsOnly, function (node) {
  10970. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10971. });
  10972. return results;
  10973. };
  10974. /**
  10975. * Get all direct children of this node.
  10976. */
  10977. Node.prototype.getChildren = function (predicate) {
  10978. return this.getDescendants(true, predicate);
  10979. };
  10980. Node.prototype._setReady = function (state) {
  10981. if (state === this._isReady) {
  10982. return;
  10983. }
  10984. if (!state) {
  10985. this._isReady = false;
  10986. return;
  10987. }
  10988. this._isReady = true;
  10989. if (this.onReady) {
  10990. this.onReady(this);
  10991. }
  10992. };
  10993. Node.prototype.getAnimationByName = function (name) {
  10994. for (var i = 0; i < this.animations.length; i++) {
  10995. var animation = this.animations[i];
  10996. if (animation.name === name) {
  10997. return animation;
  10998. }
  10999. }
  11000. return null;
  11001. };
  11002. Node.prototype.createAnimationRange = function (name, from, to) {
  11003. // check name not already in use
  11004. if (!this._ranges[name]) {
  11005. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11006. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11007. if (this.animations[i]) {
  11008. this.animations[i].createRange(name, from, to);
  11009. }
  11010. }
  11011. }
  11012. };
  11013. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11014. if (deleteFrames === void 0) { deleteFrames = true; }
  11015. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11016. if (this.animations[i]) {
  11017. this.animations[i].deleteRange(name, deleteFrames);
  11018. }
  11019. }
  11020. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11021. };
  11022. Node.prototype.getAnimationRange = function (name) {
  11023. return this._ranges[name];
  11024. };
  11025. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11026. var range = this.getAnimationRange(name);
  11027. if (!range) {
  11028. return null;
  11029. }
  11030. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11031. };
  11032. Node.prototype.serializeAnimationRanges = function () {
  11033. var serializationRanges = [];
  11034. for (var name in this._ranges) {
  11035. var range = {};
  11036. range.name = name;
  11037. range.from = this._ranges[name].from;
  11038. range.to = this._ranges[name].to;
  11039. serializationRanges.push(range);
  11040. }
  11041. return serializationRanges;
  11042. };
  11043. Node.prototype.dispose = function () {
  11044. this.parent = null;
  11045. // Callback
  11046. this.onDisposeObservable.notifyObservers(this);
  11047. this.onDisposeObservable.clear();
  11048. };
  11049. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11050. if (parsedNode.ranges) {
  11051. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11052. var data = parsedNode.ranges[index];
  11053. node.createAnimationRange(data.name, data.from, data.to);
  11054. }
  11055. }
  11056. };
  11057. return Node;
  11058. }());
  11059. __decorate([
  11060. BABYLON.serialize()
  11061. ], Node.prototype, "name", void 0);
  11062. __decorate([
  11063. BABYLON.serialize()
  11064. ], Node.prototype, "id", void 0);
  11065. __decorate([
  11066. BABYLON.serialize()
  11067. ], Node.prototype, "uniqueId", void 0);
  11068. __decorate([
  11069. BABYLON.serialize()
  11070. ], Node.prototype, "state", void 0);
  11071. __decorate([
  11072. BABYLON.serialize()
  11073. ], Node.prototype, "metadata", void 0);
  11074. BABYLON.Node = Node;
  11075. })(BABYLON || (BABYLON = {}));
  11076. //# sourceMappingURL=babylon.node.js.map
  11077. var BABYLON;
  11078. (function (BABYLON) {
  11079. var FilesInput = (function () {
  11080. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11081. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11082. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11083. this._engine = p_engine;
  11084. this._canvas = p_canvas;
  11085. this._currentScene = p_scene;
  11086. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11087. this._progressCallback = p_progressCallback;
  11088. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11089. this._textureLoadingCallback = p_textureLoadingCallback;
  11090. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11091. }
  11092. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11093. var _this = this;
  11094. if (p_elementToMonitor) {
  11095. this._elementToMonitor = p_elementToMonitor;
  11096. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11097. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11098. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11099. }
  11100. };
  11101. FilesInput.prototype.renderFunction = function () {
  11102. if (this._additionnalRenderLoopLogicCallback) {
  11103. this._additionnalRenderLoopLogicCallback();
  11104. }
  11105. if (this._currentScene) {
  11106. if (this._textureLoadingCallback) {
  11107. var remaining = this._currentScene.getWaitingItemsCount();
  11108. if (remaining > 0) {
  11109. this._textureLoadingCallback(remaining);
  11110. }
  11111. }
  11112. this._currentScene.render();
  11113. }
  11114. };
  11115. FilesInput.prototype.drag = function (e) {
  11116. e.stopPropagation();
  11117. e.preventDefault();
  11118. };
  11119. FilesInput.prototype.drop = function (eventDrop) {
  11120. eventDrop.stopPropagation();
  11121. eventDrop.preventDefault();
  11122. this.loadFiles(eventDrop);
  11123. };
  11124. FilesInput.prototype.loadFiles = function (event) {
  11125. if (this._startingProcessingFilesCallback)
  11126. this._startingProcessingFilesCallback();
  11127. // Handling data transfer via drag'n'drop
  11128. if (event && event.dataTransfer && event.dataTransfer.files) {
  11129. this._filesToLoad = event.dataTransfer.files;
  11130. }
  11131. // Handling files from input files
  11132. if (event && event.target && event.target.files) {
  11133. this._filesToLoad = event.target.files;
  11134. }
  11135. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11136. for (var i = 0; i < this._filesToLoad.length; i++) {
  11137. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11138. var extension = name_1.split('.').pop();
  11139. var type = this._filesToLoad[i].type;
  11140. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11141. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11142. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11143. }
  11144. else {
  11145. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11146. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11147. this._sceneFileToLoad = this._filesToLoad[i];
  11148. }
  11149. else {
  11150. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11151. }
  11152. }
  11153. }
  11154. this.reload();
  11155. }
  11156. };
  11157. FilesInput.prototype.reload = function () {
  11158. var _this = this;
  11159. var that = this;
  11160. // If a ".babylon" file has been provided
  11161. if (this._sceneFileToLoad) {
  11162. if (this._currentScene) {
  11163. if (BABYLON.Tools.errorsCount > 0) {
  11164. BABYLON.Tools.ClearLogCache();
  11165. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11166. }
  11167. this._engine.stopRenderLoop();
  11168. this._currentScene.dispose();
  11169. }
  11170. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11171. that._currentScene = newScene;
  11172. // Wait for textures and shaders to be ready
  11173. that._currentScene.executeWhenReady(function () {
  11174. // Attach camera to canvas inputs
  11175. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11176. that._currentScene.createDefaultCameraOrLight();
  11177. }
  11178. that._currentScene.activeCamera.attachControl(that._canvas);
  11179. if (that._sceneLoadedCallback) {
  11180. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11181. }
  11182. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11183. });
  11184. }, function (progress) {
  11185. if (_this._progressCallback) {
  11186. _this._progressCallback(progress);
  11187. }
  11188. });
  11189. }
  11190. else {
  11191. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11192. }
  11193. };
  11194. return FilesInput;
  11195. }());
  11196. FilesInput.FilesTextures = new Array();
  11197. FilesInput.FilesToLoad = new Array();
  11198. BABYLON.FilesInput = FilesInput;
  11199. })(BABYLON || (BABYLON = {}));
  11200. //# sourceMappingURL=babylon.filesInput.js.map
  11201. var BABYLON;
  11202. (function (BABYLON) {
  11203. var IntersectionInfo = (function () {
  11204. function IntersectionInfo(bu, bv, distance) {
  11205. this.bu = bu;
  11206. this.bv = bv;
  11207. this.distance = distance;
  11208. this.faceId = 0;
  11209. this.subMeshId = 0;
  11210. }
  11211. return IntersectionInfo;
  11212. }());
  11213. BABYLON.IntersectionInfo = IntersectionInfo;
  11214. var PickingInfo = (function () {
  11215. function PickingInfo() {
  11216. this.hit = false;
  11217. this.distance = 0;
  11218. this.pickedPoint = null;
  11219. this.pickedMesh = null;
  11220. this.bu = 0;
  11221. this.bv = 0;
  11222. this.faceId = -1;
  11223. this.subMeshId = 0;
  11224. this.pickedSprite = null;
  11225. }
  11226. // Methods
  11227. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11228. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11229. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11230. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11231. return null;
  11232. }
  11233. var indices = this.pickedMesh.getIndices();
  11234. var result;
  11235. if (useVerticesNormals) {
  11236. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11237. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11238. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11239. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11240. normal0 = normal0.scale(this.bu);
  11241. normal1 = normal1.scale(this.bv);
  11242. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11243. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11244. }
  11245. else {
  11246. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11247. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11248. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11249. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11250. var p1p2 = vertex1.subtract(vertex2);
  11251. var p3p2 = vertex3.subtract(vertex2);
  11252. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11253. }
  11254. if (useWorldCoordinates) {
  11255. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11256. }
  11257. return BABYLON.Vector3.Normalize(result);
  11258. };
  11259. PickingInfo.prototype.getTextureCoordinates = function () {
  11260. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11261. return null;
  11262. }
  11263. var indices = this.pickedMesh.getIndices();
  11264. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11265. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11266. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11267. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11268. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11269. uv1 = uv1.scale(this.bu);
  11270. uv2 = uv2.scale(this.bv);
  11271. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11272. };
  11273. return PickingInfo;
  11274. }());
  11275. BABYLON.PickingInfo = PickingInfo;
  11276. })(BABYLON || (BABYLON = {}));
  11277. //# sourceMappingURL=babylon.pickingInfo.js.map
  11278. var BABYLON;
  11279. (function (BABYLON) {
  11280. var BoundingSphere = (function () {
  11281. function BoundingSphere(minimum, maximum) {
  11282. this.minimum = minimum;
  11283. this.maximum = maximum;
  11284. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11285. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11286. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11287. this.radius = distance * 0.5;
  11288. this.centerWorld = BABYLON.Vector3.Zero();
  11289. this._update(BABYLON.Matrix.Identity());
  11290. }
  11291. // Methods
  11292. BoundingSphere.prototype._update = function (world) {
  11293. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11294. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11295. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11296. };
  11297. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11298. for (var i = 0; i < 6; i++) {
  11299. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11300. return false;
  11301. }
  11302. return true;
  11303. };
  11304. BoundingSphere.prototype.intersectsPoint = function (point) {
  11305. var x = this.centerWorld.x - point.x;
  11306. var y = this.centerWorld.y - point.y;
  11307. var z = this.centerWorld.z - point.z;
  11308. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11309. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11310. return false;
  11311. return true;
  11312. };
  11313. // Statics
  11314. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11315. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11316. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11317. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11318. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11319. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11320. return false;
  11321. return true;
  11322. };
  11323. return BoundingSphere;
  11324. }());
  11325. BABYLON.BoundingSphere = BoundingSphere;
  11326. })(BABYLON || (BABYLON = {}));
  11327. //# sourceMappingURL=babylon.boundingSphere.js.map
  11328. var BABYLON;
  11329. (function (BABYLON) {
  11330. var BoundingBox = (function () {
  11331. function BoundingBox(minimum, maximum) {
  11332. this.minimum = minimum;
  11333. this.maximum = maximum;
  11334. this.vectors = new Array();
  11335. this.vectorsWorld = new Array();
  11336. // Bounding vectors
  11337. this.vectors.push(this.minimum.clone());
  11338. this.vectors.push(this.maximum.clone());
  11339. this.vectors.push(this.minimum.clone());
  11340. this.vectors[2].x = this.maximum.x;
  11341. this.vectors.push(this.minimum.clone());
  11342. this.vectors[3].y = this.maximum.y;
  11343. this.vectors.push(this.minimum.clone());
  11344. this.vectors[4].z = this.maximum.z;
  11345. this.vectors.push(this.maximum.clone());
  11346. this.vectors[5].z = this.minimum.z;
  11347. this.vectors.push(this.maximum.clone());
  11348. this.vectors[6].x = this.minimum.x;
  11349. this.vectors.push(this.maximum.clone());
  11350. this.vectors[7].y = this.minimum.y;
  11351. // OBB
  11352. this.center = this.maximum.add(this.minimum).scale(0.5);
  11353. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11354. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11355. // World
  11356. for (var index = 0; index < this.vectors.length; index++) {
  11357. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11358. }
  11359. this.minimumWorld = BABYLON.Vector3.Zero();
  11360. this.maximumWorld = BABYLON.Vector3.Zero();
  11361. this.centerWorld = BABYLON.Vector3.Zero();
  11362. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11363. this._update(BABYLON.Matrix.Identity());
  11364. }
  11365. // Methods
  11366. BoundingBox.prototype.getWorldMatrix = function () {
  11367. return this._worldMatrix;
  11368. };
  11369. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11370. this._worldMatrix.copyFrom(matrix);
  11371. return this;
  11372. };
  11373. BoundingBox.prototype._update = function (world) {
  11374. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11375. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11376. for (var index = 0; index < this.vectors.length; index++) {
  11377. var v = this.vectorsWorld[index];
  11378. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11379. if (v.x < this.minimumWorld.x)
  11380. this.minimumWorld.x = v.x;
  11381. if (v.y < this.minimumWorld.y)
  11382. this.minimumWorld.y = v.y;
  11383. if (v.z < this.minimumWorld.z)
  11384. this.minimumWorld.z = v.z;
  11385. if (v.x > this.maximumWorld.x)
  11386. this.maximumWorld.x = v.x;
  11387. if (v.y > this.maximumWorld.y)
  11388. this.maximumWorld.y = v.y;
  11389. if (v.z > this.maximumWorld.z)
  11390. this.maximumWorld.z = v.z;
  11391. }
  11392. // Extend
  11393. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11394. this.extendSizeWorld.scaleInPlace(0.5);
  11395. // OBB
  11396. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11397. this.centerWorld.scaleInPlace(0.5);
  11398. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11399. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11400. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11401. this._worldMatrix = world;
  11402. };
  11403. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11404. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11405. };
  11406. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11407. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11408. };
  11409. BoundingBox.prototype.intersectsPoint = function (point) {
  11410. var delta = -BABYLON.Epsilon;
  11411. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11412. return false;
  11413. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11414. return false;
  11415. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11416. return false;
  11417. return true;
  11418. };
  11419. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11420. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11421. };
  11422. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11423. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11424. return false;
  11425. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11426. return false;
  11427. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11428. return false;
  11429. return true;
  11430. };
  11431. // Statics
  11432. BoundingBox.Intersects = function (box0, box1) {
  11433. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11434. return false;
  11435. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11436. return false;
  11437. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11438. return false;
  11439. return true;
  11440. };
  11441. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11442. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11443. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11444. return (num <= (sphereRadius * sphereRadius));
  11445. };
  11446. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11447. for (var p = 0; p < 6; p++) {
  11448. for (var i = 0; i < 8; i++) {
  11449. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11450. return false;
  11451. }
  11452. }
  11453. }
  11454. return true;
  11455. };
  11456. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11457. for (var p = 0; p < 6; p++) {
  11458. var inCount = 8;
  11459. for (var i = 0; i < 8; i++) {
  11460. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11461. --inCount;
  11462. }
  11463. else {
  11464. break;
  11465. }
  11466. }
  11467. if (inCount === 0)
  11468. return false;
  11469. }
  11470. return true;
  11471. };
  11472. return BoundingBox;
  11473. }());
  11474. BABYLON.BoundingBox = BoundingBox;
  11475. })(BABYLON || (BABYLON = {}));
  11476. //# sourceMappingURL=babylon.boundingBox.js.map
  11477. var BABYLON;
  11478. (function (BABYLON) {
  11479. var computeBoxExtents = function (axis, box) {
  11480. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11481. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11482. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11483. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11484. var r = r0 + r1 + r2;
  11485. return {
  11486. min: p - r,
  11487. max: p + r
  11488. };
  11489. };
  11490. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11491. var axisOverlap = function (axis, box0, box1) {
  11492. var result0 = computeBoxExtents(axis, box0);
  11493. var result1 = computeBoxExtents(axis, box1);
  11494. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11495. };
  11496. var BoundingInfo = (function () {
  11497. function BoundingInfo(minimum, maximum) {
  11498. this.minimum = minimum;
  11499. this.maximum = maximum;
  11500. this._isLocked = false;
  11501. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11502. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11503. }
  11504. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11505. get: function () {
  11506. return this._isLocked;
  11507. },
  11508. set: function (value) {
  11509. this._isLocked = value;
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. // Methods
  11515. BoundingInfo.prototype.update = function (world) {
  11516. if (this._isLocked) {
  11517. return;
  11518. }
  11519. this.boundingBox._update(world);
  11520. this.boundingSphere._update(world);
  11521. };
  11522. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11523. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11524. return false;
  11525. return this.boundingBox.isInFrustum(frustumPlanes);
  11526. };
  11527. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11528. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11529. };
  11530. BoundingInfo.prototype._checkCollision = function (collider) {
  11531. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11532. };
  11533. BoundingInfo.prototype.intersectsPoint = function (point) {
  11534. if (!this.boundingSphere.centerWorld) {
  11535. return false;
  11536. }
  11537. if (!this.boundingSphere.intersectsPoint(point)) {
  11538. return false;
  11539. }
  11540. if (!this.boundingBox.intersectsPoint(point)) {
  11541. return false;
  11542. }
  11543. return true;
  11544. };
  11545. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11546. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11547. return false;
  11548. }
  11549. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11550. return false;
  11551. }
  11552. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11553. return false;
  11554. }
  11555. if (!precise) {
  11556. return true;
  11557. }
  11558. var box0 = this.boundingBox;
  11559. var box1 = boundingInfo.boundingBox;
  11560. if (!axisOverlap(box0.directions[0], box0, box1))
  11561. return false;
  11562. if (!axisOverlap(box0.directions[1], box0, box1))
  11563. return false;
  11564. if (!axisOverlap(box0.directions[2], box0, box1))
  11565. return false;
  11566. if (!axisOverlap(box1.directions[0], box0, box1))
  11567. return false;
  11568. if (!axisOverlap(box1.directions[1], box0, box1))
  11569. return false;
  11570. if (!axisOverlap(box1.directions[2], box0, box1))
  11571. return false;
  11572. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11573. return false;
  11574. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11575. return false;
  11576. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11577. return false;
  11578. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11579. return false;
  11580. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11581. return false;
  11582. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11583. return false;
  11584. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11585. return false;
  11586. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11587. return false;
  11588. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11589. return false;
  11590. return true;
  11591. };
  11592. return BoundingInfo;
  11593. }());
  11594. BABYLON.BoundingInfo = BoundingInfo;
  11595. })(BABYLON || (BABYLON = {}));
  11596. //# sourceMappingURL=babylon.boundingInfo.js.map
  11597. var BABYLON;
  11598. (function (BABYLON) {
  11599. var Ray = (function () {
  11600. function Ray(origin, direction, length) {
  11601. if (length === void 0) { length = Number.MAX_VALUE; }
  11602. this.origin = origin;
  11603. this.direction = direction;
  11604. this.length = length;
  11605. }
  11606. // Methods
  11607. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11608. var d = 0.0;
  11609. var maxValue = Number.MAX_VALUE;
  11610. var inv;
  11611. var min;
  11612. var max;
  11613. var temp;
  11614. if (Math.abs(this.direction.x) < 0.0000001) {
  11615. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11616. return false;
  11617. }
  11618. }
  11619. else {
  11620. inv = 1.0 / this.direction.x;
  11621. min = (minimum.x - this.origin.x) * inv;
  11622. max = (maximum.x - this.origin.x) * inv;
  11623. if (max === -Infinity) {
  11624. max = Infinity;
  11625. }
  11626. if (min > max) {
  11627. temp = min;
  11628. min = max;
  11629. max = temp;
  11630. }
  11631. d = Math.max(min, d);
  11632. maxValue = Math.min(max, maxValue);
  11633. if (d > maxValue) {
  11634. return false;
  11635. }
  11636. }
  11637. if (Math.abs(this.direction.y) < 0.0000001) {
  11638. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11639. return false;
  11640. }
  11641. }
  11642. else {
  11643. inv = 1.0 / this.direction.y;
  11644. min = (minimum.y - this.origin.y) * inv;
  11645. max = (maximum.y - this.origin.y) * inv;
  11646. if (max === -Infinity) {
  11647. max = Infinity;
  11648. }
  11649. if (min > max) {
  11650. temp = min;
  11651. min = max;
  11652. max = temp;
  11653. }
  11654. d = Math.max(min, d);
  11655. maxValue = Math.min(max, maxValue);
  11656. if (d > maxValue) {
  11657. return false;
  11658. }
  11659. }
  11660. if (Math.abs(this.direction.z) < 0.0000001) {
  11661. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11662. return false;
  11663. }
  11664. }
  11665. else {
  11666. inv = 1.0 / this.direction.z;
  11667. min = (minimum.z - this.origin.z) * inv;
  11668. max = (maximum.z - this.origin.z) * inv;
  11669. if (max === -Infinity) {
  11670. max = Infinity;
  11671. }
  11672. if (min > max) {
  11673. temp = min;
  11674. min = max;
  11675. max = temp;
  11676. }
  11677. d = Math.max(min, d);
  11678. maxValue = Math.min(max, maxValue);
  11679. if (d > maxValue) {
  11680. return false;
  11681. }
  11682. }
  11683. return true;
  11684. };
  11685. Ray.prototype.intersectsBox = function (box) {
  11686. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11687. };
  11688. Ray.prototype.intersectsSphere = function (sphere) {
  11689. var x = sphere.center.x - this.origin.x;
  11690. var y = sphere.center.y - this.origin.y;
  11691. var z = sphere.center.z - this.origin.z;
  11692. var pyth = (x * x) + (y * y) + (z * z);
  11693. var rr = sphere.radius * sphere.radius;
  11694. if (pyth <= rr) {
  11695. return true;
  11696. }
  11697. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11698. if (dot < 0.0) {
  11699. return false;
  11700. }
  11701. var temp = pyth - (dot * dot);
  11702. return temp <= rr;
  11703. };
  11704. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11705. if (!this._edge1) {
  11706. this._edge1 = BABYLON.Vector3.Zero();
  11707. this._edge2 = BABYLON.Vector3.Zero();
  11708. this._pvec = BABYLON.Vector3.Zero();
  11709. this._tvec = BABYLON.Vector3.Zero();
  11710. this._qvec = BABYLON.Vector3.Zero();
  11711. }
  11712. vertex1.subtractToRef(vertex0, this._edge1);
  11713. vertex2.subtractToRef(vertex0, this._edge2);
  11714. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11715. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11716. if (det === 0) {
  11717. return null;
  11718. }
  11719. var invdet = 1 / det;
  11720. this.origin.subtractToRef(vertex0, this._tvec);
  11721. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11722. if (bu < 0 || bu > 1.0) {
  11723. return null;
  11724. }
  11725. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11726. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11727. if (bv < 0 || bu + bv > 1.0) {
  11728. return null;
  11729. }
  11730. //check if the distance is longer than the predefined length.
  11731. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11732. if (distance > this.length) {
  11733. return null;
  11734. }
  11735. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11736. };
  11737. Ray.prototype.intersectsPlane = function (plane) {
  11738. var distance;
  11739. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11740. if (Math.abs(result1) < 9.99999997475243E-07) {
  11741. return null;
  11742. }
  11743. else {
  11744. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11745. distance = (-plane.d - result2) / result1;
  11746. if (distance < 0.0) {
  11747. if (distance < -9.99999997475243E-07) {
  11748. return null;
  11749. }
  11750. else {
  11751. return 0;
  11752. }
  11753. }
  11754. return distance;
  11755. }
  11756. };
  11757. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11758. var tm = BABYLON.Tmp.Matrix[0];
  11759. mesh.getWorldMatrix().invertToRef(tm);
  11760. if (this._tmpRay) {
  11761. Ray.TransformToRef(this, tm, this._tmpRay);
  11762. }
  11763. else {
  11764. this._tmpRay = Ray.Transform(this, tm);
  11765. }
  11766. return mesh.intersects(this._tmpRay, fastCheck);
  11767. };
  11768. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11769. if (results) {
  11770. results.length = 0;
  11771. }
  11772. else {
  11773. results = [];
  11774. }
  11775. for (var i = 0; i < meshes.length; i++) {
  11776. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11777. if (pickInfo.hit) {
  11778. results.push(pickInfo);
  11779. }
  11780. }
  11781. results.sort(this._comparePickingInfo);
  11782. return results;
  11783. };
  11784. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11785. if (pickingInfoA.distance < pickingInfoB.distance) {
  11786. return -1;
  11787. }
  11788. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11789. return 1;
  11790. }
  11791. else {
  11792. return 0;
  11793. }
  11794. };
  11795. /**
  11796. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11797. * @param sega the first point of the segment to test the intersection against
  11798. * @param segb the second point of the segment to test the intersection against
  11799. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11800. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11801. */
  11802. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11803. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11804. var u = segb.subtract(sega);
  11805. var v = rsegb.subtract(this.origin);
  11806. var w = sega.subtract(this.origin);
  11807. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11808. var b = BABYLON.Vector3.Dot(u, v);
  11809. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11810. var d = BABYLON.Vector3.Dot(u, w);
  11811. var e = BABYLON.Vector3.Dot(v, w);
  11812. var D = a * c - b * b; // always >= 0
  11813. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11814. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11815. // compute the line parameters of the two closest points
  11816. if (D < Ray.smallnum) {
  11817. sN = 0.0; // force using point P0 on segment S1
  11818. sD = 1.0; // to prevent possible division by 0.0 later
  11819. tN = e;
  11820. tD = c;
  11821. }
  11822. else {
  11823. sN = (b * e - c * d);
  11824. tN = (a * e - b * d);
  11825. if (sN < 0.0) {
  11826. sN = 0.0;
  11827. tN = e;
  11828. tD = c;
  11829. }
  11830. else if (sN > sD) {
  11831. sN = sD;
  11832. tN = e + b;
  11833. tD = c;
  11834. }
  11835. }
  11836. if (tN < 0.0) {
  11837. tN = 0.0;
  11838. // recompute sc for this edge
  11839. if (-d < 0.0) {
  11840. sN = 0.0;
  11841. }
  11842. else if (-d > a)
  11843. sN = sD;
  11844. else {
  11845. sN = -d;
  11846. sD = a;
  11847. }
  11848. }
  11849. else if (tN > tD) {
  11850. tN = tD;
  11851. // recompute sc for this edge
  11852. if ((-d + b) < 0.0) {
  11853. sN = 0;
  11854. }
  11855. else if ((-d + b) > a) {
  11856. sN = sD;
  11857. }
  11858. else {
  11859. sN = (-d + b);
  11860. sD = a;
  11861. }
  11862. }
  11863. // finally do the division to get sc and tc
  11864. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11865. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11866. // get the difference of the two closest points
  11867. var qtc = v.multiplyByFloats(tc, tc, tc);
  11868. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11869. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11870. if (isIntersected) {
  11871. return qtc.length();
  11872. }
  11873. return -1;
  11874. };
  11875. // Statics
  11876. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11877. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11878. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11879. var direction = end.subtract(start);
  11880. direction.normalize();
  11881. return new Ray(start, direction);
  11882. };
  11883. /**
  11884. * 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
  11885. * transformed to the given world matrix.
  11886. * @param origin The origin point
  11887. * @param end The end point
  11888. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11889. */
  11890. Ray.CreateNewFromTo = function (origin, end, world) {
  11891. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11892. var direction = end.subtract(origin);
  11893. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11894. direction.normalize();
  11895. return Ray.Transform(new Ray(origin, direction, length), world);
  11896. };
  11897. Ray.Transform = function (ray, matrix) {
  11898. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11899. Ray.TransformToRef(ray, matrix, result);
  11900. return result;
  11901. };
  11902. Ray.TransformToRef = function (ray, matrix, result) {
  11903. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11904. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11905. result.length = ray.length;
  11906. var dir = result.direction;
  11907. var len = dir.length();
  11908. if (!(len === 0 || len === 1)) {
  11909. var num = 1.0 / len;
  11910. dir.x *= num;
  11911. dir.y *= num;
  11912. dir.z *= num;
  11913. result.length *= len;
  11914. }
  11915. };
  11916. return Ray;
  11917. }());
  11918. Ray.smallnum = 0.00000001;
  11919. Ray.rayl = 10e8;
  11920. BABYLON.Ray = Ray;
  11921. })(BABYLON || (BABYLON = {}));
  11922. //# sourceMappingURL=babylon.ray.js.map
  11923. var BABYLON;
  11924. (function (BABYLON) {
  11925. var RayHelper = (function () {
  11926. function RayHelper(ray) {
  11927. this.ray = ray;
  11928. }
  11929. RayHelper.CreateAndShow = function (ray, scene, color) {
  11930. var helper = new RayHelper(ray);
  11931. helper.show(scene, color);
  11932. return helper;
  11933. };
  11934. RayHelper.prototype.show = function (scene, color) {
  11935. if (!this._renderFunction) {
  11936. var ray = this.ray;
  11937. this._renderFunction = this._render.bind(this);
  11938. this._scene = scene;
  11939. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11940. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11941. this._scene.registerBeforeRender(this._renderFunction);
  11942. }
  11943. if (color) {
  11944. this._renderLine.color.copyFrom(color);
  11945. }
  11946. };
  11947. RayHelper.prototype.hide = function () {
  11948. if (this._renderFunction) {
  11949. this._scene.unregisterBeforeRender(this._renderFunction);
  11950. this._scene = null;
  11951. this._renderFunction = null;
  11952. this._renderLine.dispose();
  11953. this._renderLine = null;
  11954. this._renderPoints = null;
  11955. }
  11956. };
  11957. RayHelper.prototype._render = function () {
  11958. var ray = this.ray;
  11959. var point = this._renderPoints[1];
  11960. var len = Math.min(ray.length, 1000000);
  11961. point.copyFrom(ray.direction);
  11962. point.scaleInPlace(len);
  11963. point.addInPlace(ray.origin);
  11964. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11965. };
  11966. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11967. this._attachedToMesh = mesh;
  11968. var ray = this.ray;
  11969. if (!ray.direction) {
  11970. ray.direction = BABYLON.Vector3.Zero();
  11971. }
  11972. if (!ray.origin) {
  11973. ray.origin = BABYLON.Vector3.Zero();
  11974. }
  11975. if (length) {
  11976. ray.length = length;
  11977. }
  11978. if (!meshSpaceOrigin) {
  11979. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11980. }
  11981. if (!meshSpaceDirection) {
  11982. // -1 so that this will work with Mesh.lookAt
  11983. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11984. }
  11985. if (!this._meshSpaceDirection) {
  11986. this._meshSpaceDirection = meshSpaceDirection.clone();
  11987. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11988. }
  11989. else {
  11990. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11991. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11992. }
  11993. if (!this._updateToMeshFunction) {
  11994. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11995. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11996. }
  11997. this._updateToMesh();
  11998. };
  11999. RayHelper.prototype.detachFromMesh = function () {
  12000. if (this._attachedToMesh) {
  12001. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  12002. this._attachedToMesh = null;
  12003. this._updateToMeshFunction = null;
  12004. }
  12005. };
  12006. RayHelper.prototype._updateToMesh = function () {
  12007. var ray = this.ray;
  12008. if (this._attachedToMesh._isDisposed) {
  12009. this.detachFromMesh();
  12010. return;
  12011. }
  12012. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12013. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12014. };
  12015. RayHelper.prototype.dispose = function () {
  12016. this.hide();
  12017. this.detachFromMesh();
  12018. this.ray = null;
  12019. };
  12020. return RayHelper;
  12021. }());
  12022. BABYLON.RayHelper = RayHelper;
  12023. })(BABYLON || (BABYLON = {}));
  12024. //# sourceMappingURL=babylon.rayHelper.js.map
  12025. var BABYLON;
  12026. (function (BABYLON) {
  12027. var AbstractMesh = (function (_super) {
  12028. __extends(AbstractMesh, _super);
  12029. // Constructor
  12030. function AbstractMesh(name, scene) {
  12031. var _this = _super.call(this, name, scene) || this;
  12032. _this._facetNb = 0; // facet number
  12033. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12034. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12035. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12036. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12037. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12038. _this._subDiv = {
  12039. max: 1,
  12040. X: 1,
  12041. Y: 1,
  12042. Z: 1
  12043. };
  12044. // Events
  12045. /**
  12046. * An event triggered when this mesh collides with another one
  12047. * @type {BABYLON.Observable}
  12048. */
  12049. _this.onCollideObservable = new BABYLON.Observable();
  12050. /**
  12051. * An event triggered when the collision's position changes
  12052. * @type {BABYLON.Observable}
  12053. */
  12054. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12055. /**
  12056. * An event triggered after the world matrix is updated
  12057. * @type {BABYLON.Observable}
  12058. */
  12059. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12060. // Properties
  12061. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12062. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12063. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12064. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12065. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12066. _this.visibility = 1.0;
  12067. _this.alphaIndex = Number.MAX_VALUE;
  12068. _this.infiniteDistance = false;
  12069. _this.isVisible = true;
  12070. _this.isPickable = true;
  12071. _this.showBoundingBox = false;
  12072. _this.showSubMeshesBoundingBox = false;
  12073. _this.isBlocker = false;
  12074. _this.renderingGroupId = 0;
  12075. _this.receiveShadows = false;
  12076. _this.renderOutline = false;
  12077. _this.outlineColor = BABYLON.Color3.Red();
  12078. _this.outlineWidth = 0.02;
  12079. _this.renderOverlay = false;
  12080. _this.overlayColor = BABYLON.Color3.Red();
  12081. _this.overlayAlpha = 0.5;
  12082. _this.hasVertexAlpha = false;
  12083. _this.useVertexColors = true;
  12084. _this.applyFog = true;
  12085. _this.computeBonesUsingShaders = true;
  12086. _this.scalingDeterminant = 1;
  12087. _this.numBoneInfluencers = 4;
  12088. _this.useOctreeForRenderingSelection = true;
  12089. _this.useOctreeForPicking = true;
  12090. _this.useOctreeForCollisions = true;
  12091. _this.layerMask = 0x0FFFFFFF;
  12092. /**
  12093. * True if the mesh must be rendered in any case.
  12094. */
  12095. _this.alwaysSelectAsActiveMesh = false;
  12096. // Collisions
  12097. _this._checkCollisions = false;
  12098. _this._collisionMask = -1;
  12099. _this._collisionGroup = -1;
  12100. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12101. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12102. _this._collider = new BABYLON.Collider();
  12103. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12104. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12105. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12106. // Edges
  12107. _this.edgesWidth = 1;
  12108. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12109. // Cache
  12110. _this._localWorld = BABYLON.Matrix.Zero();
  12111. _this._worldMatrix = BABYLON.Matrix.Zero();
  12112. _this._absolutePosition = BABYLON.Vector3.Zero();
  12113. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12114. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12115. _this._isDirty = false;
  12116. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12117. _this._isDisposed = false;
  12118. _this._renderId = 0;
  12119. _this._intersectionsInProgress = new Array();
  12120. _this._isWorldMatrixFrozen = false;
  12121. _this._unIndexed = false;
  12122. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12123. if (collidedMesh === void 0) { collidedMesh = null; }
  12124. //TODO move this to the collision coordinator!
  12125. if (_this.getScene().workerCollisions)
  12126. newPosition.multiplyInPlace(_this._collider.radius);
  12127. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12128. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12129. _this.position.addInPlace(_this._diffPositionForCollisions);
  12130. }
  12131. if (collidedMesh) {
  12132. _this.onCollideObservable.notifyObservers(collidedMesh);
  12133. }
  12134. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12135. };
  12136. _this.getScene().addMesh(_this);
  12137. return _this;
  12138. }
  12139. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12140. get: function () {
  12141. return AbstractMesh._BILLBOARDMODE_NONE;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12147. get: function () {
  12148. return AbstractMesh._BILLBOARDMODE_X;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12154. get: function () {
  12155. return AbstractMesh._BILLBOARDMODE_Y;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12161. get: function () {
  12162. return AbstractMesh._BILLBOARDMODE_Z;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12168. get: function () {
  12169. return AbstractMesh._BILLBOARDMODE_ALL;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12175. /**
  12176. * Read-only : the number of facets in the mesh
  12177. */
  12178. get: function () {
  12179. return this._facetNb;
  12180. },
  12181. enumerable: true,
  12182. configurable: true
  12183. });
  12184. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12185. /**
  12186. * The number (integer) of subdivisions per axis in the partioning space
  12187. */
  12188. get: function () {
  12189. return this._partitioningSubdivisions;
  12190. },
  12191. set: function (nb) {
  12192. this._partitioningSubdivisions = nb;
  12193. },
  12194. enumerable: true,
  12195. configurable: true
  12196. });
  12197. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12198. /**
  12199. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12200. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12201. */
  12202. get: function () {
  12203. return this._partitioningBBoxRatio;
  12204. },
  12205. set: function (ratio) {
  12206. this._partitioningBBoxRatio = ratio;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12212. /**
  12213. * Read-only boolean : is the feature facetData enabled ?
  12214. */
  12215. get: function () {
  12216. return this._facetDataEnabled;
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12222. set: function (callback) {
  12223. if (this._onCollideObserver) {
  12224. this.onCollideObservable.remove(this._onCollideObserver);
  12225. }
  12226. this._onCollideObserver = this.onCollideObservable.add(callback);
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12232. set: function (callback) {
  12233. if (this._onCollisionPositionChangeObserver) {
  12234. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12235. }
  12236. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12242. get: function () {
  12243. return this._collisionMask;
  12244. },
  12245. set: function (mask) {
  12246. this._collisionMask = !isNaN(mask) ? mask : -1;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12252. get: function () {
  12253. return this._collisionGroup;
  12254. },
  12255. set: function (mask) {
  12256. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12257. },
  12258. enumerable: true,
  12259. configurable: true
  12260. });
  12261. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12262. get: function () {
  12263. return this._skeleton;
  12264. },
  12265. set: function (value) {
  12266. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12267. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12268. }
  12269. if (value && value.needInitialSkinMatrix) {
  12270. value._registerMeshWithPoseMatrix(this);
  12271. }
  12272. this._skeleton = value;
  12273. if (!this._skeleton) {
  12274. this._bonesTransformMatrices = null;
  12275. }
  12276. },
  12277. enumerable: true,
  12278. configurable: true
  12279. });
  12280. /**
  12281. * Returns the string "AbstractMesh"
  12282. */
  12283. AbstractMesh.prototype.getClassName = function () {
  12284. return "AbstractMesh";
  12285. };
  12286. /**
  12287. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12288. */
  12289. AbstractMesh.prototype.toString = function (fullDetails) {
  12290. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12291. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12292. if (this._skeleton) {
  12293. ret += ", skeleton: " + this._skeleton.name;
  12294. }
  12295. if (fullDetails) {
  12296. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12297. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12298. }
  12299. return ret;
  12300. };
  12301. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12302. /**
  12303. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12304. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12305. * Default : (0.0, 0.0, 0.0)
  12306. */
  12307. get: function () {
  12308. return this._rotation;
  12309. },
  12310. set: function (newRotation) {
  12311. this._rotation = newRotation;
  12312. },
  12313. enumerable: true,
  12314. configurable: true
  12315. });
  12316. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12317. /**
  12318. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12319. * Default : (1.0, 1.0, 1.0)
  12320. */
  12321. get: function () {
  12322. return this._scaling;
  12323. },
  12324. set: function (newScaling) {
  12325. this._scaling = newScaling;
  12326. if (this.physicsImpostor) {
  12327. this.physicsImpostor.forceUpdate();
  12328. }
  12329. },
  12330. enumerable: true,
  12331. configurable: true
  12332. });
  12333. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12334. /**
  12335. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12336. * It's null by default.
  12337. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12338. */
  12339. get: function () {
  12340. return this._rotationQuaternion;
  12341. },
  12342. set: function (quaternion) {
  12343. this._rotationQuaternion = quaternion;
  12344. //reset the rotation vector.
  12345. if (quaternion && this.rotation.length()) {
  12346. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12347. }
  12348. },
  12349. enumerable: true,
  12350. configurable: true
  12351. });
  12352. // Methods
  12353. /**
  12354. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12355. * Returns the AbstractMesh.
  12356. */
  12357. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12358. this._poseMatrix.copyFrom(matrix);
  12359. return this;
  12360. };
  12361. /**
  12362. * Returns the mesh Pose matrix.
  12363. * Returned object : Matrix
  12364. */
  12365. AbstractMesh.prototype.getPoseMatrix = function () {
  12366. return this._poseMatrix;
  12367. };
  12368. /**
  12369. * Disables the mesh edger rendering mode.
  12370. * Returns the AbstractMesh.
  12371. */
  12372. AbstractMesh.prototype.disableEdgesRendering = function () {
  12373. if (this._edgesRenderer !== undefined) {
  12374. this._edgesRenderer.dispose();
  12375. this._edgesRenderer = undefined;
  12376. }
  12377. return this;
  12378. };
  12379. /**
  12380. * Enables the edge rendering mode on the mesh.
  12381. * This mode makes the mesh edges visible.
  12382. * Returns the AbstractMesh.
  12383. */
  12384. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12385. if (epsilon === void 0) { epsilon = 0.95; }
  12386. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12387. this.disableEdgesRendering();
  12388. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12389. return this;
  12390. };
  12391. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12392. /**
  12393. * Returns true if the mesh is blocked. Used by the class Mesh.
  12394. * Returns the boolean `false` by default.
  12395. */
  12396. get: function () {
  12397. return false;
  12398. },
  12399. enumerable: true,
  12400. configurable: true
  12401. });
  12402. /**
  12403. * Returns the mesh itself by default, used by the class Mesh.
  12404. * Returned type : AbstractMesh
  12405. */
  12406. AbstractMesh.prototype.getLOD = function (camera) {
  12407. return this;
  12408. };
  12409. /**
  12410. * Returns 0 by default, used by the class Mesh.
  12411. * Returns an integer.
  12412. */
  12413. AbstractMesh.prototype.getTotalVertices = function () {
  12414. return 0;
  12415. };
  12416. /**
  12417. * Returns null by default, used by the class Mesh.
  12418. * Returned type : integer array
  12419. */
  12420. AbstractMesh.prototype.getIndices = function () {
  12421. return null;
  12422. };
  12423. /**
  12424. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12425. * Returned type : float array or Float32Array
  12426. */
  12427. AbstractMesh.prototype.getVerticesData = function (kind) {
  12428. return null;
  12429. };
  12430. /** Returns false by default, used by the class Mesh.
  12431. * Returns a boolean
  12432. */
  12433. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12434. return false;
  12435. };
  12436. /**
  12437. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12438. * Returns a BoundingInfo
  12439. */
  12440. AbstractMesh.prototype.getBoundingInfo = function () {
  12441. if (this._masterMesh) {
  12442. return this._masterMesh.getBoundingInfo();
  12443. }
  12444. if (!this._boundingInfo) {
  12445. this._updateBoundingInfo();
  12446. }
  12447. return this._boundingInfo;
  12448. };
  12449. /**
  12450. * Sets a mesh new object BoundingInfo.
  12451. * Returns the AbstractMesh.
  12452. */
  12453. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12454. this._boundingInfo = boundingInfo;
  12455. return this;
  12456. };
  12457. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12458. get: function () {
  12459. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12460. },
  12461. enumerable: true,
  12462. configurable: true
  12463. });
  12464. AbstractMesh.prototype._preActivate = function () {
  12465. };
  12466. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12467. };
  12468. AbstractMesh.prototype._activate = function (renderId) {
  12469. this._renderId = renderId;
  12470. };
  12471. /**
  12472. * Returns the last update of the World matrix
  12473. * Returns a Matrix.
  12474. */
  12475. AbstractMesh.prototype.getWorldMatrix = function () {
  12476. if (this._masterMesh) {
  12477. return this._masterMesh.getWorldMatrix();
  12478. }
  12479. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12480. this.computeWorldMatrix();
  12481. }
  12482. return this._worldMatrix;
  12483. };
  12484. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12485. /**
  12486. * Returns directly the last state of the mesh World matrix.
  12487. * A Matrix is returned.
  12488. */
  12489. get: function () {
  12490. return this._worldMatrix;
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12496. /**
  12497. * Returns the current mesh absolute position.
  12498. * Retuns a Vector3.
  12499. */
  12500. get: function () {
  12501. return this._absolutePosition;
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. /**
  12507. * Prevents the World matrix to be computed any longer.
  12508. * Returns the AbstractMesh.
  12509. */
  12510. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12511. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12512. this.computeWorldMatrix(true);
  12513. this._isWorldMatrixFrozen = true;
  12514. return this;
  12515. };
  12516. /**
  12517. * Allows back the World matrix computation.
  12518. * Returns the AbstractMesh.
  12519. */
  12520. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12521. this._isWorldMatrixFrozen = false;
  12522. this.computeWorldMatrix(true);
  12523. return this;
  12524. };
  12525. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12526. /**
  12527. * True if the World matrix has been frozen.
  12528. * Returns a boolean.
  12529. */
  12530. get: function () {
  12531. return this._isWorldMatrixFrozen;
  12532. },
  12533. enumerable: true,
  12534. configurable: true
  12535. });
  12536. /**
  12537. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12538. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12539. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12540. * The passed axis is also normalized.
  12541. * Returns the AbstractMesh.
  12542. */
  12543. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12544. axis.normalize();
  12545. if (!this.rotationQuaternion) {
  12546. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12547. this.rotation = BABYLON.Vector3.Zero();
  12548. }
  12549. var rotationQuaternion;
  12550. if (!space || space === BABYLON.Space.LOCAL) {
  12551. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12552. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12553. }
  12554. else {
  12555. if (this.parent) {
  12556. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12557. invertParentWorldMatrix.invert();
  12558. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12559. }
  12560. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12561. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12562. }
  12563. return this;
  12564. };
  12565. /**
  12566. * Translates the mesh along the axis vector for the passed distance in the given space.
  12567. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12568. * Returns the AbstractMesh.
  12569. */
  12570. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12571. var displacementVector = axis.scale(distance);
  12572. if (!space || space === BABYLON.Space.LOCAL) {
  12573. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12574. this.setPositionWithLocalVector(tempV3);
  12575. }
  12576. else {
  12577. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12578. }
  12579. return this;
  12580. };
  12581. /**
  12582. * Adds a rotation step to the mesh current rotation.
  12583. * x, y, z are Euler angles expressed in radians.
  12584. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12585. * This means this rotation is made in the mesh local space only.
  12586. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12587. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12588. * ```javascript
  12589. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12590. * ```
  12591. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12592. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12593. * Returns the AbstractMesh.
  12594. */
  12595. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12596. var rotationQuaternion;
  12597. if (this.rotationQuaternion) {
  12598. rotationQuaternion = this.rotationQuaternion;
  12599. }
  12600. else {
  12601. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12602. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12603. }
  12604. var accumulation = BABYLON.Tmp.Quaternion[0];
  12605. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12606. rotationQuaternion.multiplyInPlace(accumulation);
  12607. if (!this.rotationQuaternion) {
  12608. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12609. }
  12610. return this;
  12611. };
  12612. /**
  12613. * Retuns the mesh absolute position in the World.
  12614. * Returns a Vector3.
  12615. */
  12616. AbstractMesh.prototype.getAbsolutePosition = function () {
  12617. this.computeWorldMatrix();
  12618. return this._absolutePosition;
  12619. };
  12620. /**
  12621. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12622. * Returns the AbstractMesh.
  12623. */
  12624. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12625. if (!absolutePosition) {
  12626. return;
  12627. }
  12628. var absolutePositionX;
  12629. var absolutePositionY;
  12630. var absolutePositionZ;
  12631. if (absolutePosition.x === undefined) {
  12632. if (arguments.length < 3) {
  12633. return;
  12634. }
  12635. absolutePositionX = arguments[0];
  12636. absolutePositionY = arguments[1];
  12637. absolutePositionZ = arguments[2];
  12638. }
  12639. else {
  12640. absolutePositionX = absolutePosition.x;
  12641. absolutePositionY = absolutePosition.y;
  12642. absolutePositionZ = absolutePosition.z;
  12643. }
  12644. if (this.parent) {
  12645. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12646. invertParentWorldMatrix.invert();
  12647. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12648. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12649. }
  12650. else {
  12651. this.position.x = absolutePositionX;
  12652. this.position.y = absolutePositionY;
  12653. this.position.z = absolutePositionZ;
  12654. }
  12655. return this;
  12656. };
  12657. // ================================== Point of View Movement =================================
  12658. /**
  12659. * Perform relative position change from the point of view of behind the front of the mesh.
  12660. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12661. * Supports definition of mesh facing forward or backward.
  12662. * @param {number} amountRight
  12663. * @param {number} amountUp
  12664. * @param {number} amountForward
  12665. *
  12666. * Returns the AbstractMesh.
  12667. */
  12668. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12669. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12670. return this;
  12671. };
  12672. /**
  12673. * Calculate relative position change from the point of view of behind the front of the mesh.
  12674. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12675. * Supports definition of mesh facing forward or backward.
  12676. * @param {number} amountRight
  12677. * @param {number} amountUp
  12678. * @param {number} amountForward
  12679. *
  12680. * Returns a new Vector3.
  12681. */
  12682. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12683. var rotMatrix = new BABYLON.Matrix();
  12684. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12685. rotQuaternion.toRotationMatrix(rotMatrix);
  12686. var translationDelta = BABYLON.Vector3.Zero();
  12687. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12689. return translationDelta;
  12690. };
  12691. // ================================== Point of View Rotation =================================
  12692. /**
  12693. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12694. * Supports definition of mesh facing forward or backward.
  12695. * @param {number} flipBack
  12696. * @param {number} twirlClockwise
  12697. * @param {number} tiltRight
  12698. *
  12699. * Returns the AbstractMesh.
  12700. */
  12701. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12702. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12703. return this;
  12704. };
  12705. /**
  12706. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12707. * Supports definition of mesh facing forward or backward.
  12708. * @param {number} flipBack
  12709. * @param {number} twirlClockwise
  12710. * @param {number} tiltRight
  12711. *
  12712. * Returns a new Vector3.
  12713. */
  12714. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12715. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12716. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12717. };
  12718. /**
  12719. * Sets a new pivot matrix to the mesh.
  12720. * Returns the AbstractMesh.
  12721. */
  12722. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12723. this._pivotMatrix = matrix;
  12724. this._cache.pivotMatrixUpdated = true;
  12725. return this;
  12726. };
  12727. /**
  12728. * Returns the mesh pivot matrix.
  12729. * Default : Identity.
  12730. * A Matrix is returned.
  12731. */
  12732. AbstractMesh.prototype.getPivotMatrix = function () {
  12733. return this._pivotMatrix;
  12734. };
  12735. AbstractMesh.prototype._isSynchronized = function () {
  12736. if (this._isDirty) {
  12737. return false;
  12738. }
  12739. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12740. return false;
  12741. if (this._cache.pivotMatrixUpdated) {
  12742. return false;
  12743. }
  12744. if (this.infiniteDistance) {
  12745. return false;
  12746. }
  12747. if (!this._cache.position.equals(this.position))
  12748. return false;
  12749. if (this.rotationQuaternion) {
  12750. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12751. return false;
  12752. }
  12753. if (!this._cache.rotation.equals(this.rotation))
  12754. return false;
  12755. if (!this._cache.scaling.equals(this.scaling))
  12756. return false;
  12757. return true;
  12758. };
  12759. AbstractMesh.prototype._initCache = function () {
  12760. _super.prototype._initCache.call(this);
  12761. this._cache.localMatrixUpdated = false;
  12762. this._cache.position = BABYLON.Vector3.Zero();
  12763. this._cache.scaling = BABYLON.Vector3.Zero();
  12764. this._cache.rotation = BABYLON.Vector3.Zero();
  12765. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12766. this._cache.billboardMode = -1;
  12767. };
  12768. AbstractMesh.prototype.markAsDirty = function (property) {
  12769. if (property === "rotation") {
  12770. this.rotationQuaternion = null;
  12771. }
  12772. this._currentRenderId = Number.MAX_VALUE;
  12773. this._isDirty = true;
  12774. return this;
  12775. };
  12776. /**
  12777. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12778. * Returns the AbstractMesh.
  12779. */
  12780. AbstractMesh.prototype._updateBoundingInfo = function () {
  12781. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12782. this._boundingInfo.update(this.worldMatrixFromCache);
  12783. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12784. return this;
  12785. };
  12786. /**
  12787. * Update a mesh's children BoundingInfo objects only.
  12788. * Returns the AbstractMesh.
  12789. */
  12790. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12791. if (!this.subMeshes) {
  12792. return;
  12793. }
  12794. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12795. var subMesh = this.subMeshes[subIndex];
  12796. if (!subMesh.IsGlobal) {
  12797. subMesh.updateBoundingInfo(matrix);
  12798. }
  12799. }
  12800. return this;
  12801. };
  12802. /**
  12803. * Computes the mesh World matrix and returns it.
  12804. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12805. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12806. * If the parameter `force`is set to `true`, the actual computation is done.
  12807. * Returns the mesh World Matrix.
  12808. */
  12809. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12810. if (this._isWorldMatrixFrozen) {
  12811. return this._worldMatrix;
  12812. }
  12813. if (!force && ((this._currentRenderId === this.getScene().getRenderId() && this.isSynchronized(true)))) {
  12814. this._currentRenderId = this.getScene().getRenderId();
  12815. return this._worldMatrix;
  12816. }
  12817. this._cache.position.copyFrom(this.position);
  12818. this._cache.scaling.copyFrom(this.scaling);
  12819. this._cache.pivotMatrixUpdated = false;
  12820. this._cache.billboardMode = this.billboardMode;
  12821. this._currentRenderId = this.getScene().getRenderId();
  12822. this._isDirty = false;
  12823. // Scaling
  12824. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12825. // Rotation
  12826. //rotate, if quaternion is set and rotation was used
  12827. if (this.rotationQuaternion) {
  12828. var len = this.rotation.length();
  12829. if (len) {
  12830. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12831. this.rotation.copyFromFloats(0, 0, 0);
  12832. }
  12833. }
  12834. if (this.rotationQuaternion) {
  12835. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12836. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12837. }
  12838. else {
  12839. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12840. this._cache.rotation.copyFrom(this.rotation);
  12841. }
  12842. // Translation
  12843. if (this.infiniteDistance && !this.parent) {
  12844. var camera = this.getScene().activeCamera;
  12845. if (camera) {
  12846. var cameraWorldMatrix = camera.getWorldMatrix();
  12847. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12848. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12849. }
  12850. }
  12851. else {
  12852. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12853. }
  12854. // Composing transformations
  12855. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12856. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12857. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12858. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12859. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12860. // Need to decompose each rotation here
  12861. var currentPosition = BABYLON.Tmp.Vector3[3];
  12862. if (this.parent && this.parent.getWorldMatrix) {
  12863. if (this._meshToBoneReferal) {
  12864. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12865. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12866. }
  12867. else {
  12868. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12869. }
  12870. }
  12871. else {
  12872. currentPosition.copyFrom(this.position);
  12873. }
  12874. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12875. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12876. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12877. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12878. }
  12879. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12880. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12881. }
  12882. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12883. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12884. }
  12885. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12886. }
  12887. else {
  12888. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12889. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12890. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12891. }
  12892. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12893. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12894. }
  12895. // Local world
  12896. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12897. // Parent
  12898. if (this.parent && this.parent.getWorldMatrix) {
  12899. this._markSyncedWithParent();
  12900. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12901. if (this._meshToBoneReferal) {
  12902. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12903. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12904. }
  12905. else {
  12906. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12907. }
  12908. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12909. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12910. this._worldMatrix.copyFrom(this._localWorld);
  12911. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12912. }
  12913. else {
  12914. if (this._meshToBoneReferal) {
  12915. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12916. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12917. }
  12918. else {
  12919. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12920. }
  12921. }
  12922. }
  12923. else {
  12924. this._worldMatrix.copyFrom(this._localWorld);
  12925. }
  12926. // Bounding info
  12927. this._updateBoundingInfo();
  12928. // Absolute position
  12929. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12930. // Callbacks
  12931. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12932. if (!this._poseMatrix) {
  12933. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12934. }
  12935. return this._worldMatrix;
  12936. };
  12937. /**
  12938. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12939. * @param func: callback function to add
  12940. *
  12941. * Returns the AbstractMesh.
  12942. */
  12943. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12944. this.onAfterWorldMatrixUpdateObservable.add(func);
  12945. return this;
  12946. };
  12947. /**
  12948. * Removes a registered callback function.
  12949. * Returns the AbstractMesh.
  12950. */
  12951. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12952. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12953. return this;
  12954. };
  12955. /**
  12956. * Sets the mesh position in its local space.
  12957. * Returns the AbstractMesh.
  12958. */
  12959. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12960. this.computeWorldMatrix();
  12961. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12962. return this;
  12963. };
  12964. /**
  12965. * Returns the mesh position in the local space from the current World matrix values.
  12966. * Returns a new Vector3.
  12967. */
  12968. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12969. this.computeWorldMatrix();
  12970. var invLocalWorldMatrix = this._localWorld.clone();
  12971. invLocalWorldMatrix.invert();
  12972. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12973. };
  12974. /**
  12975. * Translates the mesh along the passed Vector3 in its local space.
  12976. * Returns the AbstractMesh.
  12977. */
  12978. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12979. this.computeWorldMatrix(true);
  12980. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12981. return this;
  12982. };
  12983. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12984. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12985. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12986. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12987. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12988. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12989. /// <returns>Mesh oriented towards targetMesh</returns>
  12990. if (yawCor === void 0) { yawCor = 0; }
  12991. if (pitchCor === void 0) { pitchCor = 0; }
  12992. if (rollCor === void 0) { rollCor = 0; }
  12993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12994. var dv = AbstractMesh._lookAtVectorCache;
  12995. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12996. targetPoint.subtractToRef(pos, dv);
  12997. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12998. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12999. var pitch = Math.atan2(dv.y, len);
  13000. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13001. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13002. return this;
  13003. };
  13004. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13005. this._meshToBoneReferal = affectedMesh;
  13006. this.parent = bone;
  13007. if (bone.getWorldMatrix().determinant() < 0) {
  13008. this.scalingDeterminant *= -1;
  13009. }
  13010. return this;
  13011. };
  13012. AbstractMesh.prototype.detachFromBone = function () {
  13013. if (this.parent.getWorldMatrix().determinant() < 0) {
  13014. this.scalingDeterminant *= -1;
  13015. }
  13016. this._meshToBoneReferal = null;
  13017. this.parent = null;
  13018. return this;
  13019. };
  13020. /**
  13021. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13022. * A mesh is in the frustum if its bounding box intersects the frustum.
  13023. * Boolean returned.
  13024. */
  13025. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13026. return this._boundingInfo.isInFrustum(frustumPlanes);
  13027. };
  13028. /**
  13029. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13030. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13031. * Boolean returned.
  13032. */
  13033. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13034. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13035. ;
  13036. };
  13037. /**
  13038. * True if the mesh intersects another mesh or a SolidParticle object.
  13039. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  13040. * Returns a boolean.
  13041. */
  13042. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13043. if (!this._boundingInfo || !mesh._boundingInfo) {
  13044. return false;
  13045. }
  13046. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13047. };
  13048. /**
  13049. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13050. * Returns a boolean.
  13051. */
  13052. AbstractMesh.prototype.intersectsPoint = function (point) {
  13053. if (!this._boundingInfo) {
  13054. return false;
  13055. }
  13056. return this._boundingInfo.intersectsPoint(point);
  13057. };
  13058. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13059. return this.physicsImpostor;
  13060. };
  13061. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13062. if (!camera) {
  13063. camera = this.getScene().activeCamera;
  13064. }
  13065. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13066. };
  13067. /**
  13068. * Returns the distance from the mesh to the active camera.
  13069. * Returns a float.
  13070. */
  13071. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13072. if (!camera) {
  13073. camera = this.getScene().activeCamera;
  13074. }
  13075. return this.absolutePosition.subtract(camera.position).length();
  13076. };
  13077. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13078. if (!this.physicsImpostor) {
  13079. return;
  13080. }
  13081. this.physicsImpostor.applyImpulse(force, contactPoint);
  13082. return this;
  13083. };
  13084. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13085. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13086. return;
  13087. }
  13088. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13089. mainPivot: pivot1,
  13090. connectedPivot: pivot2,
  13091. nativeParams: options
  13092. });
  13093. return this;
  13094. };
  13095. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13096. // Collisions
  13097. /**
  13098. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13099. * Default `false`.
  13100. */
  13101. get: function () {
  13102. return this._checkCollisions;
  13103. },
  13104. set: function (collisionEnabled) {
  13105. this._checkCollisions = collisionEnabled;
  13106. if (this.getScene().workerCollisions) {
  13107. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13108. }
  13109. },
  13110. enumerable: true,
  13111. configurable: true
  13112. });
  13113. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13114. var globalPosition = this.getAbsolutePosition();
  13115. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13116. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13117. this._collider.radius = this.ellipsoid;
  13118. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13119. return this;
  13120. };
  13121. // Submeshes octree
  13122. /**
  13123. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13124. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13125. * Returns an Octree of submeshes.
  13126. */
  13127. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13128. if (maxCapacity === void 0) { maxCapacity = 64; }
  13129. if (maxDepth === void 0) { maxDepth = 2; }
  13130. if (!this._submeshesOctree) {
  13131. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13132. }
  13133. this.computeWorldMatrix(true);
  13134. // Update octree
  13135. var bbox = this.getBoundingInfo().boundingBox;
  13136. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13137. return this._submeshesOctree;
  13138. };
  13139. // Collisions
  13140. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13141. this._generatePointsArray();
  13142. // Transformation
  13143. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13144. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13145. subMesh._lastColliderWorldVertices = [];
  13146. subMesh._trianglePlanes = [];
  13147. var start = subMesh.verticesStart;
  13148. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13149. for (var i = start; i < end; i++) {
  13150. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13151. }
  13152. }
  13153. // Collide
  13154. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13155. if (collider.collisionFound) {
  13156. collider.collidedMesh = this;
  13157. }
  13158. return this;
  13159. };
  13160. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13161. var subMeshes;
  13162. var len;
  13163. // Octrees
  13164. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13165. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13166. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13167. len = intersections.length;
  13168. subMeshes = intersections.data;
  13169. }
  13170. else {
  13171. subMeshes = this.subMeshes;
  13172. len = subMeshes.length;
  13173. }
  13174. for (var index = 0; index < len; index++) {
  13175. var subMesh = subMeshes[index];
  13176. // Bounding test
  13177. if (len > 1 && !subMesh._checkCollision(collider))
  13178. continue;
  13179. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13180. }
  13181. return this;
  13182. };
  13183. AbstractMesh.prototype._checkCollision = function (collider) {
  13184. // Bounding box test
  13185. if (!this._boundingInfo._checkCollision(collider))
  13186. return this;
  13187. // Transformation matrix
  13188. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13189. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13190. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13191. return this;
  13192. };
  13193. // Picking
  13194. AbstractMesh.prototype._generatePointsArray = function () {
  13195. return false;
  13196. };
  13197. /**
  13198. * Checks if the passed Ray intersects with the mesh.
  13199. * Returns an object PickingInfo.
  13200. */
  13201. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13202. var pickingInfo = new BABYLON.PickingInfo();
  13203. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13204. return pickingInfo;
  13205. }
  13206. if (!this._generatePointsArray()) {
  13207. return pickingInfo;
  13208. }
  13209. var intersectInfo = null;
  13210. // Octrees
  13211. var subMeshes;
  13212. var len;
  13213. if (this._submeshesOctree && this.useOctreeForPicking) {
  13214. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13215. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13216. len = intersections.length;
  13217. subMeshes = intersections.data;
  13218. }
  13219. else {
  13220. subMeshes = this.subMeshes;
  13221. len = subMeshes.length;
  13222. }
  13223. for (var index = 0; index < len; index++) {
  13224. var subMesh = subMeshes[index];
  13225. // Bounding test
  13226. if (len > 1 && !subMesh.canIntersects(ray))
  13227. continue;
  13228. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13229. if (currentIntersectInfo) {
  13230. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13231. intersectInfo = currentIntersectInfo;
  13232. intersectInfo.subMeshId = index;
  13233. if (fastCheck) {
  13234. break;
  13235. }
  13236. }
  13237. }
  13238. }
  13239. if (intersectInfo) {
  13240. // Get picked point
  13241. var world = this.getWorldMatrix();
  13242. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13243. var direction = ray.direction.clone();
  13244. direction = direction.scale(intersectInfo.distance);
  13245. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13246. var pickedPoint = worldOrigin.add(worldDirection);
  13247. // Return result
  13248. pickingInfo.hit = true;
  13249. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13250. pickingInfo.pickedPoint = pickedPoint;
  13251. pickingInfo.pickedMesh = this;
  13252. pickingInfo.bu = intersectInfo.bu;
  13253. pickingInfo.bv = intersectInfo.bv;
  13254. pickingInfo.faceId = intersectInfo.faceId;
  13255. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13256. return pickingInfo;
  13257. }
  13258. return pickingInfo;
  13259. };
  13260. /**
  13261. * Clones the mesh, used by the class Mesh.
  13262. * Just returns `null` for an AbstractMesh.
  13263. */
  13264. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13265. return null;
  13266. };
  13267. /**
  13268. * Disposes all the mesh submeshes.
  13269. * Returns the AbstractMesh.
  13270. */
  13271. AbstractMesh.prototype.releaseSubMeshes = function () {
  13272. if (this.subMeshes) {
  13273. while (this.subMeshes.length) {
  13274. this.subMeshes[0].dispose();
  13275. }
  13276. }
  13277. else {
  13278. this.subMeshes = new Array();
  13279. }
  13280. return this;
  13281. };
  13282. /**
  13283. * Disposes the AbstractMesh.
  13284. * Some internal references are kept for further use.
  13285. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13286. * Returns nothing.
  13287. */
  13288. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13289. var _this = this;
  13290. var index;
  13291. // Action manager
  13292. if (this.actionManager) {
  13293. this.actionManager.dispose();
  13294. this.actionManager = null;
  13295. }
  13296. // Skeleton
  13297. this.skeleton = null;
  13298. // Animations
  13299. this.getScene().stopAnimation(this);
  13300. // Physics
  13301. if (this.physicsImpostor) {
  13302. this.physicsImpostor.dispose();
  13303. }
  13304. // Intersections in progress
  13305. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13306. var other = this._intersectionsInProgress[index];
  13307. var pos = other._intersectionsInProgress.indexOf(this);
  13308. other._intersectionsInProgress.splice(pos, 1);
  13309. }
  13310. this._intersectionsInProgress = [];
  13311. // Lights
  13312. var lights = this.getScene().lights;
  13313. lights.forEach(function (light) {
  13314. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13315. if (meshIndex !== -1) {
  13316. light.includedOnlyMeshes.splice(meshIndex, 1);
  13317. }
  13318. meshIndex = light.excludedMeshes.indexOf(_this);
  13319. if (meshIndex !== -1) {
  13320. light.excludedMeshes.splice(meshIndex, 1);
  13321. }
  13322. // Shadow generators
  13323. var generator = light.getShadowGenerator();
  13324. if (generator) {
  13325. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13326. if (meshIndex !== -1) {
  13327. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13328. }
  13329. }
  13330. });
  13331. // Edges
  13332. if (this._edgesRenderer) {
  13333. this._edgesRenderer.dispose();
  13334. this._edgesRenderer = null;
  13335. }
  13336. // SubMeshes
  13337. if (this.getClassName() !== "InstancedMesh") {
  13338. this.releaseSubMeshes();
  13339. }
  13340. // Engine
  13341. this.getScene().getEngine().wipeCaches();
  13342. // Remove from scene
  13343. this.getScene().removeMesh(this);
  13344. if (!doNotRecurse) {
  13345. // Particles
  13346. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13347. if (this.getScene().particleSystems[index].emitter === this) {
  13348. this.getScene().particleSystems[index].dispose();
  13349. index--;
  13350. }
  13351. }
  13352. // Children
  13353. var objects = this.getDescendants(true);
  13354. for (index = 0; index < objects.length; index++) {
  13355. objects[index].dispose();
  13356. }
  13357. }
  13358. else {
  13359. var childMeshes = this.getChildMeshes(true);
  13360. for (index = 0; index < childMeshes.length; index++) {
  13361. var child = childMeshes[index];
  13362. child.parent = null;
  13363. child.computeWorldMatrix(true);
  13364. }
  13365. }
  13366. // facet data
  13367. if (this._facetDataEnabled) {
  13368. this.disableFacetData();
  13369. }
  13370. this.onAfterWorldMatrixUpdateObservable.clear();
  13371. this.onCollideObservable.clear();
  13372. this.onCollisionPositionChangeObservable.clear();
  13373. this._isDisposed = true;
  13374. _super.prototype.dispose.call(this);
  13375. };
  13376. /**
  13377. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13378. * This Vector3 is expressed in the World space.
  13379. */
  13380. AbstractMesh.prototype.getDirection = function (localAxis) {
  13381. var result = BABYLON.Vector3.Zero();
  13382. this.getDirectionToRef(localAxis, result);
  13383. return result;
  13384. };
  13385. /**
  13386. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13387. * localAxis is expressed in the mesh local space.
  13388. * result is computed in the Wordl space from the mesh World matrix.
  13389. * Returns the AbstractMesh.
  13390. */
  13391. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13392. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13393. return this;
  13394. };
  13395. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13397. if (this.getScene().getRenderId() == 0) {
  13398. this.computeWorldMatrix(true);
  13399. }
  13400. var wm = this.getWorldMatrix();
  13401. if (space == BABYLON.Space.WORLD) {
  13402. var tmat = BABYLON.Tmp.Matrix[0];
  13403. wm.invertToRef(tmat);
  13404. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13405. }
  13406. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13407. this._pivotMatrix.m[12] = -point.x;
  13408. this._pivotMatrix.m[13] = -point.y;
  13409. this._pivotMatrix.m[14] = -point.z;
  13410. this._cache.pivotMatrixUpdated = true;
  13411. return this;
  13412. };
  13413. /**
  13414. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13415. */
  13416. AbstractMesh.prototype.getPivotPoint = function () {
  13417. var point = BABYLON.Vector3.Zero();
  13418. this.getPivotPointToRef(point);
  13419. return point;
  13420. };
  13421. /**
  13422. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13423. * Returns the AbstractMesh.
  13424. */
  13425. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13426. result.x = -this._pivotMatrix.m[12];
  13427. result.y = -this._pivotMatrix.m[13];
  13428. result.z = -this._pivotMatrix.m[14];
  13429. return this;
  13430. };
  13431. /**
  13432. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13433. */
  13434. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13435. var point = BABYLON.Vector3.Zero();
  13436. this.getAbsolutePivotPointToRef(point);
  13437. return point;
  13438. };
  13439. /**
  13440. * Defines the passed mesh as the parent of the current mesh.
  13441. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13442. * Returns the AbstractMesh.
  13443. */
  13444. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13445. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13446. var child = this;
  13447. var parent = mesh;
  13448. if (mesh == null) {
  13449. if (child.parent && keepWorldPositionRotation) {
  13450. var rotation = BABYLON.Tmp.Quaternion[0];
  13451. var position = BABYLON.Tmp.Vector3[0];
  13452. var scale = BABYLON.Tmp.Vector3[1];
  13453. child.getWorldMatrix().decompose(scale, rotation, position);
  13454. if (child.rotationQuaternion) {
  13455. child.rotationQuaternion.copyFrom(rotation);
  13456. }
  13457. else {
  13458. rotation.toEulerAnglesToRef(child.rotation);
  13459. }
  13460. child.position.x = position.x;
  13461. child.position.y = position.y;
  13462. child.position.z = position.z;
  13463. }
  13464. }
  13465. else {
  13466. if (keepWorldPositionRotation) {
  13467. var rotation = BABYLON.Tmp.Quaternion[0];
  13468. var position = BABYLON.Tmp.Vector3[0];
  13469. var scale = BABYLON.Tmp.Vector3[1];
  13470. var m1 = BABYLON.Tmp.Matrix[0];
  13471. var m2 = BABYLON.Tmp.Matrix[1];
  13472. parent.getWorldMatrix().decompose(scale, rotation, position);
  13473. rotation.toRotationMatrix(m1);
  13474. m2.setTranslation(position);
  13475. m2.multiplyToRef(m1, m1);
  13476. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13477. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13478. m.decompose(scale, rotation, position);
  13479. if (child.rotationQuaternion) {
  13480. child.rotationQuaternion.copyFrom(rotation);
  13481. }
  13482. else {
  13483. rotation.toEulerAnglesToRef(child.rotation);
  13484. }
  13485. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13486. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13487. m.decompose(scale, rotation, position);
  13488. child.position.x = position.x;
  13489. child.position.y = position.y;
  13490. child.position.z = position.z;
  13491. }
  13492. }
  13493. child.parent = parent;
  13494. return this;
  13495. };
  13496. /**
  13497. * Adds the passed mesh as a child to the current mesh.
  13498. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13499. * Returns the AbstractMesh.
  13500. */
  13501. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13502. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13503. mesh.setParent(this, keepWorldPositionRotation);
  13504. return this;
  13505. };
  13506. /**
  13507. * Removes the passed mesh from the current mesh children list.
  13508. * Returns the AbstractMesh.
  13509. */
  13510. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13511. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13512. mesh.setParent(null, keepWorldPositionRotation);
  13513. return this;
  13514. };
  13515. /**
  13516. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13517. * Returns the AbstractMesh.
  13518. */
  13519. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13520. result.x = this._pivotMatrix.m[12];
  13521. result.y = this._pivotMatrix.m[13];
  13522. result.z = this._pivotMatrix.m[14];
  13523. this.getPivotPointToRef(result);
  13524. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13525. return this;
  13526. };
  13527. // Facet data
  13528. /**
  13529. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13530. * Returns the AbstractMesh.
  13531. */
  13532. AbstractMesh.prototype._initFacetData = function () {
  13533. if (!this._facetNormals) {
  13534. this._facetNormals = new Array();
  13535. }
  13536. if (!this._facetPositions) {
  13537. this._facetPositions = new Array();
  13538. }
  13539. if (!this._facetPartitioning) {
  13540. this._facetPartitioning = new Array();
  13541. }
  13542. this._facetNb = this.getIndices().length / 3;
  13543. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13544. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13545. for (var f = 0; f < this._facetNb; f++) {
  13546. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13547. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13548. }
  13549. this._facetDataEnabled = true;
  13550. return this;
  13551. };
  13552. /**
  13553. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13554. * This method can be called within the render loop.
  13555. * 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.
  13556. * Returns the AbstractMesh.
  13557. */
  13558. AbstractMesh.prototype.updateFacetData = function () {
  13559. if (!this._facetDataEnabled) {
  13560. this._initFacetData();
  13561. }
  13562. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13563. var indices = this.getIndices();
  13564. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13565. var bInfo = this.getBoundingInfo();
  13566. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13567. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13568. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13569. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13570. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13571. this._subDiv.max = this._partitioningSubdivisions;
  13572. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13573. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13574. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13575. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13576. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13577. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13578. // set the parameters for ComputeNormals()
  13579. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13580. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13581. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13582. this._facetParameters.bInfo = bInfo;
  13583. this._facetParameters.bbSize = this._bbSize;
  13584. this._facetParameters.subDiv = this._subDiv;
  13585. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13586. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13587. return this;
  13588. };
  13589. /**
  13590. * Returns the facetLocalNormals array.
  13591. * The normals are expressed in the mesh local space.
  13592. */
  13593. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13594. if (!this._facetNormals) {
  13595. this.updateFacetData();
  13596. }
  13597. return this._facetNormals;
  13598. };
  13599. /**
  13600. * Returns the facetLocalPositions array.
  13601. * The facet positions are expressed in the mesh local space.
  13602. */
  13603. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13604. if (!this._facetPositions) {
  13605. this.updateFacetData();
  13606. }
  13607. return this._facetPositions;
  13608. };
  13609. /**
  13610. * Returns the facetLocalPartioning array.
  13611. */
  13612. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13613. if (!this._facetPartitioning) {
  13614. this.updateFacetData();
  13615. }
  13616. return this._facetPartitioning;
  13617. };
  13618. /**
  13619. * Returns the i-th facet position in the world system.
  13620. * This method allocates a new Vector3 per call.
  13621. */
  13622. AbstractMesh.prototype.getFacetPosition = function (i) {
  13623. var pos = BABYLON.Vector3.Zero();
  13624. this.getFacetPositionToRef(i, pos);
  13625. return pos;
  13626. };
  13627. /**
  13628. * Sets the reference Vector3 with the i-th facet position in the world system.
  13629. * Returns the AbstractMesh.
  13630. */
  13631. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13632. var localPos = (this.getFacetLocalPositions())[i];
  13633. var world = this.getWorldMatrix();
  13634. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13635. return this;
  13636. };
  13637. /**
  13638. * Returns the i-th facet normal in the world system.
  13639. * This method allocates a new Vector3 per call.
  13640. */
  13641. AbstractMesh.prototype.getFacetNormal = function (i) {
  13642. var norm = BABYLON.Vector3.Zero();
  13643. this.getFacetNormalToRef(i, norm);
  13644. return norm;
  13645. };
  13646. /**
  13647. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13648. * Returns the AbstractMesh.
  13649. */
  13650. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13651. var localNorm = (this.getFacetLocalNormals())[i];
  13652. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13653. return this;
  13654. };
  13655. /**
  13656. * 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).
  13657. */
  13658. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13659. var bInfo = this.getBoundingInfo();
  13660. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13661. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13662. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13663. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13664. return null;
  13665. }
  13666. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13667. };
  13668. /**
  13669. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13670. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13671. * 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.
  13672. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13673. * 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.
  13674. */
  13675. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13676. if (checkFace === void 0) { checkFace = false; }
  13677. if (facing === void 0) { facing = true; }
  13678. var world = this.getWorldMatrix();
  13679. var invMat = BABYLON.Tmp.Matrix[5];
  13680. world.invertToRef(invMat);
  13681. var invVect = BABYLON.Tmp.Vector3[8];
  13682. var closest = null;
  13683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13684. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13685. if (projected) {
  13686. // tranform the local computed projected vector to world coordinates
  13687. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13688. }
  13689. return closest;
  13690. };
  13691. /**
  13692. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13693. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13694. * 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.
  13695. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13696. * 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.
  13697. */
  13698. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13699. if (checkFace === void 0) { checkFace = false; }
  13700. if (facing === void 0) { facing = true; }
  13701. var closest = null;
  13702. var tmpx = 0.0;
  13703. var tmpy = 0.0;
  13704. var tmpz = 0.0;
  13705. var d = 0.0; // tmp dot facet normal * facet position
  13706. var t0 = 0.0;
  13707. var projx = 0.0;
  13708. var projy = 0.0;
  13709. var projz = 0.0;
  13710. // Get all the facets in the same partitioning block than (x, y, z)
  13711. var facetPositions = this.getFacetLocalPositions();
  13712. var facetNormals = this.getFacetLocalNormals();
  13713. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13714. if (!facetsInBlock) {
  13715. return null;
  13716. }
  13717. // Get the closest facet to (x, y, z)
  13718. var shortest = Number.MAX_VALUE; // init distance vars
  13719. var tmpDistance = shortest;
  13720. var fib; // current facet in the block
  13721. var norm; // current facet normal
  13722. var p0; // current facet barycenter position
  13723. // loop on all the facets in the current partitioning block
  13724. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13725. fib = facetsInBlock[idx];
  13726. norm = facetNormals[fib];
  13727. p0 = facetPositions[fib];
  13728. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13729. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13730. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13731. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13732. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13733. projx = x + norm.x * t0;
  13734. projy = y + norm.y * t0;
  13735. projz = z + norm.z * t0;
  13736. tmpx = projx - x;
  13737. tmpy = projy - y;
  13738. tmpz = projz - z;
  13739. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13740. if (tmpDistance < shortest) {
  13741. shortest = tmpDistance;
  13742. closest = fib;
  13743. if (projected) {
  13744. projected.x = projx;
  13745. projected.y = projy;
  13746. projected.z = projz;
  13747. }
  13748. }
  13749. }
  13750. }
  13751. return closest;
  13752. };
  13753. /**
  13754. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13755. */
  13756. AbstractMesh.prototype.getFacetDataParameters = function () {
  13757. return this._facetParameters;
  13758. };
  13759. /**
  13760. * Disables the feature FacetData and frees the related memory.
  13761. * Returns the AbstractMesh.
  13762. */
  13763. AbstractMesh.prototype.disableFacetData = function () {
  13764. if (this._facetDataEnabled) {
  13765. this._facetDataEnabled = false;
  13766. this._facetPositions = null;
  13767. this._facetNormals = null;
  13768. this._facetPartitioning = null;
  13769. this._facetParameters = null;
  13770. }
  13771. return this;
  13772. };
  13773. return AbstractMesh;
  13774. }(BABYLON.Node));
  13775. // Statics
  13776. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13777. AbstractMesh._BILLBOARDMODE_X = 1;
  13778. AbstractMesh._BILLBOARDMODE_Y = 2;
  13779. AbstractMesh._BILLBOARDMODE_Z = 4;
  13780. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13781. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13782. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13783. BABYLON.AbstractMesh = AbstractMesh;
  13784. })(BABYLON || (BABYLON = {}));
  13785. //# sourceMappingURL=babylon.abstractMesh.js.map
  13786. var BABYLON;
  13787. (function (BABYLON) {
  13788. var Light = (function (_super) {
  13789. __extends(Light, _super);
  13790. /**
  13791. * Creates a Light object in the scene.
  13792. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13793. */
  13794. function Light(name, scene) {
  13795. var _this = _super.call(this, name, scene) || this;
  13796. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13797. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13798. _this.intensity = 1.0;
  13799. _this.range = Number.MAX_VALUE;
  13800. _this.includeOnlyWithLayerMask = 0;
  13801. _this.includedOnlyMeshes = new Array();
  13802. _this.excludedMeshes = new Array();
  13803. _this.excludeWithLayerMask = 0;
  13804. _this.lightmapMode = 0;
  13805. // PBR Properties.
  13806. _this.radius = 0.00001;
  13807. _this._excludedMeshesIds = new Array();
  13808. _this._includedOnlyMeshesIds = new Array();
  13809. _this.getScene().addLight(_this);
  13810. return _this;
  13811. }
  13812. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13813. /**
  13814. * If every light affecting the material is in this lightmapMode,
  13815. * material.lightmapTexture adds or multiplies
  13816. * (depends on material.useLightmapAsShadowmap)
  13817. * after every other light calculations.
  13818. */
  13819. get: function () {
  13820. return Light._LIGHTMAP_DEFAULT;
  13821. },
  13822. enumerable: true,
  13823. configurable: true
  13824. });
  13825. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13826. /**
  13827. * material.lightmapTexture as only diffuse lighting from this light
  13828. * adds pnly specular lighting from this light
  13829. * adds dynamic shadows
  13830. */
  13831. get: function () {
  13832. return Light._LIGHTMAP_SPECULAR;
  13833. },
  13834. enumerable: true,
  13835. configurable: true
  13836. });
  13837. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13838. /**
  13839. * material.lightmapTexture as only lighting
  13840. * no light calculation from this light
  13841. * only adds dynamic shadows from this light
  13842. */
  13843. get: function () {
  13844. return Light._LIGHTMAP_SHADOWSONLY;
  13845. },
  13846. enumerable: true,
  13847. configurable: true
  13848. });
  13849. /**
  13850. * Returns the string "Light".
  13851. */
  13852. Light.prototype.getClassName = function () {
  13853. return "Light";
  13854. };
  13855. /**
  13856. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13857. */
  13858. Light.prototype.toString = function (fullDetails) {
  13859. var ret = "Name: " + this.name;
  13860. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13861. if (this.animations) {
  13862. for (var i = 0; i < this.animations.length; i++) {
  13863. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13864. }
  13865. }
  13866. if (fullDetails) {
  13867. }
  13868. return ret;
  13869. };
  13870. /**
  13871. * Returns the Light associated shadow generator.
  13872. */
  13873. Light.prototype.getShadowGenerator = function () {
  13874. return this._shadowGenerator;
  13875. };
  13876. /**
  13877. * Returns a Vector3, the absolute light position in the World.
  13878. */
  13879. Light.prototype.getAbsolutePosition = function () {
  13880. return BABYLON.Vector3.Zero();
  13881. };
  13882. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13883. };
  13884. Light.prototype._getWorldMatrix = function () {
  13885. return BABYLON.Matrix.Identity();
  13886. };
  13887. /**
  13888. * Boolean : True if the light will affect the passed mesh.
  13889. */
  13890. Light.prototype.canAffectMesh = function (mesh) {
  13891. if (!mesh) {
  13892. return true;
  13893. }
  13894. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13895. return false;
  13896. }
  13897. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13898. return false;
  13899. }
  13900. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13901. return false;
  13902. }
  13903. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13904. return false;
  13905. }
  13906. return true;
  13907. };
  13908. /**
  13909. * Returns the light World matrix.
  13910. */
  13911. Light.prototype.getWorldMatrix = function () {
  13912. this._currentRenderId = this.getScene().getRenderId();
  13913. var worldMatrix = this._getWorldMatrix();
  13914. if (this.parent && this.parent.getWorldMatrix) {
  13915. if (!this._parentedWorldMatrix) {
  13916. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13917. }
  13918. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13919. this._markSyncedWithParent();
  13920. return this._parentedWorldMatrix;
  13921. }
  13922. return worldMatrix;
  13923. };
  13924. /**
  13925. * Disposes the light.
  13926. */
  13927. Light.prototype.dispose = function () {
  13928. if (this._shadowGenerator) {
  13929. this._shadowGenerator.dispose();
  13930. this._shadowGenerator = null;
  13931. }
  13932. // Animations
  13933. this.getScene().stopAnimation(this);
  13934. // Remove from scene
  13935. this.getScene().removeLight(this);
  13936. _super.prototype.dispose.call(this);
  13937. };
  13938. /**
  13939. * Returns the light type ID (integer).
  13940. */
  13941. Light.prototype.getTypeID = function () {
  13942. return 0;
  13943. };
  13944. /**
  13945. * Returns a new Light object, named "name", from the current one.
  13946. */
  13947. Light.prototype.clone = function (name) {
  13948. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13949. };
  13950. /**
  13951. * Serializes the current light into a Serialization object.
  13952. * Returns the serialized object.
  13953. */
  13954. Light.prototype.serialize = function () {
  13955. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13956. // Type
  13957. serializationObject.type = this.getTypeID();
  13958. // Parent
  13959. if (this.parent) {
  13960. serializationObject.parentId = this.parent.id;
  13961. }
  13962. // Inclusion / exclusions
  13963. if (this.excludedMeshes.length > 0) {
  13964. serializationObject.excludedMeshesIds = [];
  13965. this.excludedMeshes.forEach(function (mesh) {
  13966. serializationObject.excludedMeshesIds.push(mesh.id);
  13967. });
  13968. }
  13969. if (this.includedOnlyMeshes.length > 0) {
  13970. serializationObject.includedOnlyMeshesIds = [];
  13971. this.includedOnlyMeshes.forEach(function (mesh) {
  13972. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13973. });
  13974. }
  13975. // Animations
  13976. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13977. serializationObject.ranges = this.serializeAnimationRanges();
  13978. return serializationObject;
  13979. };
  13980. /**
  13981. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13982. * This new light is named "name" and added to the passed scene.
  13983. */
  13984. Light.GetConstructorFromName = function (type, name, scene) {
  13985. switch (type) {
  13986. case 0:
  13987. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13988. case 1:
  13989. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13990. case 2:
  13991. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13992. case 3:
  13993. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13994. }
  13995. };
  13996. /**
  13997. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13998. */
  13999. Light.Parse = function (parsedLight, scene) {
  14000. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14001. // Inclusion / exclusions
  14002. if (parsedLight.excludedMeshesIds) {
  14003. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14004. }
  14005. if (parsedLight.includedOnlyMeshesIds) {
  14006. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14007. }
  14008. // Parent
  14009. if (parsedLight.parentId) {
  14010. light._waitingParentId = parsedLight.parentId;
  14011. }
  14012. // Animations
  14013. if (parsedLight.animations) {
  14014. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14015. var parsedAnimation = parsedLight.animations[animationIndex];
  14016. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14017. }
  14018. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14019. }
  14020. if (parsedLight.autoAnimate) {
  14021. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14022. }
  14023. return light;
  14024. };
  14025. return Light;
  14026. }(BABYLON.Node));
  14027. //lightmapMode Consts
  14028. Light._LIGHTMAP_DEFAULT = 0;
  14029. Light._LIGHTMAP_SPECULAR = 1;
  14030. Light._LIGHTMAP_SHADOWSONLY = 2;
  14031. __decorate([
  14032. BABYLON.serializeAsColor3()
  14033. ], Light.prototype, "diffuse", void 0);
  14034. __decorate([
  14035. BABYLON.serializeAsColor3()
  14036. ], Light.prototype, "specular", void 0);
  14037. __decorate([
  14038. BABYLON.serialize()
  14039. ], Light.prototype, "intensity", void 0);
  14040. __decorate([
  14041. BABYLON.serialize()
  14042. ], Light.prototype, "range", void 0);
  14043. __decorate([
  14044. BABYLON.serialize()
  14045. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  14046. __decorate([
  14047. BABYLON.serialize()
  14048. ], Light.prototype, "excludeWithLayerMask", void 0);
  14049. __decorate([
  14050. BABYLON.serialize()
  14051. ], Light.prototype, "lightmapMode", void 0);
  14052. __decorate([
  14053. BABYLON.serialize()
  14054. ], Light.prototype, "radius", void 0);
  14055. BABYLON.Light = Light;
  14056. })(BABYLON || (BABYLON = {}));
  14057. //# sourceMappingURL=babylon.light.js.map
  14058. var BABYLON;
  14059. (function (BABYLON) {
  14060. var PointLight = (function (_super) {
  14061. __extends(PointLight, _super);
  14062. /**
  14063. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14064. * A PointLight emits the light in every direction.
  14065. * It can cast shadows.
  14066. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14067. * ```javascript
  14068. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14069. * ```
  14070. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14071. */
  14072. function PointLight(name, position, scene) {
  14073. var _this = _super.call(this, name, scene) || this;
  14074. _this.position = position;
  14075. return _this;
  14076. }
  14077. /**
  14078. * Returns the string "PointLight"
  14079. */
  14080. PointLight.prototype.getClassName = function () {
  14081. return "PointLight";
  14082. };
  14083. /**
  14084. * Returns a Vector3, the PointLight absolute position in the World.
  14085. */
  14086. PointLight.prototype.getAbsolutePosition = function () {
  14087. return this.transformedPosition ? this.transformedPosition : this.position;
  14088. };
  14089. /**
  14090. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14091. */
  14092. PointLight.prototype.computeTransformedPosition = function () {
  14093. if (this.parent && this.parent.getWorldMatrix) {
  14094. if (!this.transformedPosition) {
  14095. this.transformedPosition = BABYLON.Vector3.Zero();
  14096. }
  14097. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14098. return true;
  14099. }
  14100. return false;
  14101. };
  14102. /**
  14103. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14104. * Returns the PointLight.
  14105. */
  14106. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14107. if (this.parent && this.parent.getWorldMatrix) {
  14108. this.computeTransformedPosition();
  14109. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14110. return this;
  14111. }
  14112. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14113. return this;
  14114. };
  14115. /**
  14116. * Boolean : returns true by default.
  14117. */
  14118. PointLight.prototype.needCube = function () {
  14119. return true;
  14120. };
  14121. /**
  14122. * Boolean : returns false by default.
  14123. */
  14124. PointLight.prototype.needRefreshPerFrame = function () {
  14125. return false;
  14126. };
  14127. /**
  14128. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14129. */
  14130. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14131. switch (faceIndex) {
  14132. case 0:
  14133. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14134. case 1:
  14135. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14136. case 2:
  14137. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14138. case 3:
  14139. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14140. case 4:
  14141. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14142. case 5:
  14143. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14144. }
  14145. return BABYLON.Vector3.Zero();
  14146. };
  14147. /**
  14148. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14149. * - fov = PI / 2
  14150. * - aspect ratio : 1.0
  14151. * - z-near and far equal to the active camera minZ and maxZ.
  14152. * Returns the PointLight.
  14153. */
  14154. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14155. if (this.customProjectionMatrixBuilder) {
  14156. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14157. }
  14158. else {
  14159. var activeCamera = this.getScene().activeCamera;
  14160. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14161. }
  14162. return this;
  14163. };
  14164. PointLight.prototype._getWorldMatrix = function () {
  14165. if (!this._worldMatrix) {
  14166. this._worldMatrix = BABYLON.Matrix.Identity();
  14167. }
  14168. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14169. return this._worldMatrix;
  14170. };
  14171. /**
  14172. * Returns the integer 0.
  14173. */
  14174. PointLight.prototype.getTypeID = function () {
  14175. return 0;
  14176. };
  14177. return PointLight;
  14178. }(BABYLON.Light));
  14179. __decorate([
  14180. BABYLON.serializeAsVector3()
  14181. ], PointLight.prototype, "position", void 0);
  14182. __decorate([
  14183. BABYLON.serialize()
  14184. ], PointLight.prototype, "shadowMinZ", void 0);
  14185. __decorate([
  14186. BABYLON.serialize()
  14187. ], PointLight.prototype, "shadowMaxZ", void 0);
  14188. BABYLON.PointLight = PointLight;
  14189. })(BABYLON || (BABYLON = {}));
  14190. //# sourceMappingURL=babylon.pointLight.js.map
  14191. var BABYLON;
  14192. (function (BABYLON) {
  14193. var SpotLight = (function (_super) {
  14194. __extends(SpotLight, _super);
  14195. /**
  14196. * Creates a SpotLight object in the scene with the passed parameters :
  14197. * - `position` (Vector3) is the initial SpotLight position,
  14198. * - `direction` (Vector3) is the initial SpotLight direction,
  14199. * - `angle` (float, in radians) is the spot light cone angle,
  14200. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14201. * A spot light is a simply light oriented cone.
  14202. * It can cast shadows.
  14203. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14204. */
  14205. function SpotLight(name, position, direction, angle, exponent, scene) {
  14206. var _this = _super.call(this, name, scene) || this;
  14207. _this.position = position;
  14208. _this.direction = direction;
  14209. _this.angle = angle;
  14210. _this.exponent = exponent;
  14211. return _this;
  14212. }
  14213. /**
  14214. * Returns the string "SpotLight".
  14215. */
  14216. SpotLight.prototype.getClassName = function () {
  14217. return "SpotLight";
  14218. };
  14219. /**
  14220. * Returns the SpotLight absolute position in the World (Vector3).
  14221. */
  14222. SpotLight.prototype.getAbsolutePosition = function () {
  14223. return this.transformedPosition ? this.transformedPosition : this.position;
  14224. };
  14225. /**
  14226. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  14227. * Returns the SpotLight.
  14228. */
  14229. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14230. if (this.customProjectionMatrixBuilder) {
  14231. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14232. }
  14233. else {
  14234. var activeCamera = this.getScene().activeCamera;
  14235. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14236. }
  14237. return this;
  14238. };
  14239. /**
  14240. * Boolean : false by default.
  14241. */
  14242. SpotLight.prototype.needCube = function () {
  14243. return false;
  14244. };
  14245. /**
  14246. * Boolean : false by default.
  14247. */
  14248. SpotLight.prototype.needRefreshPerFrame = function () {
  14249. return false;
  14250. };
  14251. /**
  14252. * Returns the SpotLight direction (Vector3) for any passed face index.
  14253. */
  14254. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14255. return this.direction;
  14256. };
  14257. /**
  14258. * Updates the SpotLight direction towards the passed target (Vector3).
  14259. * Returns the updated direction.
  14260. */
  14261. SpotLight.prototype.setDirectionToTarget = function (target) {
  14262. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14263. return this.direction;
  14264. };
  14265. /**
  14266. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14267. */
  14268. SpotLight.prototype.computeTransformedPosition = function () {
  14269. if (this.parent && this.parent.getWorldMatrix) {
  14270. if (!this.transformedPosition) {
  14271. this.transformedPosition = BABYLON.Vector3.Zero();
  14272. }
  14273. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14274. return true;
  14275. }
  14276. return false;
  14277. };
  14278. /**
  14279. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14280. * Return the SpotLight.
  14281. */
  14282. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14283. var normalizeDirection;
  14284. if (this.parent && this.parent.getWorldMatrix) {
  14285. if (!this._transformedDirection) {
  14286. this._transformedDirection = BABYLON.Vector3.Zero();
  14287. }
  14288. this.computeTransformedPosition();
  14289. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14290. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14291. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14292. }
  14293. else {
  14294. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14295. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14296. }
  14297. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14298. return this;
  14299. };
  14300. SpotLight.prototype._getWorldMatrix = function () {
  14301. if (!this._worldMatrix) {
  14302. this._worldMatrix = BABYLON.Matrix.Identity();
  14303. }
  14304. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14305. return this._worldMatrix;
  14306. };
  14307. /**
  14308. * Returns the integer 2.
  14309. */
  14310. SpotLight.prototype.getTypeID = function () {
  14311. return 2;
  14312. };
  14313. /**
  14314. * Returns the SpotLight rotation (Vector3).
  14315. */
  14316. SpotLight.prototype.getRotation = function () {
  14317. this.direction.normalize();
  14318. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14319. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14320. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14321. };
  14322. return SpotLight;
  14323. }(BABYLON.Light));
  14324. __decorate([
  14325. BABYLON.serializeAsVector3()
  14326. ], SpotLight.prototype, "position", void 0);
  14327. __decorate([
  14328. BABYLON.serializeAsVector3()
  14329. ], SpotLight.prototype, "direction", void 0);
  14330. __decorate([
  14331. BABYLON.serialize()
  14332. ], SpotLight.prototype, "angle", void 0);
  14333. __decorate([
  14334. BABYLON.serialize()
  14335. ], SpotLight.prototype, "exponent", void 0);
  14336. __decorate([
  14337. BABYLON.serialize()
  14338. ], SpotLight.prototype, "shadowMinZ", void 0);
  14339. __decorate([
  14340. BABYLON.serialize()
  14341. ], SpotLight.prototype, "shadowMaxZ", void 0);
  14342. BABYLON.SpotLight = SpotLight;
  14343. })(BABYLON || (BABYLON = {}));
  14344. //# sourceMappingURL=babylon.spotLight.js.map
  14345. var BABYLON;
  14346. (function (BABYLON) {
  14347. var HemisphericLight = (function (_super) {
  14348. __extends(HemisphericLight, _super);
  14349. /**
  14350. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14351. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14352. * The HemisphericLight can't cast shadows.
  14353. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14354. */
  14355. function HemisphericLight(name, direction, scene) {
  14356. var _this = _super.call(this, name, scene) || this;
  14357. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14358. _this.direction = direction;
  14359. return _this;
  14360. }
  14361. /**
  14362. * Returns the string "HemisphericLight".
  14363. */
  14364. HemisphericLight.prototype.getClassName = function () {
  14365. return "HemisphericLight";
  14366. };
  14367. /**
  14368. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14369. * Returns the updated direction.
  14370. */
  14371. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14372. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14373. return this.direction;
  14374. };
  14375. HemisphericLight.prototype.getShadowGenerator = function () {
  14376. return null;
  14377. };
  14378. /**
  14379. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14380. * Returns the HemisphericLight.
  14381. */
  14382. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14383. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14384. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14385. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14386. return this;
  14387. };
  14388. HemisphericLight.prototype._getWorldMatrix = function () {
  14389. if (!this._worldMatrix) {
  14390. this._worldMatrix = BABYLON.Matrix.Identity();
  14391. }
  14392. return this._worldMatrix;
  14393. };
  14394. /**
  14395. * Returns the integer 3.
  14396. */
  14397. HemisphericLight.prototype.getTypeID = function () {
  14398. return 3;
  14399. };
  14400. return HemisphericLight;
  14401. }(BABYLON.Light));
  14402. __decorate([
  14403. BABYLON.serializeAsColor3()
  14404. ], HemisphericLight.prototype, "groundColor", void 0);
  14405. __decorate([
  14406. BABYLON.serializeAsVector3()
  14407. ], HemisphericLight.prototype, "direction", void 0);
  14408. BABYLON.HemisphericLight = HemisphericLight;
  14409. })(BABYLON || (BABYLON = {}));
  14410. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14411. /// <reference path="babylon.light.ts" />
  14412. var BABYLON;
  14413. (function (BABYLON) {
  14414. var DirectionalLight = (function (_super) {
  14415. __extends(DirectionalLight, _super);
  14416. /**
  14417. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14418. * The directional light is emitted from everywhere in the given direction.
  14419. * It can cast shawdows.
  14420. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14421. */
  14422. function DirectionalLight(name, direction, scene) {
  14423. var _this = _super.call(this, name, scene) || this;
  14424. _this.shadowOrthoScale = 0.5;
  14425. _this.autoUpdateExtends = true;
  14426. // Cache
  14427. _this._orthoLeft = Number.MAX_VALUE;
  14428. _this._orthoRight = Number.MIN_VALUE;
  14429. _this._orthoTop = Number.MIN_VALUE;
  14430. _this._orthoBottom = Number.MAX_VALUE;
  14431. _this.position = direction.scale(-1.0);
  14432. _this.direction = direction;
  14433. return _this;
  14434. }
  14435. /**
  14436. * Returns the string "DirectionalLight".
  14437. */
  14438. DirectionalLight.prototype.getClassName = function () {
  14439. return "DirectionalLight";
  14440. };
  14441. /**
  14442. * Returns the DirectionalLight absolute position in the World.
  14443. */
  14444. DirectionalLight.prototype.getAbsolutePosition = function () {
  14445. return this.transformedPosition ? this.transformedPosition : this.position;
  14446. };
  14447. /**
  14448. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14449. * Returns the updated DirectionalLight direction (Vector3).
  14450. */
  14451. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14452. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14453. return this.direction;
  14454. };
  14455. /**
  14456. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14457. * Returns the DirectionalLight.
  14458. */
  14459. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14460. if (this.customProjectionMatrixBuilder) {
  14461. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14462. }
  14463. else {
  14464. var activeCamera = this.getScene().activeCamera;
  14465. // Check extends
  14466. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14467. var tempVector3 = BABYLON.Vector3.Zero();
  14468. this._orthoLeft = Number.MAX_VALUE;
  14469. this._orthoRight = Number.MIN_VALUE;
  14470. this._orthoTop = Number.MIN_VALUE;
  14471. this._orthoBottom = Number.MAX_VALUE;
  14472. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14473. var mesh = renderList[meshIndex];
  14474. if (!mesh) {
  14475. continue;
  14476. }
  14477. var boundingInfo = mesh.getBoundingInfo();
  14478. if (!boundingInfo) {
  14479. continue;
  14480. }
  14481. var boundingBox = boundingInfo.boundingBox;
  14482. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14483. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14484. if (tempVector3.x < this._orthoLeft)
  14485. this._orthoLeft = tempVector3.x;
  14486. if (tempVector3.y < this._orthoBottom)
  14487. this._orthoBottom = tempVector3.y;
  14488. if (tempVector3.x > this._orthoRight)
  14489. this._orthoRight = tempVector3.x;
  14490. if (tempVector3.y > this._orthoTop)
  14491. this._orthoTop = tempVector3.y;
  14492. }
  14493. }
  14494. }
  14495. var xOffset = this._orthoRight - this._orthoLeft;
  14496. var yOffset = this._orthoTop - this._orthoBottom;
  14497. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14498. }
  14499. return this;
  14500. };
  14501. /**
  14502. * Boolean : true by default.
  14503. */
  14504. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14505. return true;
  14506. };
  14507. /**
  14508. * Boolean : false by default.
  14509. */
  14510. DirectionalLight.prototype.needCube = function () {
  14511. return false;
  14512. };
  14513. /**
  14514. * Returns the light direction (Vector3) for any passed face index.
  14515. */
  14516. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14517. return this.direction;
  14518. };
  14519. /**
  14520. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14521. */
  14522. DirectionalLight.prototype.computeTransformedPosition = function () {
  14523. if (this.parent && this.parent.getWorldMatrix) {
  14524. if (!this.transformedPosition) {
  14525. this.transformedPosition = BABYLON.Vector3.Zero();
  14526. }
  14527. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14528. return true;
  14529. }
  14530. return false;
  14531. };
  14532. /**
  14533. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14534. * Returns the DirectionalLight.
  14535. */
  14536. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14537. if (this.parent && this.parent.getWorldMatrix) {
  14538. if (!this._transformedDirection) {
  14539. this._transformedDirection = BABYLON.Vector3.Zero();
  14540. }
  14541. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14542. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14543. return this;
  14544. }
  14545. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14546. return this;
  14547. };
  14548. DirectionalLight.prototype._getWorldMatrix = function () {
  14549. if (!this._worldMatrix) {
  14550. this._worldMatrix = BABYLON.Matrix.Identity();
  14551. }
  14552. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14553. return this._worldMatrix;
  14554. };
  14555. /**
  14556. * Returns the integer 1.
  14557. */
  14558. DirectionalLight.prototype.getTypeID = function () {
  14559. return 1;
  14560. };
  14561. return DirectionalLight;
  14562. }(BABYLON.Light));
  14563. __decorate([
  14564. BABYLON.serializeAsVector3()
  14565. ], DirectionalLight.prototype, "position", void 0);
  14566. __decorate([
  14567. BABYLON.serializeAsVector3()
  14568. ], DirectionalLight.prototype, "direction", void 0);
  14569. __decorate([
  14570. BABYLON.serialize()
  14571. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14572. __decorate([
  14573. BABYLON.serialize()
  14574. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14575. __decorate([
  14576. BABYLON.serialize()
  14577. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  14578. __decorate([
  14579. BABYLON.serialize()
  14580. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  14581. BABYLON.DirectionalLight = DirectionalLight;
  14582. })(BABYLON || (BABYLON = {}));
  14583. //# sourceMappingURL=babylon.directionalLight.js.map
  14584. var BABYLON;
  14585. (function (BABYLON) {
  14586. var ShadowGenerator = (function () {
  14587. /**
  14588. * Creates a ShadowGenerator object.
  14589. * A ShadowGenerator is the required tool to use the shadows.
  14590. * Each light casting shadows needs to use its own ShadowGenerator.
  14591. * Required parameters :
  14592. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14593. * - `light` : the light object generating the shadows.
  14594. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14595. */
  14596. function ShadowGenerator(mapSize, light) {
  14597. var _this = this;
  14598. // Members
  14599. this._filter = ShadowGenerator.FILTER_NONE;
  14600. this.blurScale = 2;
  14601. this._blurBoxOffset = 0;
  14602. this._bias = 0.00005;
  14603. this._lightDirection = BABYLON.Vector3.Zero();
  14604. this._depthScale = 30.0;
  14605. this.forceBackFacesOnly = false;
  14606. this._darkness = 0;
  14607. this._transparencyShadow = false;
  14608. this._viewMatrix = BABYLON.Matrix.Zero();
  14609. this._projectionMatrix = BABYLON.Matrix.Zero();
  14610. this._transformMatrix = BABYLON.Matrix.Zero();
  14611. this._worldViewProjection = BABYLON.Matrix.Zero();
  14612. this._currentFaceIndex = 0;
  14613. this._currentFaceIndexCache = 0;
  14614. this._useFullFloat = true;
  14615. this._light = light;
  14616. this._scene = light.getScene();
  14617. this._mapSize = mapSize;
  14618. light._shadowGenerator = this;
  14619. // Texture type fallback from float to int if not supported.
  14620. var textureType;
  14621. var caps = this._scene.getEngine().getCaps();
  14622. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14623. this._useFullFloat = true;
  14624. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14625. }
  14626. else {
  14627. this._useFullFloat = false;
  14628. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14629. }
  14630. // Render target
  14631. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14632. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14633. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14634. this._shadowMap.anisotropicFilteringLevel = 1;
  14635. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14636. this._shadowMap.renderParticles = false;
  14637. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14638. _this._currentFaceIndex = faceIndex;
  14639. });
  14640. this._shadowMap.onAfterUnbindObservable.add(function () {
  14641. if (!_this.useBlurExponentialShadowMap) {
  14642. return;
  14643. }
  14644. if (!_this._shadowMap2) {
  14645. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14646. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14647. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14648. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14649. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  14650. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14651. effect.setTexture("textureSampler", _this._shadowMap);
  14652. });
  14653. _this.blurBoxOffset = 1;
  14654. }
  14655. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14656. });
  14657. // Custom render function
  14658. var renderSubMesh = function (subMesh) {
  14659. var mesh = subMesh.getRenderingMesh();
  14660. var scene = _this._scene;
  14661. var engine = scene.getEngine();
  14662. // Culling
  14663. engine.setState(subMesh.getMaterial().backFaceCulling);
  14664. // Managing instances
  14665. var batch = mesh._getInstancesRenderList(subMesh._id);
  14666. if (batch.mustReturn) {
  14667. return;
  14668. }
  14669. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14670. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14671. engine.enableEffect(_this._effect);
  14672. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14673. var material = subMesh.getMaterial();
  14674. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  14675. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14676. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14677. if (_this.getLight().needCube()) {
  14678. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14679. }
  14680. // Alpha test
  14681. if (material && material.needAlphaTesting()) {
  14682. var alphaTexture = material.getAlphaTestTexture();
  14683. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14684. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14685. }
  14686. // Bones
  14687. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14688. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14689. }
  14690. if (_this.forceBackFacesOnly) {
  14691. engine.setState(true, 0, false, true);
  14692. }
  14693. // Draw
  14694. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14695. if (_this.forceBackFacesOnly) {
  14696. engine.setState(true, 0, false, false);
  14697. }
  14698. }
  14699. else {
  14700. // Need to reset refresh rate of the shadowMap
  14701. _this._shadowMap.resetRefreshCounter();
  14702. }
  14703. };
  14704. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14705. var index;
  14706. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14707. renderSubMesh(opaqueSubMeshes.data[index]);
  14708. }
  14709. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14710. renderSubMesh(alphaTestSubMeshes.data[index]);
  14711. }
  14712. if (_this._transparencyShadow) {
  14713. for (index = 0; index < transparentSubMeshes.length; index++) {
  14714. renderSubMesh(transparentSubMeshes.data[index]);
  14715. }
  14716. }
  14717. };
  14718. this._shadowMap.onClearObservable.add(function (engine) {
  14719. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  14720. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14721. }
  14722. else {
  14723. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14724. }
  14725. });
  14726. }
  14727. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14728. // Static
  14729. get: function () {
  14730. return ShadowGenerator._FILTER_NONE;
  14731. },
  14732. enumerable: true,
  14733. configurable: true
  14734. });
  14735. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14736. get: function () {
  14737. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14738. },
  14739. enumerable: true,
  14740. configurable: true
  14741. });
  14742. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  14743. get: function () {
  14744. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  14745. },
  14746. enumerable: true,
  14747. configurable: true
  14748. });
  14749. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  14750. get: function () {
  14751. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  14752. },
  14753. enumerable: true,
  14754. configurable: true
  14755. });
  14756. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14757. get: function () {
  14758. return this._bias;
  14759. },
  14760. set: function (bias) {
  14761. this._bias = bias;
  14762. },
  14763. enumerable: true,
  14764. configurable: true
  14765. });
  14766. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14767. get: function () {
  14768. return this._blurBoxOffset;
  14769. },
  14770. set: function (value) {
  14771. var _this = this;
  14772. if (this._blurBoxOffset === value) {
  14773. return;
  14774. }
  14775. this._blurBoxOffset = value;
  14776. if (this._boxBlurPostprocess) {
  14777. this._boxBlurPostprocess.dispose();
  14778. }
  14779. var textureType;
  14780. var caps = this._scene.getEngine().getCaps();
  14781. if (this._useFullFloat) {
  14782. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14783. }
  14784. else {
  14785. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14786. }
  14787. 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, textureType);
  14788. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14789. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14790. });
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  14796. get: function () {
  14797. return this._depthScale;
  14798. },
  14799. set: function (value) {
  14800. this._depthScale = value;
  14801. },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14806. get: function () {
  14807. return this._filter;
  14808. },
  14809. set: function (value) {
  14810. if (this._filter === value) {
  14811. return;
  14812. }
  14813. this._filter = value;
  14814. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  14815. this._shadowMap.anisotropicFilteringLevel = 16;
  14816. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14817. }
  14818. else {
  14819. this._shadowMap.anisotropicFilteringLevel = 1;
  14820. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14821. }
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14827. get: function () {
  14828. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  14829. return this.useExponentialShadowMap;
  14830. },
  14831. set: function (value) {
  14832. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  14833. this.useExponentialShadowMap = value;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  14839. get: function () {
  14840. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  14841. },
  14842. set: function (value) {
  14843. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14844. },
  14845. enumerable: true,
  14846. configurable: true
  14847. });
  14848. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14849. get: function () {
  14850. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  14851. },
  14852. set: function (value) {
  14853. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14859. get: function () {
  14860. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  14861. return this.useBlurExponentialShadowMap;
  14862. },
  14863. set: function (value) {
  14864. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  14865. this.useBlurExponentialShadowMap = value;
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  14871. get: function () {
  14872. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  14873. },
  14874. set: function (value) {
  14875. if (this._light.needCube() && value) {
  14876. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  14877. }
  14878. else {
  14879. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14880. }
  14881. },
  14882. enumerable: true,
  14883. configurable: true
  14884. });
  14885. /**
  14886. * Boolean : true when the ShadowGenerator is finally computed.
  14887. */
  14888. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14889. var defines = [];
  14890. if (this._useFullFloat) {
  14891. defines.push("#define FULLFLOAT");
  14892. }
  14893. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  14894. defines.push("#define ESM");
  14895. }
  14896. if (this.getLight().needCube()) {
  14897. defines.push("#define CUBEMAP");
  14898. }
  14899. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14900. var mesh = subMesh.getMesh();
  14901. var material = subMesh.getMaterial();
  14902. // Alpha test
  14903. if (material && material.needAlphaTesting()) {
  14904. defines.push("#define ALPHATEST");
  14905. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14906. attribs.push(BABYLON.VertexBuffer.UVKind);
  14907. defines.push("#define UV1");
  14908. }
  14909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14910. var alphaTexture = material.getAlphaTestTexture();
  14911. if (alphaTexture.coordinatesIndex === 1) {
  14912. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14913. defines.push("#define UV2");
  14914. }
  14915. }
  14916. }
  14917. // Bones
  14918. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14919. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14920. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14921. if (mesh.numBoneInfluencers > 4) {
  14922. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14923. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14924. }
  14925. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14926. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14927. }
  14928. else {
  14929. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14930. }
  14931. // Instances
  14932. if (useInstances) {
  14933. defines.push("#define INSTANCES");
  14934. attribs.push("world0");
  14935. attribs.push("world1");
  14936. attribs.push("world2");
  14937. attribs.push("world3");
  14938. }
  14939. // Get correct effect
  14940. var join = defines.join("\n");
  14941. if (this._cachedDefines !== join) {
  14942. this._cachedDefines = join;
  14943. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  14944. }
  14945. return this._effect.isReady();
  14946. };
  14947. /**
  14948. * Returns a RenderTargetTexture object : the shadow map texture.
  14949. */
  14950. ShadowGenerator.prototype.getShadowMap = function () {
  14951. return this._shadowMap;
  14952. };
  14953. /**
  14954. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14955. */
  14956. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14957. if (this._shadowMap2) {
  14958. return this._shadowMap2;
  14959. }
  14960. return this._shadowMap;
  14961. };
  14962. /**
  14963. * Returns the associated light object.
  14964. */
  14965. ShadowGenerator.prototype.getLight = function () {
  14966. return this._light;
  14967. };
  14968. // Methods
  14969. /**
  14970. * Returns a Matrix object : the updated transformation matrix.
  14971. */
  14972. ShadowGenerator.prototype.getTransformMatrix = function () {
  14973. var scene = this._scene;
  14974. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14975. return this._transformMatrix;
  14976. }
  14977. this._currentRenderID = scene.getRenderId();
  14978. this._currentFaceIndexCache = this._currentFaceIndex;
  14979. var lightPosition = this._light.position;
  14980. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14981. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14982. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14983. }
  14984. if (this._light.computeTransformedPosition()) {
  14985. lightPosition = this._light.transformedPosition;
  14986. }
  14987. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14988. this._cachedPosition = lightPosition.clone();
  14989. this._cachedDirection = this._lightDirection.clone();
  14990. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14991. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14993. }
  14994. return this._transformMatrix;
  14995. };
  14996. /**
  14997. * Returns the darkness value (float).
  14998. */
  14999. ShadowGenerator.prototype.getDarkness = function () {
  15000. return this._darkness;
  15001. };
  15002. /**
  15003. * Sets the ShadowGenerator darkness value (float <= 1.0).
  15004. * Returns the ShadowGenerator.
  15005. */
  15006. ShadowGenerator.prototype.setDarkness = function (darkness) {
  15007. if (darkness >= 1.0)
  15008. this._darkness = 1.0;
  15009. else if (darkness <= 0.0)
  15010. this._darkness = 0.0;
  15011. else
  15012. this._darkness = darkness;
  15013. return this;
  15014. };
  15015. /**
  15016. * Sets the ability to have transparent shadow (boolean).
  15017. * Returns the ShadowGenerator.
  15018. */
  15019. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  15020. this._transparencyShadow = hasShadow;
  15021. return this;
  15022. };
  15023. ShadowGenerator.prototype._packHalf = function (depth) {
  15024. var scale = depth * 255.0;
  15025. var fract = scale - Math.floor(scale);
  15026. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  15027. };
  15028. /**
  15029. * Disposes the ShadowGenerator.
  15030. * Returns nothing.
  15031. */
  15032. ShadowGenerator.prototype.dispose = function () {
  15033. this._shadowMap.dispose();
  15034. if (this._shadowMap2) {
  15035. this._shadowMap2.dispose();
  15036. }
  15037. if (this._downSamplePostprocess) {
  15038. this._downSamplePostprocess.dispose();
  15039. }
  15040. if (this._boxBlurPostprocess) {
  15041. this._boxBlurPostprocess.dispose();
  15042. }
  15043. this._light._shadowGenerator = null;
  15044. };
  15045. /**
  15046. * Serializes the ShadowGenerator and returns a serializationObject.
  15047. */
  15048. ShadowGenerator.prototype.serialize = function () {
  15049. var serializationObject = {};
  15050. serializationObject.lightId = this._light.id;
  15051. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15052. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  15053. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  15054. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15055. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15056. serializationObject.darkness = this.getDarkness();
  15057. serializationObject.renderList = [];
  15058. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15059. var mesh = this.getShadowMap().renderList[meshIndex];
  15060. serializationObject.renderList.push(mesh.id);
  15061. }
  15062. return serializationObject;
  15063. };
  15064. /**
  15065. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15066. */
  15067. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15068. //casting to point light, as light is missing the position attr and typescript complains.
  15069. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15070. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15071. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15072. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15073. meshes.forEach(function (mesh) {
  15074. shadowGenerator.getShadowMap().renderList.push(mesh);
  15075. });
  15076. }
  15077. if (parsedShadowGenerator.usePoissonSampling) {
  15078. shadowGenerator.usePoissonSampling = true;
  15079. }
  15080. else if (parsedShadowGenerator.useExponentialShadowMap) {
  15081. shadowGenerator.useExponentialShadowMap = true;
  15082. }
  15083. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  15084. shadowGenerator.useBlurExponentialShadowMap = true;
  15085. }
  15086. if (parsedShadowGenerator.blurScale) {
  15087. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15088. }
  15089. if (parsedShadowGenerator.blurBoxOffset) {
  15090. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15091. }
  15092. if (parsedShadowGenerator.bias !== undefined) {
  15093. shadowGenerator.bias = parsedShadowGenerator.bias;
  15094. }
  15095. if (parsedShadowGenerator.darkness) {
  15096. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15097. }
  15098. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15099. return shadowGenerator;
  15100. };
  15101. return ShadowGenerator;
  15102. }());
  15103. ShadowGenerator._FILTER_NONE = 0;
  15104. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  15105. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15106. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  15107. BABYLON.ShadowGenerator = ShadowGenerator;
  15108. })(BABYLON || (BABYLON = {}));
  15109. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15110. var BABYLON;
  15111. (function (BABYLON) {
  15112. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15113. if (boxMin.x > sphereCenter.x + sphereRadius)
  15114. return false;
  15115. if (sphereCenter.x - sphereRadius > boxMax.x)
  15116. return false;
  15117. if (boxMin.y > sphereCenter.y + sphereRadius)
  15118. return false;
  15119. if (sphereCenter.y - sphereRadius > boxMax.y)
  15120. return false;
  15121. if (boxMin.z > sphereCenter.z + sphereRadius)
  15122. return false;
  15123. if (sphereCenter.z - sphereRadius > boxMax.z)
  15124. return false;
  15125. return true;
  15126. };
  15127. var getLowestRoot = (function () {
  15128. var result = { root: 0, found: false };
  15129. return function (a, b, c, maxR) {
  15130. result.root = 0;
  15131. result.found = false;
  15132. var determinant = b * b - 4.0 * a * c;
  15133. if (determinant < 0)
  15134. return result;
  15135. var sqrtD = Math.sqrt(determinant);
  15136. var r1 = (-b - sqrtD) / (2.0 * a);
  15137. var r2 = (-b + sqrtD) / (2.0 * a);
  15138. if (r1 > r2) {
  15139. var temp = r2;
  15140. r2 = r1;
  15141. r1 = temp;
  15142. }
  15143. if (r1 > 0 && r1 < maxR) {
  15144. result.root = r1;
  15145. result.found = true;
  15146. return result;
  15147. }
  15148. if (r2 > 0 && r2 < maxR) {
  15149. result.root = r2;
  15150. result.found = true;
  15151. return result;
  15152. }
  15153. return result;
  15154. };
  15155. })();
  15156. var Collider = (function () {
  15157. function Collider() {
  15158. this.radius = new BABYLON.Vector3(1, 1, 1);
  15159. this.retry = 0;
  15160. this.basePointWorld = BABYLON.Vector3.Zero();
  15161. this.velocityWorld = BABYLON.Vector3.Zero();
  15162. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15163. this._collisionPoint = BABYLON.Vector3.Zero();
  15164. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15165. this._tempVector = BABYLON.Vector3.Zero();
  15166. this._tempVector2 = BABYLON.Vector3.Zero();
  15167. this._tempVector3 = BABYLON.Vector3.Zero();
  15168. this._tempVector4 = BABYLON.Vector3.Zero();
  15169. this._edge = BABYLON.Vector3.Zero();
  15170. this._baseToVertex = BABYLON.Vector3.Zero();
  15171. this._destinationPoint = BABYLON.Vector3.Zero();
  15172. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15173. this._displacementVector = BABYLON.Vector3.Zero();
  15174. this._collisionMask = -1;
  15175. }
  15176. Object.defineProperty(Collider.prototype, "collisionMask", {
  15177. get: function () {
  15178. return this._collisionMask;
  15179. },
  15180. set: function (mask) {
  15181. this._collisionMask = !isNaN(mask) ? mask : -1;
  15182. },
  15183. enumerable: true,
  15184. configurable: true
  15185. });
  15186. // Methods
  15187. Collider.prototype._initialize = function (source, dir, e) {
  15188. this.velocity = dir;
  15189. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15190. this.basePoint = source;
  15191. source.multiplyToRef(this.radius, this.basePointWorld);
  15192. dir.multiplyToRef(this.radius, this.velocityWorld);
  15193. this.velocityWorldLength = this.velocityWorld.length();
  15194. this.epsilon = e;
  15195. this.collisionFound = false;
  15196. };
  15197. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15198. pa.subtractToRef(point, this._tempVector);
  15199. pb.subtractToRef(point, this._tempVector2);
  15200. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15201. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15202. if (d < 0)
  15203. return false;
  15204. pc.subtractToRef(point, this._tempVector3);
  15205. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15206. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15207. if (d < 0)
  15208. return false;
  15209. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15210. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15211. return d >= 0;
  15212. };
  15213. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15214. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15215. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15216. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15217. return false;
  15218. }
  15219. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15220. return false;
  15221. return true;
  15222. };
  15223. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15224. var t0;
  15225. var embeddedInPlane = false;
  15226. //defensive programming, actually not needed.
  15227. if (!trianglePlaneArray) {
  15228. trianglePlaneArray = [];
  15229. }
  15230. if (!trianglePlaneArray[faceIndex]) {
  15231. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15232. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15233. }
  15234. var trianglePlane = trianglePlaneArray[faceIndex];
  15235. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15236. return;
  15237. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15238. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15239. if (normalDotVelocity == 0) {
  15240. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15241. return;
  15242. embeddedInPlane = true;
  15243. t0 = 0;
  15244. }
  15245. else {
  15246. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15247. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15248. if (t0 > t1) {
  15249. var temp = t1;
  15250. t1 = t0;
  15251. t0 = temp;
  15252. }
  15253. if (t0 > 1.0 || t1 < 0.0)
  15254. return;
  15255. if (t0 < 0)
  15256. t0 = 0;
  15257. if (t0 > 1.0)
  15258. t0 = 1.0;
  15259. }
  15260. this._collisionPoint.copyFromFloats(0, 0, 0);
  15261. var found = false;
  15262. var t = 1.0;
  15263. if (!embeddedInPlane) {
  15264. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15265. this.velocity.scaleToRef(t0, this._tempVector);
  15266. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15267. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15268. found = true;
  15269. t = t0;
  15270. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15271. }
  15272. }
  15273. if (!found) {
  15274. var velocitySquaredLength = this.velocity.lengthSquared();
  15275. var a = velocitySquaredLength;
  15276. this.basePoint.subtractToRef(p1, this._tempVector);
  15277. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15278. var c = this._tempVector.lengthSquared() - 1.0;
  15279. var lowestRoot = getLowestRoot(a, b, c, t);
  15280. if (lowestRoot.found) {
  15281. t = lowestRoot.root;
  15282. found = true;
  15283. this._collisionPoint.copyFrom(p1);
  15284. }
  15285. this.basePoint.subtractToRef(p2, this._tempVector);
  15286. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15287. c = this._tempVector.lengthSquared() - 1.0;
  15288. lowestRoot = getLowestRoot(a, b, c, t);
  15289. if (lowestRoot.found) {
  15290. t = lowestRoot.root;
  15291. found = true;
  15292. this._collisionPoint.copyFrom(p2);
  15293. }
  15294. this.basePoint.subtractToRef(p3, this._tempVector);
  15295. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15296. c = this._tempVector.lengthSquared() - 1.0;
  15297. lowestRoot = getLowestRoot(a, b, c, t);
  15298. if (lowestRoot.found) {
  15299. t = lowestRoot.root;
  15300. found = true;
  15301. this._collisionPoint.copyFrom(p3);
  15302. }
  15303. p2.subtractToRef(p1, this._edge);
  15304. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15305. var edgeSquaredLength = this._edge.lengthSquared();
  15306. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15307. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15308. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15309. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15310. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15311. lowestRoot = getLowestRoot(a, b, c, t);
  15312. if (lowestRoot.found) {
  15313. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15314. if (f >= 0.0 && f <= 1.0) {
  15315. t = lowestRoot.root;
  15316. found = true;
  15317. this._edge.scaleInPlace(f);
  15318. p1.addToRef(this._edge, this._collisionPoint);
  15319. }
  15320. }
  15321. p3.subtractToRef(p2, this._edge);
  15322. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15323. edgeSquaredLength = this._edge.lengthSquared();
  15324. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15325. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15326. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15327. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15328. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15329. lowestRoot = getLowestRoot(a, b, c, t);
  15330. if (lowestRoot.found) {
  15331. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15332. if (f >= 0.0 && f <= 1.0) {
  15333. t = lowestRoot.root;
  15334. found = true;
  15335. this._edge.scaleInPlace(f);
  15336. p2.addToRef(this._edge, this._collisionPoint);
  15337. }
  15338. }
  15339. p1.subtractToRef(p3, this._edge);
  15340. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15341. edgeSquaredLength = this._edge.lengthSquared();
  15342. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15343. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15344. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15345. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15346. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15347. lowestRoot = getLowestRoot(a, b, c, t);
  15348. if (lowestRoot.found) {
  15349. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15350. if (f >= 0.0 && f <= 1.0) {
  15351. t = lowestRoot.root;
  15352. found = true;
  15353. this._edge.scaleInPlace(f);
  15354. p3.addToRef(this._edge, this._collisionPoint);
  15355. }
  15356. }
  15357. }
  15358. if (found) {
  15359. var distToCollision = t * this.velocity.length();
  15360. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15361. if (!this.intersectionPoint) {
  15362. this.intersectionPoint = this._collisionPoint.clone();
  15363. }
  15364. else {
  15365. this.intersectionPoint.copyFrom(this._collisionPoint);
  15366. }
  15367. this.nearestDistance = distToCollision;
  15368. this.collisionFound = true;
  15369. }
  15370. }
  15371. };
  15372. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15373. for (var i = indexStart; i < indexEnd; i += 3) {
  15374. var p1 = pts[indices[i] - decal];
  15375. var p2 = pts[indices[i + 1] - decal];
  15376. var p3 = pts[indices[i + 2] - decal];
  15377. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15378. }
  15379. };
  15380. Collider.prototype._getResponse = function (pos, vel) {
  15381. pos.addToRef(vel, this._destinationPoint);
  15382. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15383. this.basePoint.addToRef(vel, pos);
  15384. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15385. this._slidePlaneNormal.normalize();
  15386. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15387. pos.addInPlace(this._displacementVector);
  15388. this.intersectionPoint.addInPlace(this._displacementVector);
  15389. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15390. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15391. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15392. };
  15393. return Collider;
  15394. }());
  15395. BABYLON.Collider = Collider;
  15396. })(BABYLON || (BABYLON = {}));
  15397. //# sourceMappingURL=babylon.collider.js.map
  15398. var BABYLON;
  15399. (function (BABYLON) {
  15400. //WebWorker code will be inserted to this variable.
  15401. BABYLON.CollisionWorker = "";
  15402. var WorkerTaskType;
  15403. (function (WorkerTaskType) {
  15404. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15405. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15406. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15407. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15408. var WorkerReplyType;
  15409. (function (WorkerReplyType) {
  15410. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15411. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15412. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15413. var CollisionCoordinatorWorker = (function () {
  15414. function CollisionCoordinatorWorker() {
  15415. var _this = this;
  15416. this._scaledPosition = BABYLON.Vector3.Zero();
  15417. this._scaledVelocity = BABYLON.Vector3.Zero();
  15418. this.onMeshUpdated = function (mesh) {
  15419. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15420. };
  15421. this.onGeometryUpdated = function (geometry) {
  15422. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15423. };
  15424. this._afterRender = function () {
  15425. if (!_this._init)
  15426. return;
  15427. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15428. return;
  15429. }
  15430. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15431. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15432. if (_this._runningUpdated > 4) {
  15433. return;
  15434. }
  15435. ++_this._runningUpdated;
  15436. var payload = {
  15437. updatedMeshes: _this._addUpdateMeshesList,
  15438. updatedGeometries: _this._addUpdateGeometriesList,
  15439. removedGeometries: _this._toRemoveGeometryArray,
  15440. removedMeshes: _this._toRemoveMeshesArray
  15441. };
  15442. var message = {
  15443. payload: payload,
  15444. taskType: WorkerTaskType.UPDATE
  15445. };
  15446. var serializable = [];
  15447. for (var id in payload.updatedGeometries) {
  15448. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15449. //prepare transferables
  15450. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15451. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15452. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15453. }
  15454. }
  15455. _this._worker.postMessage(message, serializable);
  15456. _this._addUpdateMeshesList = {};
  15457. _this._addUpdateGeometriesList = {};
  15458. _this._toRemoveGeometryArray = [];
  15459. _this._toRemoveMeshesArray = [];
  15460. };
  15461. this._onMessageFromWorker = function (e) {
  15462. var returnData = e.data;
  15463. if (returnData.error != WorkerReplyType.SUCCESS) {
  15464. //TODO what errors can be returned from the worker?
  15465. BABYLON.Tools.Warn("error returned from worker!");
  15466. return;
  15467. }
  15468. switch (returnData.taskType) {
  15469. case WorkerTaskType.INIT:
  15470. _this._init = true;
  15471. //Update the worked with ALL of the scene's current state
  15472. _this._scene.meshes.forEach(function (mesh) {
  15473. _this.onMeshAdded(mesh);
  15474. });
  15475. _this._scene.getGeometries().forEach(function (geometry) {
  15476. _this.onGeometryAdded(geometry);
  15477. });
  15478. break;
  15479. case WorkerTaskType.UPDATE:
  15480. _this._runningUpdated--;
  15481. break;
  15482. case WorkerTaskType.COLLIDE:
  15483. _this._runningCollisionTask = false;
  15484. var returnPayload = returnData.payload;
  15485. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15486. return;
  15487. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15488. //cleanup
  15489. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15490. break;
  15491. }
  15492. };
  15493. this._collisionsCallbackArray = [];
  15494. this._init = false;
  15495. this._runningUpdated = 0;
  15496. this._runningCollisionTask = false;
  15497. this._addUpdateMeshesList = {};
  15498. this._addUpdateGeometriesList = {};
  15499. this._toRemoveGeometryArray = [];
  15500. this._toRemoveMeshesArray = [];
  15501. }
  15502. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15503. if (!this._init)
  15504. return;
  15505. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15506. return;
  15507. position.divideToRef(collider.radius, this._scaledPosition);
  15508. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15509. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15510. var payload = {
  15511. collider: {
  15512. position: this._scaledPosition.asArray(),
  15513. velocity: this._scaledVelocity.asArray(),
  15514. radius: collider.radius.asArray()
  15515. },
  15516. collisionId: collisionIndex,
  15517. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15518. maximumRetry: maximumRetry
  15519. };
  15520. var message = {
  15521. payload: payload,
  15522. taskType: WorkerTaskType.COLLIDE
  15523. };
  15524. this._worker.postMessage(message);
  15525. };
  15526. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15527. this._scene = scene;
  15528. this._scene.registerAfterRender(this._afterRender);
  15529. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15530. this._worker = new Worker(workerUrl);
  15531. this._worker.onmessage = this._onMessageFromWorker;
  15532. var message = {
  15533. payload: {},
  15534. taskType: WorkerTaskType.INIT
  15535. };
  15536. this._worker.postMessage(message);
  15537. };
  15538. CollisionCoordinatorWorker.prototype.destroy = function () {
  15539. this._scene.unregisterAfterRender(this._afterRender);
  15540. this._worker.terminate();
  15541. };
  15542. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15543. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15544. this.onMeshUpdated(mesh);
  15545. };
  15546. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15547. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15548. };
  15549. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15550. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15551. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15552. this.onGeometryUpdated(geometry);
  15553. };
  15554. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15555. this._toRemoveGeometryArray.push(geometry.id);
  15556. };
  15557. return CollisionCoordinatorWorker;
  15558. }());
  15559. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15560. var submeshes = [];
  15561. if (mesh.subMeshes) {
  15562. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15563. return {
  15564. position: idx,
  15565. verticesStart: sm.verticesStart,
  15566. verticesCount: sm.verticesCount,
  15567. indexStart: sm.indexStart,
  15568. indexCount: sm.indexCount,
  15569. hasMaterial: !!sm.getMaterial(),
  15570. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15571. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15572. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15573. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15574. };
  15575. });
  15576. }
  15577. var geometryId = null;
  15578. if (mesh instanceof BABYLON.Mesh) {
  15579. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15580. }
  15581. else if (mesh instanceof BABYLON.InstancedMesh) {
  15582. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15583. }
  15584. return {
  15585. uniqueId: mesh.uniqueId,
  15586. id: mesh.id,
  15587. name: mesh.name,
  15588. geometryId: geometryId,
  15589. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15590. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15591. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15592. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15593. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15594. subMeshes: submeshes,
  15595. checkCollisions: mesh.checkCollisions
  15596. };
  15597. };
  15598. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15599. return {
  15600. id: geometry.id,
  15601. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15602. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15603. indices: new Uint32Array(geometry.getIndices() || []),
  15604. };
  15605. };
  15606. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15607. var CollisionCoordinatorLegacy = (function () {
  15608. function CollisionCoordinatorLegacy() {
  15609. this._scaledPosition = BABYLON.Vector3.Zero();
  15610. this._scaledVelocity = BABYLON.Vector3.Zero();
  15611. this._finalPosition = BABYLON.Vector3.Zero();
  15612. }
  15613. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15614. position.divideToRef(collider.radius, this._scaledPosition);
  15615. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15616. collider.collidedMesh = null;
  15617. collider.retry = 0;
  15618. collider.initialVelocity = this._scaledVelocity;
  15619. collider.initialPosition = this._scaledPosition;
  15620. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15621. this._finalPosition.multiplyInPlace(collider.radius);
  15622. //run the callback
  15623. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15624. };
  15625. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15626. this._scene = scene;
  15627. };
  15628. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15629. //Legacy need no destruction method.
  15630. };
  15631. //No update in legacy mode
  15632. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15633. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15634. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15635. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15636. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15637. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15638. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15639. if (excludedMesh === void 0) { excludedMesh = null; }
  15640. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15641. if (collider.retry >= maximumRetry) {
  15642. finalPosition.copyFrom(position);
  15643. return;
  15644. }
  15645. // Check if this is a mesh else camera or -1
  15646. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15647. collider._initialize(position, velocity, closeDistance);
  15648. // Check all meshes
  15649. for (var index = 0; index < this._scene.meshes.length; index++) {
  15650. var mesh = this._scene.meshes[index];
  15651. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15652. mesh._checkCollision(collider);
  15653. }
  15654. }
  15655. if (!collider.collisionFound) {
  15656. position.addToRef(velocity, finalPosition);
  15657. return;
  15658. }
  15659. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15660. collider._getResponse(position, velocity);
  15661. }
  15662. if (velocity.length() <= closeDistance) {
  15663. finalPosition.copyFrom(position);
  15664. return;
  15665. }
  15666. collider.retry++;
  15667. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15668. };
  15669. return CollisionCoordinatorLegacy;
  15670. }());
  15671. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15672. })(BABYLON || (BABYLON = {}));
  15673. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15674. var BABYLON;
  15675. (function (BABYLON) {
  15676. var Camera = (function (_super) {
  15677. __extends(Camera, _super);
  15678. function Camera(name, position, scene) {
  15679. var _this = _super.call(this, name, scene) || this;
  15680. _this.upVector = BABYLON.Vector3.Up();
  15681. _this.orthoLeft = null;
  15682. _this.orthoRight = null;
  15683. _this.orthoBottom = null;
  15684. _this.orthoTop = null;
  15685. _this.fov = 0.8;
  15686. _this.minZ = 1.0;
  15687. _this.maxZ = 10000.0;
  15688. _this.inertia = 0.9;
  15689. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15690. _this.isIntermediate = false;
  15691. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15692. _this.layerMask = 0x0FFFFFFF;
  15693. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15694. // Camera rig members
  15695. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15696. _this._rigCameras = new Array();
  15697. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15698. // Cache
  15699. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15700. _this._projectionMatrix = new BABYLON.Matrix();
  15701. _this._doNotComputeProjectionMatrix = false;
  15702. _this._postProcesses = new Array();
  15703. _this._transformMatrix = BABYLON.Matrix.Zero();
  15704. _this._activeMeshes = new BABYLON.SmartArray(256);
  15705. _this._globalPosition = BABYLON.Vector3.Zero();
  15706. _this._refreshFrustumPlanes = true;
  15707. _this.getScene().addCamera(_this);
  15708. if (!_this.getScene().activeCamera) {
  15709. _this.getScene().activeCamera = _this;
  15710. }
  15711. _this.position = position;
  15712. return _this;
  15713. }
  15714. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15715. get: function () {
  15716. return Camera._PERSPECTIVE_CAMERA;
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15722. get: function () {
  15723. return Camera._ORTHOGRAPHIC_CAMERA;
  15724. },
  15725. enumerable: true,
  15726. configurable: true
  15727. });
  15728. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15729. get: function () {
  15730. return Camera._FOVMODE_VERTICAL_FIXED;
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15736. get: function () {
  15737. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15738. },
  15739. enumerable: true,
  15740. configurable: true
  15741. });
  15742. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15743. get: function () {
  15744. return Camera._RIG_MODE_NONE;
  15745. },
  15746. enumerable: true,
  15747. configurable: true
  15748. });
  15749. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15750. get: function () {
  15751. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15752. },
  15753. enumerable: true,
  15754. configurable: true
  15755. });
  15756. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15757. get: function () {
  15758. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15759. },
  15760. enumerable: true,
  15761. configurable: true
  15762. });
  15763. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15764. get: function () {
  15765. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15766. },
  15767. enumerable: true,
  15768. configurable: true
  15769. });
  15770. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15771. get: function () {
  15772. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15773. },
  15774. enumerable: true,
  15775. configurable: true
  15776. });
  15777. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15778. get: function () {
  15779. return Camera._RIG_MODE_VR;
  15780. },
  15781. enumerable: true,
  15782. configurable: true
  15783. });
  15784. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15785. get: function () {
  15786. return Camera._RIG_MODE_WEBVR;
  15787. },
  15788. enumerable: true,
  15789. configurable: true
  15790. });
  15791. Camera.prototype.getClassName = function () {
  15792. return "Camera";
  15793. };
  15794. /**
  15795. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15796. */
  15797. Camera.prototype.toString = function (fullDetails) {
  15798. var ret = "Name: " + this.name;
  15799. ret += ", type: " + this.getClassName();
  15800. if (this.animations) {
  15801. for (var i = 0; i < this.animations.length; i++) {
  15802. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15803. }
  15804. }
  15805. if (fullDetails) {
  15806. }
  15807. return ret;
  15808. };
  15809. Object.defineProperty(Camera.prototype, "globalPosition", {
  15810. get: function () {
  15811. return this._globalPosition;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Camera.prototype.getActiveMeshes = function () {
  15817. return this._activeMeshes;
  15818. };
  15819. Camera.prototype.isActiveMesh = function (mesh) {
  15820. return (this._activeMeshes.indexOf(mesh) !== -1);
  15821. };
  15822. //Cache
  15823. Camera.prototype._initCache = function () {
  15824. _super.prototype._initCache.call(this);
  15825. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15826. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15827. this._cache.mode = undefined;
  15828. this._cache.minZ = undefined;
  15829. this._cache.maxZ = undefined;
  15830. this._cache.fov = undefined;
  15831. this._cache.fovMode = undefined;
  15832. this._cache.aspectRatio = undefined;
  15833. this._cache.orthoLeft = undefined;
  15834. this._cache.orthoRight = undefined;
  15835. this._cache.orthoBottom = undefined;
  15836. this._cache.orthoTop = undefined;
  15837. this._cache.renderWidth = undefined;
  15838. this._cache.renderHeight = undefined;
  15839. };
  15840. Camera.prototype._updateCache = function (ignoreParentClass) {
  15841. if (!ignoreParentClass) {
  15842. _super.prototype._updateCache.call(this);
  15843. }
  15844. var engine = this.getEngine();
  15845. this._cache.position.copyFrom(this.position);
  15846. this._cache.upVector.copyFrom(this.upVector);
  15847. this._cache.mode = this.mode;
  15848. this._cache.minZ = this.minZ;
  15849. this._cache.maxZ = this.maxZ;
  15850. this._cache.fov = this.fov;
  15851. this._cache.fovMode = this.fovMode;
  15852. this._cache.aspectRatio = engine.getAspectRatio(this);
  15853. this._cache.orthoLeft = this.orthoLeft;
  15854. this._cache.orthoRight = this.orthoRight;
  15855. this._cache.orthoBottom = this.orthoBottom;
  15856. this._cache.orthoTop = this.orthoTop;
  15857. this._cache.renderWidth = engine.getRenderWidth();
  15858. this._cache.renderHeight = engine.getRenderHeight();
  15859. };
  15860. Camera.prototype._updateFromScene = function () {
  15861. this.updateCache();
  15862. this.update();
  15863. };
  15864. // Synchronized
  15865. Camera.prototype._isSynchronized = function () {
  15866. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15867. };
  15868. Camera.prototype._isSynchronizedViewMatrix = function () {
  15869. if (!_super.prototype._isSynchronized.call(this))
  15870. return false;
  15871. return this._cache.position.equals(this.position)
  15872. && this._cache.upVector.equals(this.upVector)
  15873. && this.isSynchronizedWithParent();
  15874. };
  15875. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15876. var check = this._cache.mode === this.mode
  15877. && this._cache.minZ === this.minZ
  15878. && this._cache.maxZ === this.maxZ;
  15879. if (!check) {
  15880. return false;
  15881. }
  15882. var engine = this.getEngine();
  15883. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15884. check = this._cache.fov === this.fov
  15885. && this._cache.fovMode === this.fovMode
  15886. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15887. }
  15888. else {
  15889. check = this._cache.orthoLeft === this.orthoLeft
  15890. && this._cache.orthoRight === this.orthoRight
  15891. && this._cache.orthoBottom === this.orthoBottom
  15892. && this._cache.orthoTop === this.orthoTop
  15893. && this._cache.renderWidth === engine.getRenderWidth()
  15894. && this._cache.renderHeight === engine.getRenderHeight();
  15895. }
  15896. return check;
  15897. };
  15898. // Controls
  15899. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15900. };
  15901. Camera.prototype.detachControl = function (element) {
  15902. };
  15903. Camera.prototype.update = function () {
  15904. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15905. this._updateRigCameras();
  15906. }
  15907. this._checkInputs();
  15908. };
  15909. Camera.prototype._checkInputs = function () {
  15910. };
  15911. Object.defineProperty(Camera.prototype, "rigCameras", {
  15912. get: function () {
  15913. return this._rigCameras;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15919. get: function () {
  15920. return this._rigPostProcess;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15926. // invalidate framebuffer
  15927. if (this._postProcesses.length > 0) {
  15928. this._postProcesses[0].markTextureDirty();
  15929. }
  15930. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15931. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15932. var cam = this._rigCameras[i];
  15933. var rigPostProcess = cam._rigPostProcess;
  15934. // for VR rig, there does not have to be a post process
  15935. if (rigPostProcess) {
  15936. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15937. if (isPass) {
  15938. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15939. cam.isIntermediate = this._postProcesses.length === 0;
  15940. }
  15941. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15942. rigPostProcess.markTextureDirty();
  15943. }
  15944. else {
  15945. cam._postProcesses = this._postProcesses.slice(0);
  15946. }
  15947. }
  15948. };
  15949. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15950. if (insertAt === void 0) { insertAt = null; }
  15951. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15952. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15953. return 0;
  15954. }
  15955. if (insertAt == null || insertAt < 0) {
  15956. this._postProcesses.push(postProcess);
  15957. }
  15958. else {
  15959. this._postProcesses.splice(insertAt, 0, postProcess);
  15960. }
  15961. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15962. return this._postProcesses.indexOf(postProcess);
  15963. };
  15964. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15965. if (atIndices === void 0) { atIndices = null; }
  15966. var result = [];
  15967. var i;
  15968. var index;
  15969. if (!atIndices) {
  15970. var idx = this._postProcesses.indexOf(postProcess);
  15971. if (idx !== -1) {
  15972. this._postProcesses.splice(idx, 1);
  15973. }
  15974. }
  15975. else {
  15976. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15977. // iterate descending, so can just splice as we go
  15978. for (i = atIndices.length - 1; i >= 0; i--) {
  15979. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15980. result.push(i);
  15981. continue;
  15982. }
  15983. index = atIndices[i];
  15984. this._postProcesses.splice(index, 1);
  15985. }
  15986. }
  15987. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15988. return result;
  15989. };
  15990. Camera.prototype.getWorldMatrix = function () {
  15991. if (!this._worldMatrix) {
  15992. this._worldMatrix = BABYLON.Matrix.Identity();
  15993. }
  15994. var viewMatrix = this.getViewMatrix();
  15995. viewMatrix.invertToRef(this._worldMatrix);
  15996. return this._worldMatrix;
  15997. };
  15998. Camera.prototype._getViewMatrix = function () {
  15999. return BABYLON.Matrix.Identity();
  16000. };
  16001. Camera.prototype.getViewMatrix = function (force) {
  16002. this._computedViewMatrix = this._computeViewMatrix(force);
  16003. if (!force && this._isSynchronizedViewMatrix()) {
  16004. return this._computedViewMatrix;
  16005. }
  16006. this._refreshFrustumPlanes = true;
  16007. if (!this.parent || !this.parent.getWorldMatrix) {
  16008. this._globalPosition.copyFrom(this.position);
  16009. }
  16010. else {
  16011. if (!this._worldMatrix) {
  16012. this._worldMatrix = BABYLON.Matrix.Identity();
  16013. }
  16014. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16015. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16016. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16017. this._computedViewMatrix.invert();
  16018. this._markSyncedWithParent();
  16019. }
  16020. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16021. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16022. }
  16023. this._currentRenderId = this.getScene().getRenderId();
  16024. return this._computedViewMatrix;
  16025. };
  16026. Camera.prototype._computeViewMatrix = function (force) {
  16027. if (!force && this._isSynchronizedViewMatrix()) {
  16028. return this._computedViewMatrix;
  16029. }
  16030. this._computedViewMatrix = this._getViewMatrix();
  16031. this._currentRenderId = this.getScene().getRenderId();
  16032. return this._computedViewMatrix;
  16033. };
  16034. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16035. this._doNotComputeProjectionMatrix = true;
  16036. if (projection !== undefined) {
  16037. this._projectionMatrix = projection;
  16038. }
  16039. };
  16040. ;
  16041. Camera.prototype.unfreezeProjectionMatrix = function () {
  16042. this._doNotComputeProjectionMatrix = false;
  16043. };
  16044. ;
  16045. Camera.prototype.getProjectionMatrix = function (force) {
  16046. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16047. return this._projectionMatrix;
  16048. }
  16049. this._refreshFrustumPlanes = true;
  16050. var engine = this.getEngine();
  16051. var scene = this.getScene();
  16052. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16053. if (this.minZ <= 0) {
  16054. this.minZ = 0.1;
  16055. }
  16056. if (scene.useRightHandedSystem) {
  16057. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16058. }
  16059. else {
  16060. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16061. }
  16062. return this._projectionMatrix;
  16063. }
  16064. var halfWidth = engine.getRenderWidth() / 2.0;
  16065. var halfHeight = engine.getRenderHeight() / 2.0;
  16066. if (scene.useRightHandedSystem) {
  16067. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16068. }
  16069. else {
  16070. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16071. }
  16072. return this._projectionMatrix;
  16073. };
  16074. Camera.prototype.getTranformationMatrix = function () {
  16075. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16076. return this._transformMatrix;
  16077. };
  16078. Camera.prototype.updateFrustumPlanes = function () {
  16079. if (!this._refreshFrustumPlanes) {
  16080. return;
  16081. }
  16082. this.getTranformationMatrix();
  16083. if (!this._frustumPlanes) {
  16084. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16085. }
  16086. else {
  16087. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16088. }
  16089. this._refreshFrustumPlanes = false;
  16090. };
  16091. Camera.prototype.isInFrustum = function (target) {
  16092. this.updateFrustumPlanes();
  16093. return target.isInFrustum(this._frustumPlanes);
  16094. };
  16095. Camera.prototype.isCompletelyInFrustum = function (target) {
  16096. this.updateFrustumPlanes();
  16097. return target.isCompletelyInFrustum(this._frustumPlanes);
  16098. };
  16099. Camera.prototype.dispose = function () {
  16100. // Animations
  16101. this.getScene().stopAnimation(this);
  16102. // Remove from scene
  16103. this.getScene().removeCamera(this);
  16104. while (this._rigCameras.length > 0) {
  16105. this._rigCameras.pop().dispose();
  16106. }
  16107. // Postprocesses
  16108. var i = this._postProcesses.length;
  16109. while (--i >= 0) {
  16110. this._postProcesses[i].dispose(this);
  16111. }
  16112. _super.prototype.dispose.call(this);
  16113. };
  16114. // ---- Camera rigs section ----
  16115. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16116. while (this._rigCameras.length > 0) {
  16117. this._rigCameras.pop().dispose();
  16118. }
  16119. this.cameraRigMode = mode;
  16120. this._cameraRigParams = {};
  16121. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16122. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16123. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16124. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16125. // create the rig cameras, unless none
  16126. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16127. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16128. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16129. }
  16130. switch (this.cameraRigMode) {
  16131. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16132. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16133. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16134. break;
  16135. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16136. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16137. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16138. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16139. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16140. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16141. break;
  16142. case Camera.RIG_MODE_VR:
  16143. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16144. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16145. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16146. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16147. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16148. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16149. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16150. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16151. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16152. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16153. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16154. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16155. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16156. if (metrics.compensateDistortion) {
  16157. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16158. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16159. }
  16160. break;
  16161. case Camera.RIG_MODE_WEBVR:
  16162. if (rigParams.vrDisplay) {
  16163. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16164. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16165. //Left eye
  16166. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16167. this._rigCameras[0].setCameraRigParameter("left", true);
  16168. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16169. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16170. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16171. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16172. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16173. this._rigCameras[0].parent = this;
  16174. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16175. //Right eye
  16176. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16177. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16178. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16179. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16180. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16181. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16182. this._rigCameras[1].parent = this;
  16183. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16184. }
  16185. break;
  16186. }
  16187. this._cascadePostProcessesToRigCams();
  16188. this.
  16189. update();
  16190. };
  16191. Camera.prototype._getVRProjectionMatrix = function () {
  16192. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16193. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16194. return this._projectionMatrix;
  16195. };
  16196. Camera.prototype._updateCameraRotationMatrix = function () {
  16197. //Here for WebVR
  16198. };
  16199. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16200. //Here for WebVR
  16201. };
  16202. /**
  16203. * This function MUST be overwritten by the different WebVR cameras available.
  16204. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16205. */
  16206. Camera.prototype._getWebVRProjectionMatrix = function () {
  16207. return BABYLON.Matrix.Identity();
  16208. };
  16209. /**
  16210. * This function MUST be overwritten by the different WebVR cameras available.
  16211. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16212. */
  16213. Camera.prototype._getWebVRViewMatrix = function () {
  16214. return BABYLON.Matrix.Identity();
  16215. };
  16216. Camera.prototype.setCameraRigParameter = function (name, value) {
  16217. if (!this._cameraRigParams) {
  16218. this._cameraRigParams = {};
  16219. }
  16220. this._cameraRigParams[name] = value;
  16221. //provisionnally:
  16222. if (name === "interaxialDistance") {
  16223. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16224. }
  16225. };
  16226. /**
  16227. * needs to be overridden by children so sub has required properties to be copied
  16228. */
  16229. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16230. return null;
  16231. };
  16232. /**
  16233. * May need to be overridden by children
  16234. */
  16235. Camera.prototype._updateRigCameras = function () {
  16236. for (var i = 0; i < this._rigCameras.length; i++) {
  16237. this._rigCameras[i].minZ = this.minZ;
  16238. this._rigCameras[i].maxZ = this.maxZ;
  16239. this._rigCameras[i].fov = this.fov;
  16240. }
  16241. // only update viewport when ANAGLYPH
  16242. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16243. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16244. }
  16245. };
  16246. Camera.prototype._setupInputs = function () {
  16247. };
  16248. Camera.prototype.serialize = function () {
  16249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16250. // Type
  16251. serializationObject.type = this.getClassName();
  16252. // Parent
  16253. if (this.parent) {
  16254. serializationObject.parentId = this.parent.id;
  16255. }
  16256. if (this.inputs) {
  16257. this.inputs.serialize(serializationObject);
  16258. }
  16259. // Animations
  16260. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16261. serializationObject.ranges = this.serializeAnimationRanges();
  16262. return serializationObject;
  16263. };
  16264. Camera.prototype.clone = function (name) {
  16265. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16266. };
  16267. Camera.prototype.getDirection = function (localAxis) {
  16268. var result = BABYLON.Vector3.Zero();
  16269. this.getDirectionToRef(localAxis, result);
  16270. return result;
  16271. };
  16272. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16273. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16274. };
  16275. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16276. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16277. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16278. switch (type) {
  16279. case "ArcRotateCamera":
  16280. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16281. case "DeviceOrientationCamera":
  16282. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16283. case "FollowCamera":
  16284. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16285. case "ArcFollowCamera":
  16286. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16287. case "GamepadCamera":
  16288. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16289. case "TouchCamera":
  16290. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16291. case "VirtualJoysticksCamera":
  16292. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16293. case "WebVRFreeCamera":
  16294. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16295. case "WebVRGamepadCamera":
  16296. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16297. case "VRDeviceOrientationFreeCamera":
  16298. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16299. case "VRDeviceOrientationGamepadCamera":
  16300. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16301. case "AnaglyphArcRotateCamera":
  16302. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16303. case "AnaglyphFreeCamera":
  16304. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16305. case "AnaglyphGamepadCamera":
  16306. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16307. case "AnaglyphUniversalCamera":
  16308. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16309. case "StereoscopicArcRotateCamera":
  16310. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16311. case "StereoscopicFreeCamera":
  16312. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16313. case "StereoscopicGamepadCamera":
  16314. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16315. case "StereoscopicUniversalCamera":
  16316. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16317. case "FreeCamera":
  16318. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16319. default:
  16320. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16321. }
  16322. };
  16323. Camera.Parse = function (parsedCamera, scene) {
  16324. var type = parsedCamera.type;
  16325. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16326. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16327. // Parent
  16328. if (parsedCamera.parentId) {
  16329. camera._waitingParentId = parsedCamera.parentId;
  16330. }
  16331. //If camera has an input manager, let it parse inputs settings
  16332. if (camera.inputs) {
  16333. camera.inputs.parse(parsedCamera);
  16334. camera._setupInputs();
  16335. }
  16336. // Target
  16337. if (parsedCamera.target) {
  16338. if (camera.setTarget) {
  16339. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16340. }
  16341. }
  16342. // Apply 3d rig, when found
  16343. if (parsedCamera.cameraRigMode) {
  16344. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16345. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16346. }
  16347. // Animations
  16348. if (parsedCamera.animations) {
  16349. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16350. var parsedAnimation = parsedCamera.animations[animationIndex];
  16351. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16352. }
  16353. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16354. }
  16355. if (parsedCamera.autoAnimate) {
  16356. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16357. }
  16358. return camera;
  16359. };
  16360. return Camera;
  16361. }(BABYLON.Node));
  16362. // Statics
  16363. Camera._PERSPECTIVE_CAMERA = 0;
  16364. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16365. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16366. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16367. Camera._RIG_MODE_NONE = 0;
  16368. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16369. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16370. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16371. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16372. Camera._RIG_MODE_VR = 20;
  16373. Camera._RIG_MODE_WEBVR = 21;
  16374. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16375. __decorate([
  16376. BABYLON.serializeAsVector3()
  16377. ], Camera.prototype, "position", void 0);
  16378. __decorate([
  16379. BABYLON.serializeAsVector3()
  16380. ], Camera.prototype, "upVector", void 0);
  16381. __decorate([
  16382. BABYLON.serialize()
  16383. ], Camera.prototype, "orthoLeft", void 0);
  16384. __decorate([
  16385. BABYLON.serialize()
  16386. ], Camera.prototype, "orthoRight", void 0);
  16387. __decorate([
  16388. BABYLON.serialize()
  16389. ], Camera.prototype, "orthoBottom", void 0);
  16390. __decorate([
  16391. BABYLON.serialize()
  16392. ], Camera.prototype, "orthoTop", void 0);
  16393. __decorate([
  16394. BABYLON.serialize()
  16395. ], Camera.prototype, "fov", void 0);
  16396. __decorate([
  16397. BABYLON.serialize()
  16398. ], Camera.prototype, "minZ", void 0);
  16399. __decorate([
  16400. BABYLON.serialize()
  16401. ], Camera.prototype, "maxZ", void 0);
  16402. __decorate([
  16403. BABYLON.serialize()
  16404. ], Camera.prototype, "inertia", void 0);
  16405. __decorate([
  16406. BABYLON.serialize()
  16407. ], Camera.prototype, "mode", void 0);
  16408. __decorate([
  16409. BABYLON.serialize()
  16410. ], Camera.prototype, "layerMask", void 0);
  16411. __decorate([
  16412. BABYLON.serialize()
  16413. ], Camera.prototype, "fovMode", void 0);
  16414. __decorate([
  16415. BABYLON.serialize()
  16416. ], Camera.prototype, "cameraRigMode", void 0);
  16417. __decorate([
  16418. BABYLON.serialize()
  16419. ], Camera.prototype, "interaxialDistance", void 0);
  16420. __decorate([
  16421. BABYLON.serialize()
  16422. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16423. BABYLON.Camera = Camera;
  16424. })(BABYLON || (BABYLON = {}));
  16425. //# sourceMappingURL=babylon.camera.js.map
  16426. var BABYLON;
  16427. (function (BABYLON) {
  16428. BABYLON.CameraInputTypes = {};
  16429. var CameraInputsManager = (function () {
  16430. function CameraInputsManager(camera) {
  16431. this.attached = {};
  16432. this.camera = camera;
  16433. this.checkInputs = function () { };
  16434. }
  16435. CameraInputsManager.prototype.add = function (input) {
  16436. var type = input.getSimpleName();
  16437. if (this.attached[type]) {
  16438. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16439. return;
  16440. }
  16441. this.attached[type] = input;
  16442. input.camera = this.camera;
  16443. //for checkInputs, we are dynamically creating a function
  16444. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16445. if (input.checkInputs) {
  16446. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16447. }
  16448. if (this.attachedElement) {
  16449. input.attachControl(this.attachedElement);
  16450. }
  16451. };
  16452. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16453. for (var cam in this.attached) {
  16454. var input = this.attached[cam];
  16455. if (input === inputToRemove) {
  16456. input.detachControl(this.attachedElement);
  16457. delete this.attached[cam];
  16458. this.rebuildInputCheck();
  16459. }
  16460. }
  16461. };
  16462. CameraInputsManager.prototype.removeByType = function (inputType) {
  16463. for (var cam in this.attached) {
  16464. var input = this.attached[cam];
  16465. if (input.getTypeName() === inputType) {
  16466. input.detachControl(this.attachedElement);
  16467. delete this.attached[cam];
  16468. this.rebuildInputCheck();
  16469. }
  16470. }
  16471. };
  16472. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16473. var current = this.checkInputs;
  16474. return function () {
  16475. current();
  16476. fn();
  16477. };
  16478. };
  16479. CameraInputsManager.prototype.attachInput = function (input) {
  16480. input.attachControl(this.attachedElement, this.noPreventDefault);
  16481. };
  16482. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16483. if (this.attachedElement) {
  16484. return;
  16485. }
  16486. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16487. this.attachedElement = element;
  16488. this.noPreventDefault = noPreventDefault;
  16489. for (var cam in this.attached) {
  16490. var input = this.attached[cam];
  16491. this.attached[cam].attachControl(element, noPreventDefault);
  16492. }
  16493. };
  16494. CameraInputsManager.prototype.detachElement = function (element) {
  16495. if (this.attachedElement !== element) {
  16496. return;
  16497. }
  16498. for (var cam in this.attached) {
  16499. var input = this.attached[cam];
  16500. this.attached[cam].detachControl(element);
  16501. }
  16502. this.attachedElement = null;
  16503. };
  16504. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16505. this.checkInputs = function () { };
  16506. for (var cam in this.attached) {
  16507. var input = this.attached[cam];
  16508. if (input.checkInputs) {
  16509. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16510. }
  16511. }
  16512. };
  16513. CameraInputsManager.prototype.clear = function () {
  16514. if (this.attachedElement) {
  16515. this.detachElement(this.attachedElement);
  16516. }
  16517. this.attached = {};
  16518. this.attachedElement = null;
  16519. this.checkInputs = function () { };
  16520. };
  16521. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16522. var inputs = {};
  16523. for (var cam in this.attached) {
  16524. var input = this.attached[cam];
  16525. var res = BABYLON.SerializationHelper.Serialize(input);
  16526. inputs[input.getTypeName()] = res;
  16527. }
  16528. serializedCamera.inputsmgr = inputs;
  16529. };
  16530. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16531. var parsedInputs = parsedCamera.inputsmgr;
  16532. if (parsedInputs) {
  16533. this.clear();
  16534. for (var n in parsedInputs) {
  16535. var construct = BABYLON.CameraInputTypes[n];
  16536. if (construct) {
  16537. var parsedinput = parsedInputs[n];
  16538. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16539. this.add(input);
  16540. }
  16541. }
  16542. }
  16543. else {
  16544. //2016-03-08 this part is for managing backward compatibility
  16545. for (var n in this.attached) {
  16546. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16547. if (construct) {
  16548. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16549. this.remove(this.attached[n]);
  16550. this.add(input);
  16551. }
  16552. }
  16553. }
  16554. };
  16555. return CameraInputsManager;
  16556. }());
  16557. BABYLON.CameraInputsManager = CameraInputsManager;
  16558. })(BABYLON || (BABYLON = {}));
  16559. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16560. var BABYLON;
  16561. (function (BABYLON) {
  16562. var FreeCameraMouseInput = (function () {
  16563. function FreeCameraMouseInput(touchEnabled) {
  16564. if (touchEnabled === void 0) { touchEnabled = true; }
  16565. this.touchEnabled = touchEnabled;
  16566. this.buttons = [0, 1, 2];
  16567. this.angularSensibility = 2000.0;
  16568. }
  16569. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16570. var _this = this;
  16571. var engine = this.camera.getEngine();
  16572. if (!this._pointerInput) {
  16573. this._pointerInput = function (p, s) {
  16574. var evt = p.event;
  16575. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16576. return;
  16577. }
  16578. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16579. return;
  16580. }
  16581. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16582. try {
  16583. evt.srcElement.setPointerCapture(evt.pointerId);
  16584. }
  16585. catch (e) {
  16586. }
  16587. _this.previousPosition = {
  16588. x: evt.clientX,
  16589. y: evt.clientY
  16590. };
  16591. if (!noPreventDefault) {
  16592. evt.preventDefault();
  16593. element.focus();
  16594. }
  16595. }
  16596. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16597. try {
  16598. evt.srcElement.releasePointerCapture(evt.pointerId);
  16599. }
  16600. catch (e) {
  16601. }
  16602. _this.previousPosition = null;
  16603. if (!noPreventDefault) {
  16604. evt.preventDefault();
  16605. }
  16606. }
  16607. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16608. if (!_this.previousPosition || engine.isPointerLock) {
  16609. return;
  16610. }
  16611. var offsetX = evt.clientX - _this.previousPosition.x;
  16612. var offsetY = evt.clientY - _this.previousPosition.y;
  16613. if (_this.camera.getScene().useRightHandedSystem) {
  16614. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16615. }
  16616. else {
  16617. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16618. }
  16619. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16620. _this.previousPosition = {
  16621. x: evt.clientX,
  16622. y: evt.clientY
  16623. };
  16624. if (!noPreventDefault) {
  16625. evt.preventDefault();
  16626. }
  16627. }
  16628. };
  16629. }
  16630. this._onMouseMove = function (evt) {
  16631. if (!engine.isPointerLock) {
  16632. return;
  16633. }
  16634. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16635. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16636. if (_this.camera.getScene().useRightHandedSystem) {
  16637. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16638. }
  16639. else {
  16640. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16641. }
  16642. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16643. _this.previousPosition = null;
  16644. if (!noPreventDefault) {
  16645. evt.preventDefault();
  16646. }
  16647. };
  16648. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16649. element.addEventListener("mousemove", this._onMouseMove, false);
  16650. };
  16651. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16652. if (this._observer && element) {
  16653. this.camera.getScene().onPointerObservable.remove(this._observer);
  16654. element.removeEventListener("mousemove", this._onMouseMove);
  16655. this._observer = null;
  16656. this._onMouseMove = null;
  16657. this.previousPosition = null;
  16658. }
  16659. };
  16660. FreeCameraMouseInput.prototype.getTypeName = function () {
  16661. return "FreeCameraMouseInput";
  16662. };
  16663. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16664. return "mouse";
  16665. };
  16666. return FreeCameraMouseInput;
  16667. }());
  16668. __decorate([
  16669. BABYLON.serialize()
  16670. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16671. __decorate([
  16672. BABYLON.serialize()
  16673. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16674. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16675. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16676. })(BABYLON || (BABYLON = {}));
  16677. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16678. var BABYLON;
  16679. (function (BABYLON) {
  16680. var FreeCameraKeyboardMoveInput = (function () {
  16681. function FreeCameraKeyboardMoveInput() {
  16682. this._keys = [];
  16683. this.keysUp = [38];
  16684. this.keysDown = [40];
  16685. this.keysLeft = [37];
  16686. this.keysRight = [39];
  16687. }
  16688. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16689. var _this = this;
  16690. if (!this._onKeyDown) {
  16691. element.tabIndex = 1;
  16692. this._onKeyDown = function (evt) {
  16693. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16694. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16695. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16696. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16697. var index = _this._keys.indexOf(evt.keyCode);
  16698. if (index === -1) {
  16699. _this._keys.push(evt.keyCode);
  16700. }
  16701. if (!noPreventDefault) {
  16702. evt.preventDefault();
  16703. }
  16704. }
  16705. };
  16706. this._onKeyUp = function (evt) {
  16707. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16708. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16709. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16710. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16711. var index = _this._keys.indexOf(evt.keyCode);
  16712. if (index >= 0) {
  16713. _this._keys.splice(index, 1);
  16714. }
  16715. if (!noPreventDefault) {
  16716. evt.preventDefault();
  16717. }
  16718. }
  16719. };
  16720. element.addEventListener("keydown", this._onKeyDown, false);
  16721. element.addEventListener("keyup", this._onKeyUp, false);
  16722. BABYLON.Tools.RegisterTopRootEvents([
  16723. { name: "blur", handler: this._onLostFocus }
  16724. ]);
  16725. }
  16726. };
  16727. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16728. if (this._onKeyDown) {
  16729. element.removeEventListener("keydown", this._onKeyDown);
  16730. element.removeEventListener("keyup", this._onKeyUp);
  16731. BABYLON.Tools.UnregisterTopRootEvents([
  16732. { name: "blur", handler: this._onLostFocus }
  16733. ]);
  16734. this._keys = [];
  16735. this._onKeyDown = null;
  16736. this._onKeyUp = null;
  16737. }
  16738. };
  16739. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16740. if (this._onKeyDown) {
  16741. var camera = this.camera;
  16742. // Keyboard
  16743. for (var index = 0; index < this._keys.length; index++) {
  16744. var keyCode = this._keys[index];
  16745. var speed = camera._computeLocalCameraSpeed();
  16746. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16747. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16748. }
  16749. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16750. camera._localDirection.copyFromFloats(0, 0, speed);
  16751. }
  16752. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16753. camera._localDirection.copyFromFloats(speed, 0, 0);
  16754. }
  16755. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16756. camera._localDirection.copyFromFloats(0, 0, -speed);
  16757. }
  16758. if (camera.getScene().useRightHandedSystem) {
  16759. camera._localDirection.z *= -1;
  16760. }
  16761. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16762. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16763. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16764. }
  16765. }
  16766. };
  16767. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16768. return "FreeCameraKeyboardMoveInput";
  16769. };
  16770. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16771. this._keys = [];
  16772. };
  16773. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16774. return "keyboard";
  16775. };
  16776. return FreeCameraKeyboardMoveInput;
  16777. }());
  16778. __decorate([
  16779. BABYLON.serialize()
  16780. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16781. __decorate([
  16782. BABYLON.serialize()
  16783. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16784. __decorate([
  16785. BABYLON.serialize()
  16786. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16787. __decorate([
  16788. BABYLON.serialize()
  16789. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16790. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16791. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16792. })(BABYLON || (BABYLON = {}));
  16793. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16794. var BABYLON;
  16795. (function (BABYLON) {
  16796. var FreeCameraTouchInput = (function () {
  16797. function FreeCameraTouchInput() {
  16798. this._offsetX = null;
  16799. this._offsetY = null;
  16800. this._pointerCount = 0;
  16801. this._pointerPressed = [];
  16802. this.touchAngularSensibility = 200000.0;
  16803. this.touchMoveSensibility = 250.0;
  16804. }
  16805. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16806. var _this = this;
  16807. var previousPosition;
  16808. if (this._pointerInput === undefined) {
  16809. this._onLostFocus = function (evt) {
  16810. _this._offsetX = null;
  16811. _this._offsetY = null;
  16812. };
  16813. this._pointerInput = function (p, s) {
  16814. var evt = p.event;
  16815. if (evt.pointerType === "mouse") {
  16816. return;
  16817. }
  16818. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16819. if (!noPreventDefault) {
  16820. evt.preventDefault();
  16821. }
  16822. _this._pointerPressed.push(evt.pointerId);
  16823. if (_this._pointerPressed.length !== 1) {
  16824. return;
  16825. }
  16826. previousPosition = {
  16827. x: evt.clientX,
  16828. y: evt.clientY
  16829. };
  16830. }
  16831. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16832. if (!noPreventDefault) {
  16833. evt.preventDefault();
  16834. }
  16835. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16836. if (index === -1) {
  16837. return;
  16838. }
  16839. _this._pointerPressed.splice(index, 1);
  16840. if (index != 0) {
  16841. return;
  16842. }
  16843. previousPosition = null;
  16844. _this._offsetX = null;
  16845. _this._offsetY = null;
  16846. }
  16847. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16848. if (!noPreventDefault) {
  16849. evt.preventDefault();
  16850. }
  16851. if (!previousPosition) {
  16852. return;
  16853. }
  16854. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16855. if (index != 0) {
  16856. return;
  16857. }
  16858. _this._offsetX = evt.clientX - previousPosition.x;
  16859. _this._offsetY = -(evt.clientY - previousPosition.y);
  16860. }
  16861. };
  16862. }
  16863. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16864. element.addEventListener("blur", this._onLostFocus);
  16865. };
  16866. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16867. if (this._pointerInput && element) {
  16868. this.camera.getScene().onPointerObservable.remove(this._observer);
  16869. this._observer = null;
  16870. element.removeEventListener("blur", this._onLostFocus);
  16871. this._onLostFocus = null;
  16872. this._pointerPressed = [];
  16873. this._offsetX = null;
  16874. this._offsetY = null;
  16875. this._pointerCount = 0;
  16876. }
  16877. };
  16878. FreeCameraTouchInput.prototype.checkInputs = function () {
  16879. if (this._offsetX) {
  16880. var camera = this.camera;
  16881. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16882. if (this._pointerPressed.length > 1) {
  16883. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16884. }
  16885. else {
  16886. var speed = camera._computeLocalCameraSpeed();
  16887. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16888. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16889. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16890. }
  16891. }
  16892. };
  16893. FreeCameraTouchInput.prototype.getTypeName = function () {
  16894. return "FreeCameraTouchInput";
  16895. };
  16896. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16897. return "touch";
  16898. };
  16899. return FreeCameraTouchInput;
  16900. }());
  16901. __decorate([
  16902. BABYLON.serialize()
  16903. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16904. __decorate([
  16905. BABYLON.serialize()
  16906. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16907. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16908. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16909. })(BABYLON || (BABYLON = {}));
  16910. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16911. var BABYLON;
  16912. (function (BABYLON) {
  16913. var FreeCameraDeviceOrientationInput = (function () {
  16914. function FreeCameraDeviceOrientationInput() {
  16915. var _this = this;
  16916. this._screenOrientationAngle = 0;
  16917. this._screenQuaternion = new BABYLON.Quaternion();
  16918. this._alpha = 0;
  16919. this._beta = 0;
  16920. this._gamma = 0;
  16921. this._orientationChanged = function () {
  16922. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16923. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16924. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16925. };
  16926. this._deviceOrientation = function (evt) {
  16927. _this._alpha = evt.alpha;
  16928. _this._beta = evt.beta;
  16929. _this._gamma = evt.gamma;
  16930. };
  16931. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16932. this._orientationChanged();
  16933. }
  16934. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16935. get: function () {
  16936. return this._camera;
  16937. },
  16938. set: function (camera) {
  16939. this._camera = camera;
  16940. if (!this._camera.rotationQuaternion)
  16941. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16947. window.addEventListener("orientationchange", this._orientationChanged);
  16948. window.addEventListener("deviceorientation", this._deviceOrientation);
  16949. //In certain cases, the attach control is called AFTER orientation was changed,
  16950. //So this is needed.
  16951. this._orientationChanged();
  16952. };
  16953. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16954. window.removeEventListener("orientationchange", this._orientationChanged);
  16955. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16956. };
  16957. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16958. //if no device orientation provided, don't update the rotation.
  16959. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16960. if (!this._alpha)
  16961. return;
  16962. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16963. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16964. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16965. //Mirror on XY Plane
  16966. this._camera.rotationQuaternion.z *= -1;
  16967. this._camera.rotationQuaternion.w *= -1;
  16968. };
  16969. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16970. return "FreeCameraDeviceOrientationInput";
  16971. };
  16972. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16973. return "deviceOrientation";
  16974. };
  16975. return FreeCameraDeviceOrientationInput;
  16976. }());
  16977. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16978. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16979. })(BABYLON || (BABYLON = {}));
  16980. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16981. var BABYLON;
  16982. (function (BABYLON) {
  16983. var FreeCameraGamepadInput = (function () {
  16984. function FreeCameraGamepadInput() {
  16985. this.gamepadAngularSensibility = 200;
  16986. this.gamepadMoveSensibility = 40;
  16987. // private members
  16988. this._cameraTransform = BABYLON.Matrix.Identity();
  16989. this._deltaTransform = BABYLON.Vector3.Zero();
  16990. this._vector3 = BABYLON.Vector3.Zero();
  16991. this._vector2 = BABYLON.Vector2.Zero();
  16992. }
  16993. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16994. var _this = this;
  16995. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16996. };
  16997. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16998. if (this._gamepads) {
  16999. this._gamepads.dispose();
  17000. }
  17001. this.gamepad = null;
  17002. };
  17003. FreeCameraGamepadInput.prototype.checkInputs = function () {
  17004. if (this.gamepad && this.gamepad.leftStick) {
  17005. var camera = this.camera;
  17006. var LSValues = this.gamepad.leftStick;
  17007. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  17008. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17009. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17010. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17011. var RSValues = this.gamepad.rightStick;
  17012. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  17013. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  17014. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  17015. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  17016. if (!camera.rotationQuaternion) {
  17017. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  17018. }
  17019. else {
  17020. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  17021. }
  17022. var speed = camera._computeLocalCameraSpeed() * 50.0;
  17023. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  17024. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  17025. camera.cameraDirection.addInPlace(this._deltaTransform);
  17026. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  17027. camera.cameraRotation.addInPlace(this._vector2);
  17028. }
  17029. };
  17030. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17031. // Only the first gamepad found can control the camera
  17032. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17033. // prioritize XBOX gamepads.
  17034. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17035. this.gamepad = gamepad;
  17036. }
  17037. }
  17038. };
  17039. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17040. return "FreeCameraGamepadInput";
  17041. };
  17042. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17043. return "gamepad";
  17044. };
  17045. return FreeCameraGamepadInput;
  17046. }());
  17047. __decorate([
  17048. BABYLON.serialize()
  17049. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17050. __decorate([
  17051. BABYLON.serialize()
  17052. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17053. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17054. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17055. })(BABYLON || (BABYLON = {}));
  17056. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17057. var BABYLON;
  17058. (function (BABYLON) {
  17059. var ArcRotateCameraKeyboardMoveInput = (function () {
  17060. function ArcRotateCameraKeyboardMoveInput() {
  17061. this._keys = [];
  17062. this.keysUp = [38];
  17063. this.keysDown = [40];
  17064. this.keysLeft = [37];
  17065. this.keysRight = [39];
  17066. }
  17067. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17068. var _this = this;
  17069. element.tabIndex = 1;
  17070. this._onKeyDown = function (evt) {
  17071. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17072. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17073. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17074. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17075. var index = _this._keys.indexOf(evt.keyCode);
  17076. if (index === -1) {
  17077. _this._keys.push(evt.keyCode);
  17078. }
  17079. if (evt.preventDefault) {
  17080. if (!noPreventDefault) {
  17081. evt.preventDefault();
  17082. }
  17083. }
  17084. }
  17085. };
  17086. this._onKeyUp = function (evt) {
  17087. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17088. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17089. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17090. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17091. var index = _this._keys.indexOf(evt.keyCode);
  17092. if (index >= 0) {
  17093. _this._keys.splice(index, 1);
  17094. }
  17095. if (evt.preventDefault) {
  17096. if (!noPreventDefault) {
  17097. evt.preventDefault();
  17098. }
  17099. }
  17100. }
  17101. };
  17102. this._onLostFocus = function () {
  17103. _this._keys = [];
  17104. };
  17105. element.addEventListener("keydown", this._onKeyDown, false);
  17106. element.addEventListener("keyup", this._onKeyUp, false);
  17107. BABYLON.Tools.RegisterTopRootEvents([
  17108. { name: "blur", handler: this._onLostFocus }
  17109. ]);
  17110. };
  17111. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17112. if (element) {
  17113. element.removeEventListener("keydown", this._onKeyDown);
  17114. element.removeEventListener("keyup", this._onKeyUp);
  17115. }
  17116. BABYLON.Tools.UnregisterTopRootEvents([
  17117. { name: "blur", handler: this._onLostFocus }
  17118. ]);
  17119. this._keys = [];
  17120. this._onKeyDown = null;
  17121. this._onKeyUp = null;
  17122. this._onLostFocus = null;
  17123. };
  17124. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17125. if (this._onKeyDown) {
  17126. var camera = this.camera;
  17127. for (var index = 0; index < this._keys.length; index++) {
  17128. var keyCode = this._keys[index];
  17129. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17130. camera.inertialAlphaOffset -= 0.01;
  17131. }
  17132. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17133. camera.inertialBetaOffset -= 0.01;
  17134. }
  17135. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17136. camera.inertialAlphaOffset += 0.01;
  17137. }
  17138. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17139. camera.inertialBetaOffset += 0.01;
  17140. }
  17141. }
  17142. }
  17143. };
  17144. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17145. return "ArcRotateCameraKeyboardMoveInput";
  17146. };
  17147. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17148. return "keyboard";
  17149. };
  17150. return ArcRotateCameraKeyboardMoveInput;
  17151. }());
  17152. __decorate([
  17153. BABYLON.serialize()
  17154. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17155. __decorate([
  17156. BABYLON.serialize()
  17157. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17158. __decorate([
  17159. BABYLON.serialize()
  17160. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17161. __decorate([
  17162. BABYLON.serialize()
  17163. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17164. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17165. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17166. })(BABYLON || (BABYLON = {}));
  17167. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17168. var BABYLON;
  17169. (function (BABYLON) {
  17170. var ArcRotateCameraMouseWheelInput = (function () {
  17171. function ArcRotateCameraMouseWheelInput() {
  17172. this.wheelPrecision = 3.0;
  17173. }
  17174. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17175. var _this = this;
  17176. this._wheel = function (p, s) {
  17177. //sanity check - this should be a PointerWheel event.
  17178. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17179. return;
  17180. var event = p.event;
  17181. var delta = 0;
  17182. if (event.wheelDelta) {
  17183. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17184. }
  17185. else if (event.detail) {
  17186. delta = -event.detail / _this.wheelPrecision;
  17187. }
  17188. if (delta)
  17189. _this.camera.inertialRadiusOffset += delta;
  17190. if (event.preventDefault) {
  17191. if (!noPreventDefault) {
  17192. event.preventDefault();
  17193. }
  17194. }
  17195. };
  17196. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17197. };
  17198. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17199. if (this._observer && element) {
  17200. this.camera.getScene().onPointerObservable.remove(this._observer);
  17201. this._observer = null;
  17202. this._wheel = null;
  17203. }
  17204. };
  17205. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17206. return "ArcRotateCameraMouseWheelInput";
  17207. };
  17208. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17209. return "mousewheel";
  17210. };
  17211. return ArcRotateCameraMouseWheelInput;
  17212. }());
  17213. __decorate([
  17214. BABYLON.serialize()
  17215. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17216. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17217. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17218. })(BABYLON || (BABYLON = {}));
  17219. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17220. var BABYLON;
  17221. (function (BABYLON) {
  17222. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17223. var ArcRotateCameraPointersInput = (function () {
  17224. function ArcRotateCameraPointersInput() {
  17225. this.buttons = [0, 1, 2];
  17226. this.angularSensibilityX = 1000.0;
  17227. this.angularSensibilityY = 1000.0;
  17228. this.pinchPrecision = 6.0;
  17229. this.panningSensibility = 50.0;
  17230. this._isPanClick = false;
  17231. this.pinchInwards = true;
  17232. }
  17233. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17234. var _this = this;
  17235. var engine = this.camera.getEngine();
  17236. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17237. var pointA, pointB;
  17238. var previousPinchDistance = 0;
  17239. this._pointerInput = function (p, s) {
  17240. var evt = p.event;
  17241. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17242. return;
  17243. }
  17244. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17245. try {
  17246. evt.srcElement.setPointerCapture(evt.pointerId);
  17247. }
  17248. catch (e) {
  17249. }
  17250. // Manage panning with pan button click
  17251. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17252. // manage pointers
  17253. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17254. if (pointA === undefined) {
  17255. pointA = cacheSoloPointer;
  17256. }
  17257. else if (pointB === undefined) {
  17258. pointB = cacheSoloPointer;
  17259. }
  17260. if (!noPreventDefault) {
  17261. evt.preventDefault();
  17262. element.focus();
  17263. }
  17264. }
  17265. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17266. try {
  17267. evt.srcElement.releasePointerCapture(evt.pointerId);
  17268. }
  17269. catch (e) {
  17270. }
  17271. cacheSoloPointer = null;
  17272. previousPinchDistance = 0;
  17273. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17274. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17275. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17276. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17277. pointA = pointB = undefined;
  17278. if (!noPreventDefault) {
  17279. evt.preventDefault();
  17280. }
  17281. }
  17282. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17283. if (!noPreventDefault) {
  17284. evt.preventDefault();
  17285. }
  17286. // One button down
  17287. if (pointA && pointB === undefined) {
  17288. if (_this.panningSensibility !== 0 &&
  17289. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17290. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17291. _this.camera
  17292. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17293. _this.camera
  17294. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17295. }
  17296. else {
  17297. var offsetX = evt.clientX - cacheSoloPointer.x;
  17298. var offsetY = evt.clientY - cacheSoloPointer.y;
  17299. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17300. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17301. }
  17302. cacheSoloPointer.x = evt.clientX;
  17303. cacheSoloPointer.y = evt.clientY;
  17304. }
  17305. else if (pointA && pointB) {
  17306. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17307. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17308. ed.x = evt.clientX;
  17309. ed.y = evt.clientY;
  17310. var direction = _this.pinchInwards ? 1 : -1;
  17311. var distX = pointA.x - pointB.x;
  17312. var distY = pointA.y - pointB.y;
  17313. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17314. if (previousPinchDistance === 0) {
  17315. previousPinchDistance = pinchSquaredDistance;
  17316. return;
  17317. }
  17318. if (pinchSquaredDistance !== previousPinchDistance) {
  17319. _this.camera
  17320. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17321. (_this.pinchPrecision *
  17322. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17323. direction);
  17324. previousPinchDistance = pinchSquaredDistance;
  17325. }
  17326. }
  17327. }
  17328. };
  17329. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17330. this._onContextMenu = function (evt) {
  17331. evt.preventDefault();
  17332. };
  17333. if (!this.camera._useCtrlForPanning) {
  17334. element.addEventListener("contextmenu", this._onContextMenu, false);
  17335. }
  17336. this._onLostFocus = function () {
  17337. //this._keys = [];
  17338. pointA = pointB = undefined;
  17339. previousPinchDistance = 0;
  17340. cacheSoloPointer = null;
  17341. };
  17342. this._onMouseMove = function (evt) {
  17343. if (!engine.isPointerLock) {
  17344. return;
  17345. }
  17346. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17347. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17348. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17349. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17350. if (!noPreventDefault) {
  17351. evt.preventDefault();
  17352. }
  17353. };
  17354. this._onGestureStart = function (e) {
  17355. if (window.MSGesture === undefined) {
  17356. return;
  17357. }
  17358. if (!_this._MSGestureHandler) {
  17359. _this._MSGestureHandler = new MSGesture();
  17360. _this._MSGestureHandler.target = element;
  17361. }
  17362. _this._MSGestureHandler.addPointer(e.pointerId);
  17363. };
  17364. this._onGesture = function (e) {
  17365. _this.camera.radius *= e.scale;
  17366. if (e.preventDefault) {
  17367. if (!noPreventDefault) {
  17368. e.stopPropagation();
  17369. e.preventDefault();
  17370. }
  17371. }
  17372. };
  17373. element.addEventListener("mousemove", this._onMouseMove, false);
  17374. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17375. element.addEventListener("MSGestureChange", this._onGesture, false);
  17376. element.addEventListener("keydown", this._onKeyDown, false);
  17377. element.addEventListener("keyup", this._onKeyUp, false);
  17378. BABYLON.Tools.RegisterTopRootEvents([
  17379. { name: "blur", handler: this._onLostFocus }
  17380. ]);
  17381. };
  17382. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17383. if (element && this._observer) {
  17384. this.camera.getScene().onPointerObservable.remove(this._observer);
  17385. this._observer = null;
  17386. element.removeEventListener("contextmenu", this._onContextMenu);
  17387. element.removeEventListener("mousemove", this._onMouseMove);
  17388. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17389. element.removeEventListener("MSGestureChange", this._onGesture);
  17390. element.removeEventListener("keydown", this._onKeyDown);
  17391. element.removeEventListener("keyup", this._onKeyUp);
  17392. this._isPanClick = false;
  17393. this.pinchInwards = true;
  17394. this._onKeyDown = null;
  17395. this._onKeyUp = null;
  17396. this._onMouseMove = null;
  17397. this._onGestureStart = null;
  17398. this._onGesture = null;
  17399. this._MSGestureHandler = null;
  17400. this._onLostFocus = null;
  17401. this._onContextMenu = null;
  17402. }
  17403. BABYLON.Tools.UnregisterTopRootEvents([
  17404. { name: "blur", handler: this._onLostFocus }
  17405. ]);
  17406. };
  17407. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17408. return "ArcRotateCameraPointersInput";
  17409. };
  17410. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17411. return "pointers";
  17412. };
  17413. return ArcRotateCameraPointersInput;
  17414. }());
  17415. __decorate([
  17416. BABYLON.serialize()
  17417. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17418. __decorate([
  17419. BABYLON.serialize()
  17420. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17421. __decorate([
  17422. BABYLON.serialize()
  17423. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17424. __decorate([
  17425. BABYLON.serialize()
  17426. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17427. __decorate([
  17428. BABYLON.serialize()
  17429. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17430. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17431. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17432. })(BABYLON || (BABYLON = {}));
  17433. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17434. var BABYLON;
  17435. (function (BABYLON) {
  17436. var ArcRotateCameraGamepadInput = (function () {
  17437. function ArcRotateCameraGamepadInput() {
  17438. this.gamepadRotationSensibility = 80;
  17439. this.gamepadMoveSensibility = 40;
  17440. }
  17441. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17442. var _this = this;
  17443. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17444. };
  17445. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17446. if (this._gamepads) {
  17447. this._gamepads.dispose();
  17448. }
  17449. this.gamepad = null;
  17450. };
  17451. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17452. if (this.gamepad) {
  17453. var camera = this.camera;
  17454. var RSValues = this.gamepad.rightStick;
  17455. if (RSValues.x != 0) {
  17456. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17457. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17458. camera.inertialAlphaOffset += normalizedRX;
  17459. }
  17460. }
  17461. if (RSValues.y != 0) {
  17462. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17463. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17464. camera.inertialBetaOffset += normalizedRY;
  17465. }
  17466. }
  17467. var LSValues = this.gamepad.leftStick;
  17468. if (LSValues.y != 0) {
  17469. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17470. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17471. this.camera.inertialRadiusOffset -= normalizedLY;
  17472. }
  17473. }
  17474. }
  17475. };
  17476. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17477. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17478. // prioritize XBOX gamepads.
  17479. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17480. this.gamepad = gamepad;
  17481. }
  17482. }
  17483. };
  17484. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17485. return "ArcRotateCameraGamepadInput";
  17486. };
  17487. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17488. return "gamepad";
  17489. };
  17490. return ArcRotateCameraGamepadInput;
  17491. }());
  17492. __decorate([
  17493. BABYLON.serialize()
  17494. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17495. __decorate([
  17496. BABYLON.serialize()
  17497. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17498. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17499. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17500. })(BABYLON || (BABYLON = {}));
  17501. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17502. var BABYLON;
  17503. (function (BABYLON) {
  17504. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17505. function ArcRotateCameraVRDeviceOrientationInput() {
  17506. this.alphaCorrection = 1;
  17507. this.betaCorrection = 1;
  17508. this.gammaCorrection = 1;
  17509. this._alpha = 0;
  17510. this._beta = 0;
  17511. this._gamma = 0;
  17512. this._dirty = false;
  17513. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17514. }
  17515. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17516. this.camera.attachControl(element, noPreventDefault);
  17517. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17518. };
  17519. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17520. var camera = this.camera;
  17521. this._alpha = +evt.alpha | 0;
  17522. this._beta = +evt.beta | 0;
  17523. this._gamma = +evt.gamma | 0;
  17524. this._dirty = true;
  17525. };
  17526. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17527. if (this._dirty) {
  17528. this._dirty = false;
  17529. if (this._gamma < 0) {
  17530. this._gamma = 180 + this._gamma;
  17531. }
  17532. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17533. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17534. }
  17535. };
  17536. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17537. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17538. };
  17539. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17540. return "ArcRotateCameraVRDeviceOrientationInput";
  17541. };
  17542. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17543. return "VRDeviceOrientation";
  17544. };
  17545. return ArcRotateCameraVRDeviceOrientationInput;
  17546. }());
  17547. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17548. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17549. })(BABYLON || (BABYLON = {}));
  17550. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17551. /// <reference path="babylon.camera.ts" />
  17552. var BABYLON;
  17553. (function (BABYLON) {
  17554. var TargetCamera = (function (_super) {
  17555. __extends(TargetCamera, _super);
  17556. function TargetCamera(name, position, scene) {
  17557. var _this = _super.call(this, name, position, scene) || this;
  17558. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17559. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17560. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17561. _this.speed = 2.0;
  17562. _this.noRotationConstraint = false;
  17563. _this.lockedTarget = null;
  17564. _this._currentTarget = BABYLON.Vector3.Zero();
  17565. _this._viewMatrix = BABYLON.Matrix.Zero();
  17566. _this._camMatrix = BABYLON.Matrix.Zero();
  17567. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17568. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17569. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17570. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17571. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17572. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17573. _this._tempMatrix = BABYLON.Matrix.Zero();
  17574. return _this;
  17575. }
  17576. TargetCamera.prototype.getFrontPosition = function (distance) {
  17577. var direction = this.getTarget().subtract(this.position);
  17578. direction.normalize();
  17579. direction.scaleInPlace(distance);
  17580. return this.globalPosition.add(direction);
  17581. };
  17582. TargetCamera.prototype._getLockedTargetPosition = function () {
  17583. if (!this.lockedTarget) {
  17584. return null;
  17585. }
  17586. if (this.lockedTarget.absolutePosition) {
  17587. this.lockedTarget.computeWorldMatrix();
  17588. }
  17589. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17590. };
  17591. // Cache
  17592. TargetCamera.prototype._initCache = function () {
  17593. _super.prototype._initCache.call(this);
  17594. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17595. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17596. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17597. };
  17598. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17599. if (!ignoreParentClass) {
  17600. _super.prototype._updateCache.call(this);
  17601. }
  17602. var lockedTargetPosition = this._getLockedTargetPosition();
  17603. if (!lockedTargetPosition) {
  17604. this._cache.lockedTarget = null;
  17605. }
  17606. else {
  17607. if (!this._cache.lockedTarget) {
  17608. this._cache.lockedTarget = lockedTargetPosition.clone();
  17609. }
  17610. else {
  17611. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17612. }
  17613. }
  17614. this._cache.rotation.copyFrom(this.rotation);
  17615. if (this.rotationQuaternion)
  17616. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17617. };
  17618. // Synchronized
  17619. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17620. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17621. return false;
  17622. }
  17623. var lockedTargetPosition = this._getLockedTargetPosition();
  17624. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17625. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17626. };
  17627. // Methods
  17628. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17629. var engine = this.getEngine();
  17630. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17631. };
  17632. // Target
  17633. TargetCamera.prototype.setTarget = function (target) {
  17634. this.upVector.normalize();
  17635. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17636. this._camMatrix.invert();
  17637. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17638. var vDir = target.subtract(this.position);
  17639. if (vDir.x >= 0.0) {
  17640. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17641. }
  17642. else {
  17643. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17644. }
  17645. this.rotation.z = 0;
  17646. if (isNaN(this.rotation.x)) {
  17647. this.rotation.x = 0;
  17648. }
  17649. if (isNaN(this.rotation.y)) {
  17650. this.rotation.y = 0;
  17651. }
  17652. if (isNaN(this.rotation.z)) {
  17653. this.rotation.z = 0;
  17654. }
  17655. if (this.rotationQuaternion) {
  17656. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17657. }
  17658. };
  17659. /**
  17660. * Return the current target position of the camera. This value is expressed in local space.
  17661. */
  17662. TargetCamera.prototype.getTarget = function () {
  17663. return this._currentTarget;
  17664. };
  17665. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17666. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17667. };
  17668. TargetCamera.prototype._updatePosition = function () {
  17669. if (this.parent) {
  17670. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  17671. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  17672. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  17673. return;
  17674. }
  17675. this.position.addInPlace(this.cameraDirection);
  17676. };
  17677. TargetCamera.prototype._checkInputs = function () {
  17678. var needToMove = this._decideIfNeedsToMove();
  17679. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17680. // Move
  17681. if (needToMove) {
  17682. this._updatePosition();
  17683. }
  17684. // Rotate
  17685. if (needToRotate) {
  17686. this.rotation.x += this.cameraRotation.x;
  17687. this.rotation.y += this.cameraRotation.y;
  17688. //rotate, if quaternion is set and rotation was used
  17689. if (this.rotationQuaternion) {
  17690. var len = this.rotation.lengthSquared();
  17691. if (len) {
  17692. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17693. }
  17694. }
  17695. if (!this.noRotationConstraint) {
  17696. var limit = (Math.PI / 2) * 0.95;
  17697. if (this.rotation.x > limit)
  17698. this.rotation.x = limit;
  17699. if (this.rotation.x < -limit)
  17700. this.rotation.x = -limit;
  17701. }
  17702. }
  17703. // Inertia
  17704. if (needToMove) {
  17705. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17706. this.cameraDirection.x = 0;
  17707. }
  17708. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17709. this.cameraDirection.y = 0;
  17710. }
  17711. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17712. this.cameraDirection.z = 0;
  17713. }
  17714. this.cameraDirection.scaleInPlace(this.inertia);
  17715. }
  17716. if (needToRotate) {
  17717. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17718. this.cameraRotation.x = 0;
  17719. }
  17720. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17721. this.cameraRotation.y = 0;
  17722. }
  17723. this.cameraRotation.scaleInPlace(this.inertia);
  17724. }
  17725. _super.prototype._checkInputs.call(this);
  17726. };
  17727. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17728. if (this.rotationQuaternion) {
  17729. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17730. //update the up vector!
  17731. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17732. }
  17733. else {
  17734. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17735. }
  17736. };
  17737. TargetCamera.prototype._getViewMatrix = function () {
  17738. if (!this.lockedTarget) {
  17739. // Compute
  17740. this._updateCameraRotationMatrix();
  17741. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17742. // Computing target and final matrix
  17743. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17744. }
  17745. else {
  17746. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17747. }
  17748. if (this.getScene().useRightHandedSystem) {
  17749. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17750. }
  17751. else {
  17752. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17753. }
  17754. return this._viewMatrix;
  17755. };
  17756. /**
  17757. * @override
  17758. * Override Camera.createRigCamera
  17759. */
  17760. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17761. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17762. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17763. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17764. if (!this.rotationQuaternion) {
  17765. this.rotationQuaternion = new BABYLON.Quaternion();
  17766. }
  17767. rigCamera._cameraRigParams = {};
  17768. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17769. }
  17770. return rigCamera;
  17771. }
  17772. return null;
  17773. };
  17774. /**
  17775. * @override
  17776. * Override Camera._updateRigCameras
  17777. */
  17778. TargetCamera.prototype._updateRigCameras = function () {
  17779. var camLeft = this._rigCameras[0];
  17780. var camRight = this._rigCameras[1];
  17781. switch (this.cameraRigMode) {
  17782. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17783. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17784. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17785. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17786. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17787. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17788. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17789. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17790. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17791. camLeft.setTarget(this.getTarget());
  17792. camRight.setTarget(this.getTarget());
  17793. break;
  17794. case BABYLON.Camera.RIG_MODE_VR:
  17795. if (camLeft.rotationQuaternion) {
  17796. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17797. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17798. }
  17799. else {
  17800. camLeft.rotation.copyFrom(this.rotation);
  17801. camRight.rotation.copyFrom(this.rotation);
  17802. }
  17803. camLeft.position.copyFrom(this.position);
  17804. camRight.position.copyFrom(this.position);
  17805. break;
  17806. }
  17807. _super.prototype._updateRigCameras.call(this);
  17808. };
  17809. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17810. if (!this._rigCamTransformMatrix) {
  17811. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17812. }
  17813. var target = this.getTarget();
  17814. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17815. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17816. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17817. };
  17818. TargetCamera.prototype.getClassName = function () {
  17819. return "TargetCamera";
  17820. };
  17821. return TargetCamera;
  17822. }(BABYLON.Camera));
  17823. __decorate([
  17824. BABYLON.serializeAsVector3()
  17825. ], TargetCamera.prototype, "rotation", void 0);
  17826. __decorate([
  17827. BABYLON.serialize()
  17828. ], TargetCamera.prototype, "speed", void 0);
  17829. __decorate([
  17830. BABYLON.serializeAsMeshReference("lockedTargetId")
  17831. ], TargetCamera.prototype, "lockedTarget", void 0);
  17832. BABYLON.TargetCamera = TargetCamera;
  17833. })(BABYLON || (BABYLON = {}));
  17834. //# sourceMappingURL=babylon.targetCamera.js.map
  17835. var BABYLON;
  17836. (function (BABYLON) {
  17837. var FreeCamera = (function (_super) {
  17838. __extends(FreeCamera, _super);
  17839. function FreeCamera(name, position, scene) {
  17840. var _this = _super.call(this, name, position, scene) || this;
  17841. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17842. _this.checkCollisions = false;
  17843. _this.applyGravity = false;
  17844. _this._collider = new BABYLON.Collider();
  17845. _this._needMoveForGravity = false;
  17846. _this._oldPosition = BABYLON.Vector3.Zero();
  17847. _this._diffPosition = BABYLON.Vector3.Zero();
  17848. _this._newPosition = BABYLON.Vector3.Zero();
  17849. // Collisions
  17850. _this._collisionMask = -1;
  17851. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17852. if (collidedMesh === void 0) { collidedMesh = null; }
  17853. //TODO move this to the collision coordinator!
  17854. if (_this.getScene().workerCollisions)
  17855. newPosition.multiplyInPlace(_this._collider.radius);
  17856. var updatePosition = function (newPos) {
  17857. _this._newPosition.copyFrom(newPos);
  17858. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17859. var oldPosition = _this.position.clone();
  17860. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17861. _this.position.addInPlace(_this._diffPosition);
  17862. if (_this.onCollide && collidedMesh) {
  17863. _this.onCollide(collidedMesh);
  17864. }
  17865. }
  17866. };
  17867. updatePosition(newPosition);
  17868. };
  17869. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17870. _this.inputs.addKeyboard().addMouse();
  17871. return _this;
  17872. }
  17873. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17874. //-- begin properties for backward compatibility for inputs
  17875. get: function () {
  17876. var mouse = this.inputs.attached["mouse"];
  17877. if (mouse)
  17878. return mouse.angularSensibility;
  17879. },
  17880. set: function (value) {
  17881. var mouse = this.inputs.attached["mouse"];
  17882. if (mouse)
  17883. mouse.angularSensibility = value;
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17889. get: function () {
  17890. var keyboard = this.inputs.attached["keyboard"];
  17891. if (keyboard)
  17892. return keyboard.keysUp;
  17893. },
  17894. set: function (value) {
  17895. var keyboard = this.inputs.attached["keyboard"];
  17896. if (keyboard)
  17897. keyboard.keysUp = value;
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17903. get: function () {
  17904. var keyboard = this.inputs.attached["keyboard"];
  17905. if (keyboard)
  17906. return keyboard.keysDown;
  17907. },
  17908. set: function (value) {
  17909. var keyboard = this.inputs.attached["keyboard"];
  17910. if (keyboard)
  17911. keyboard.keysDown = value;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17917. get: function () {
  17918. var keyboard = this.inputs.attached["keyboard"];
  17919. if (keyboard)
  17920. return keyboard.keysLeft;
  17921. },
  17922. set: function (value) {
  17923. var keyboard = this.inputs.attached["keyboard"];
  17924. if (keyboard)
  17925. keyboard.keysLeft = value;
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17931. get: function () {
  17932. var keyboard = this.inputs.attached["keyboard"];
  17933. if (keyboard)
  17934. return keyboard.keysRight;
  17935. },
  17936. set: function (value) {
  17937. var keyboard = this.inputs.attached["keyboard"];
  17938. if (keyboard)
  17939. keyboard.keysRight = value;
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. // Controls
  17945. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17946. this.inputs.attachElement(element, noPreventDefault);
  17947. };
  17948. FreeCamera.prototype.detachControl = function (element) {
  17949. this.inputs.detachElement(element);
  17950. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17951. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17952. };
  17953. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17954. get: function () {
  17955. return this._collisionMask;
  17956. },
  17957. set: function (mask) {
  17958. this._collisionMask = !isNaN(mask) ? mask : -1;
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17964. var globalPosition;
  17965. if (this.parent) {
  17966. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17967. }
  17968. else {
  17969. globalPosition = this.position;
  17970. }
  17971. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17972. this._collider.radius = this.ellipsoid;
  17973. this._collider.collisionMask = this._collisionMask;
  17974. //no need for clone, as long as gravity is not on.
  17975. var actualVelocity = velocity;
  17976. //add gravity to the velocity to prevent the dual-collision checking
  17977. if (this.applyGravity) {
  17978. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17979. actualVelocity = velocity.add(this.getScene().gravity);
  17980. }
  17981. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17982. };
  17983. FreeCamera.prototype._checkInputs = function () {
  17984. if (!this._localDirection) {
  17985. this._localDirection = BABYLON.Vector3.Zero();
  17986. this._transformedDirection = BABYLON.Vector3.Zero();
  17987. }
  17988. this.inputs.checkInputs();
  17989. _super.prototype._checkInputs.call(this);
  17990. };
  17991. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17992. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17993. };
  17994. FreeCamera.prototype._updatePosition = function () {
  17995. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17996. this._collideWithWorld(this.cameraDirection);
  17997. }
  17998. else {
  17999. _super.prototype._updatePosition.call(this);
  18000. }
  18001. };
  18002. FreeCamera.prototype.dispose = function () {
  18003. this.inputs.clear();
  18004. _super.prototype.dispose.call(this);
  18005. };
  18006. FreeCamera.prototype.getClassName = function () {
  18007. return "FreeCamera";
  18008. };
  18009. return FreeCamera;
  18010. }(BABYLON.TargetCamera));
  18011. __decorate([
  18012. BABYLON.serializeAsVector3()
  18013. ], FreeCamera.prototype, "ellipsoid", void 0);
  18014. __decorate([
  18015. BABYLON.serialize()
  18016. ], FreeCamera.prototype, "checkCollisions", void 0);
  18017. __decorate([
  18018. BABYLON.serialize()
  18019. ], FreeCamera.prototype, "applyGravity", void 0);
  18020. BABYLON.FreeCamera = FreeCamera;
  18021. })(BABYLON || (BABYLON = {}));
  18022. //# sourceMappingURL=babylon.freeCamera.js.map
  18023. var BABYLON;
  18024. (function (BABYLON) {
  18025. var FreeCameraInputsManager = (function (_super) {
  18026. __extends(FreeCameraInputsManager, _super);
  18027. function FreeCameraInputsManager(camera) {
  18028. return _super.call(this, camera) || this;
  18029. }
  18030. FreeCameraInputsManager.prototype.addKeyboard = function () {
  18031. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18032. return this;
  18033. };
  18034. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18035. if (touchEnabled === void 0) { touchEnabled = true; }
  18036. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18037. return this;
  18038. };
  18039. FreeCameraInputsManager.prototype.addGamepad = function () {
  18040. this.add(new BABYLON.FreeCameraGamepadInput());
  18041. return this;
  18042. };
  18043. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18044. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18045. return this;
  18046. };
  18047. FreeCameraInputsManager.prototype.addTouch = function () {
  18048. this.add(new BABYLON.FreeCameraTouchInput());
  18049. return this;
  18050. };
  18051. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18052. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18053. return this;
  18054. };
  18055. return FreeCameraInputsManager;
  18056. }(BABYLON.CameraInputsManager));
  18057. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18058. })(BABYLON || (BABYLON = {}));
  18059. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18060. /// <reference path="babylon.targetCamera.ts" />
  18061. var BABYLON;
  18062. (function (BABYLON) {
  18063. var FollowCamera = (function (_super) {
  18064. __extends(FollowCamera, _super);
  18065. function FollowCamera(name, position, scene, lockedTarget) {
  18066. var _this = _super.call(this, name, position, scene) || this;
  18067. _this.radius = 12;
  18068. _this.rotationOffset = 0;
  18069. _this.heightOffset = 4;
  18070. _this.cameraAcceleration = 0.05;
  18071. _this.maxCameraSpeed = 20;
  18072. _this.lockedTarget = lockedTarget;
  18073. return _this;
  18074. }
  18075. FollowCamera.prototype.getRadians = function (degrees) {
  18076. return degrees * Math.PI / 180;
  18077. };
  18078. FollowCamera.prototype.follow = function (cameraTarget) {
  18079. if (!cameraTarget)
  18080. return;
  18081. var yRotation;
  18082. if (cameraTarget.rotationQuaternion) {
  18083. var rotMatrix = new BABYLON.Matrix();
  18084. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18085. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18086. }
  18087. else {
  18088. yRotation = cameraTarget.rotation.y;
  18089. }
  18090. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18091. var targetPosition = cameraTarget.getAbsolutePosition();
  18092. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18093. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18094. var dx = targetX - this.position.x;
  18095. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18096. var dz = (targetZ) - this.position.z;
  18097. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18098. var vy = dy * this.cameraAcceleration;
  18099. var vz = dz * this.cameraAcceleration * 2;
  18100. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18101. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18102. }
  18103. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18104. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18105. }
  18106. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18107. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18108. }
  18109. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18110. this.setTarget(targetPosition);
  18111. };
  18112. FollowCamera.prototype._checkInputs = function () {
  18113. _super.prototype._checkInputs.call(this);
  18114. this.follow(this.lockedTarget);
  18115. };
  18116. FollowCamera.prototype.getClassName = function () {
  18117. return "FollowCamera";
  18118. };
  18119. return FollowCamera;
  18120. }(BABYLON.TargetCamera));
  18121. __decorate([
  18122. BABYLON.serialize()
  18123. ], FollowCamera.prototype, "radius", void 0);
  18124. __decorate([
  18125. BABYLON.serialize()
  18126. ], FollowCamera.prototype, "rotationOffset", void 0);
  18127. __decorate([
  18128. BABYLON.serialize()
  18129. ], FollowCamera.prototype, "heightOffset", void 0);
  18130. __decorate([
  18131. BABYLON.serialize()
  18132. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18133. __decorate([
  18134. BABYLON.serialize()
  18135. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18136. __decorate([
  18137. BABYLON.serializeAsMeshReference("lockedTargetId")
  18138. ], FollowCamera.prototype, "lockedTarget", void 0);
  18139. BABYLON.FollowCamera = FollowCamera;
  18140. var ArcFollowCamera = (function (_super) {
  18141. __extends(ArcFollowCamera, _super);
  18142. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18143. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18144. _this.alpha = alpha;
  18145. _this.beta = beta;
  18146. _this.radius = radius;
  18147. _this.target = target;
  18148. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18149. _this.follow();
  18150. return _this;
  18151. }
  18152. ArcFollowCamera.prototype.follow = function () {
  18153. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18154. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18155. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18156. var targetPosition = this.target.getAbsolutePosition();
  18157. this.position = targetPosition.add(this._cartesianCoordinates);
  18158. this.setTarget(targetPosition);
  18159. };
  18160. ArcFollowCamera.prototype._checkInputs = function () {
  18161. _super.prototype._checkInputs.call(this);
  18162. this.follow();
  18163. };
  18164. ArcFollowCamera.prototype.getClassName = function () {
  18165. return "ArcFollowCamera";
  18166. };
  18167. return ArcFollowCamera;
  18168. }(BABYLON.TargetCamera));
  18169. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18170. })(BABYLON || (BABYLON = {}));
  18171. //# sourceMappingURL=babylon.followCamera.js.map
  18172. /// <reference path="babylon.freeCamera.ts" />
  18173. var BABYLON;
  18174. (function (BABYLON) {
  18175. // We're mainly based on the logic defined into the FreeCamera code
  18176. var TouchCamera = (function (_super) {
  18177. __extends(TouchCamera, _super);
  18178. //-- end properties for backward compatibility for inputs
  18179. function TouchCamera(name, position, scene) {
  18180. var _this = _super.call(this, name, position, scene) || this;
  18181. _this.inputs.addTouch();
  18182. _this._setupInputs();
  18183. return _this;
  18184. }
  18185. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18186. //-- Begin properties for backward compatibility for inputs
  18187. get: function () {
  18188. var touch = this.inputs.attached["touch"];
  18189. if (touch)
  18190. return touch.touchAngularSensibility;
  18191. },
  18192. set: function (value) {
  18193. var touch = this.inputs.attached["touch"];
  18194. if (touch)
  18195. touch.touchAngularSensibility = value;
  18196. },
  18197. enumerable: true,
  18198. configurable: true
  18199. });
  18200. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18201. get: function () {
  18202. var touch = this.inputs.attached["touch"];
  18203. if (touch)
  18204. return touch.touchMoveSensibility;
  18205. },
  18206. set: function (value) {
  18207. var touch = this.inputs.attached["touch"];
  18208. if (touch)
  18209. touch.touchMoveSensibility = value;
  18210. },
  18211. enumerable: true,
  18212. configurable: true
  18213. });
  18214. TouchCamera.prototype.getClassName = function () {
  18215. return "TouchCamera";
  18216. };
  18217. TouchCamera.prototype._setupInputs = function () {
  18218. var mouse = this.inputs.attached["mouse"];
  18219. if (mouse) {
  18220. mouse.touchEnabled = false;
  18221. }
  18222. };
  18223. return TouchCamera;
  18224. }(BABYLON.FreeCamera));
  18225. BABYLON.TouchCamera = TouchCamera;
  18226. })(BABYLON || (BABYLON = {}));
  18227. //# sourceMappingURL=babylon.touchCamera.js.map
  18228. /// <reference path="babylon.targetCamera.ts" />
  18229. /// <reference path="..\Tools\babylon.tools.ts" />
  18230. var BABYLON;
  18231. (function (BABYLON) {
  18232. var ArcRotateCamera = (function (_super) {
  18233. __extends(ArcRotateCamera, _super);
  18234. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18235. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18236. _this.inertialAlphaOffset = 0;
  18237. _this.inertialBetaOffset = 0;
  18238. _this.inertialRadiusOffset = 0;
  18239. _this.lowerAlphaLimit = null;
  18240. _this.upperAlphaLimit = null;
  18241. _this.lowerBetaLimit = 0.01;
  18242. _this.upperBetaLimit = Math.PI;
  18243. _this.lowerRadiusLimit = null;
  18244. _this.upperRadiusLimit = null;
  18245. _this.inertialPanningX = 0;
  18246. _this.inertialPanningY = 0;
  18247. //-- end properties for backward compatibility for inputs
  18248. _this.zoomOnFactor = 1;
  18249. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18250. _this.allowUpsideDown = true;
  18251. _this._viewMatrix = new BABYLON.Matrix();
  18252. // Panning
  18253. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18254. _this.checkCollisions = false;
  18255. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18256. _this._collider = new BABYLON.Collider();
  18257. _this._previousPosition = BABYLON.Vector3.Zero();
  18258. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18259. _this._newPosition = BABYLON.Vector3.Zero();
  18260. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18261. if (collidedMesh === void 0) { collidedMesh = null; }
  18262. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18263. newPosition.multiplyInPlace(_this._collider.radius);
  18264. }
  18265. if (!collidedMesh) {
  18266. _this._previousPosition.copyFrom(_this.position);
  18267. }
  18268. else {
  18269. _this.setPosition(newPosition);
  18270. if (_this.onCollide) {
  18271. _this.onCollide(collidedMesh);
  18272. }
  18273. }
  18274. // Recompute because of constraints
  18275. var cosa = Math.cos(_this.alpha);
  18276. var sina = Math.sin(_this.alpha);
  18277. var cosb = Math.cos(_this.beta);
  18278. var sinb = Math.sin(_this.beta);
  18279. if (sinb === 0) {
  18280. sinb = 0.0001;
  18281. }
  18282. var target = _this._getTargetPosition();
  18283. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18284. _this.position.copyFrom(_this._newPosition);
  18285. var up = _this.upVector;
  18286. if (_this.allowUpsideDown && _this.beta < 0) {
  18287. up = up.clone();
  18288. up = up.negate();
  18289. }
  18290. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18291. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18292. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18293. _this._collisionTriggered = false;
  18294. };
  18295. if (!target) {
  18296. _this.target = BABYLON.Vector3.Zero();
  18297. }
  18298. else {
  18299. _this.target = target;
  18300. }
  18301. _this.alpha = alpha;
  18302. _this.beta = beta;
  18303. _this.radius = radius;
  18304. _this.getViewMatrix();
  18305. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18306. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18307. return _this;
  18308. }
  18309. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18310. //-- begin properties for backward compatibility for inputs
  18311. get: function () {
  18312. var pointers = this.inputs.attached["pointers"];
  18313. if (pointers)
  18314. return pointers.angularSensibilityX;
  18315. },
  18316. set: function (value) {
  18317. var pointers = this.inputs.attached["pointers"];
  18318. if (pointers) {
  18319. pointers.angularSensibilityX = value;
  18320. }
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18326. get: function () {
  18327. var pointers = this.inputs.attached["pointers"];
  18328. if (pointers)
  18329. return pointers.angularSensibilityY;
  18330. },
  18331. set: function (value) {
  18332. var pointers = this.inputs.attached["pointers"];
  18333. if (pointers) {
  18334. pointers.angularSensibilityY = value;
  18335. }
  18336. },
  18337. enumerable: true,
  18338. configurable: true
  18339. });
  18340. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18341. get: function () {
  18342. var pointers = this.inputs.attached["pointers"];
  18343. if (pointers)
  18344. return pointers.pinchPrecision;
  18345. },
  18346. set: function (value) {
  18347. var pointers = this.inputs.attached["pointers"];
  18348. if (pointers) {
  18349. pointers.pinchPrecision = value;
  18350. }
  18351. },
  18352. enumerable: true,
  18353. configurable: true
  18354. });
  18355. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18356. get: function () {
  18357. var pointers = this.inputs.attached["pointers"];
  18358. if (pointers)
  18359. return pointers.panningSensibility;
  18360. },
  18361. set: function (value) {
  18362. var pointers = this.inputs.attached["pointers"];
  18363. if (pointers) {
  18364. pointers.panningSensibility = value;
  18365. }
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18371. get: function () {
  18372. var keyboard = this.inputs.attached["keyboard"];
  18373. if (keyboard)
  18374. return keyboard.keysUp;
  18375. },
  18376. set: function (value) {
  18377. var keyboard = this.inputs.attached["keyboard"];
  18378. if (keyboard)
  18379. keyboard.keysUp = value;
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18385. get: function () {
  18386. var keyboard = this.inputs.attached["keyboard"];
  18387. if (keyboard)
  18388. return keyboard.keysDown;
  18389. },
  18390. set: function (value) {
  18391. var keyboard = this.inputs.attached["keyboard"];
  18392. if (keyboard)
  18393. keyboard.keysDown = value;
  18394. },
  18395. enumerable: true,
  18396. configurable: true
  18397. });
  18398. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18399. get: function () {
  18400. var keyboard = this.inputs.attached["keyboard"];
  18401. if (keyboard)
  18402. return keyboard.keysLeft;
  18403. },
  18404. set: function (value) {
  18405. var keyboard = this.inputs.attached["keyboard"];
  18406. if (keyboard)
  18407. keyboard.keysLeft = value;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18413. get: function () {
  18414. var keyboard = this.inputs.attached["keyboard"];
  18415. if (keyboard)
  18416. return keyboard.keysRight;
  18417. },
  18418. set: function (value) {
  18419. var keyboard = this.inputs.attached["keyboard"];
  18420. if (keyboard)
  18421. keyboard.keysRight = value;
  18422. },
  18423. enumerable: true,
  18424. configurable: true
  18425. });
  18426. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18427. get: function () {
  18428. var mousewheel = this.inputs.attached["mousewheel"];
  18429. if (mousewheel)
  18430. return mousewheel.wheelPrecision;
  18431. },
  18432. set: function (value) {
  18433. var mousewheel = this.inputs.attached["mousewheel"];
  18434. if (mousewheel)
  18435. mousewheel.wheelPrecision = value;
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. // Cache
  18441. ArcRotateCamera.prototype._initCache = function () {
  18442. _super.prototype._initCache.call(this);
  18443. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18444. this._cache.alpha = undefined;
  18445. this._cache.beta = undefined;
  18446. this._cache.radius = undefined;
  18447. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18448. };
  18449. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18450. if (!ignoreParentClass) {
  18451. _super.prototype._updateCache.call(this);
  18452. }
  18453. this._cache.target.copyFrom(this._getTargetPosition());
  18454. this._cache.alpha = this.alpha;
  18455. this._cache.beta = this.beta;
  18456. this._cache.radius = this.radius;
  18457. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18458. };
  18459. ArcRotateCamera.prototype._getTargetPosition = function () {
  18460. if (this.target.getAbsolutePosition) {
  18461. var pos = this.target.getAbsolutePosition();
  18462. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18463. }
  18464. return this.target;
  18465. };
  18466. // Synchronized
  18467. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18468. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18469. return false;
  18470. return this._cache.target.equals(this.target)
  18471. && this._cache.alpha === this.alpha
  18472. && this._cache.beta === this.beta
  18473. && this._cache.radius === this.radius
  18474. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18475. };
  18476. // Methods
  18477. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18478. var _this = this;
  18479. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18480. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18481. this._useCtrlForPanning = useCtrlForPanning;
  18482. this._panningMouseButton = panningMouseButton;
  18483. this.inputs.attachElement(element, noPreventDefault);
  18484. this._reset = function () {
  18485. _this.inertialAlphaOffset = 0;
  18486. _this.inertialBetaOffset = 0;
  18487. _this.inertialRadiusOffset = 0;
  18488. };
  18489. };
  18490. ArcRotateCamera.prototype.detachControl = function (element) {
  18491. this.inputs.detachElement(element);
  18492. if (this._reset) {
  18493. this._reset();
  18494. }
  18495. };
  18496. ArcRotateCamera.prototype._checkInputs = function () {
  18497. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18498. if (this._collisionTriggered) {
  18499. return;
  18500. }
  18501. this.inputs.checkInputs();
  18502. // Inertia
  18503. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18504. if (this.getScene().useRightHandedSystem) {
  18505. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18506. }
  18507. else {
  18508. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18509. }
  18510. this.beta += this.inertialBetaOffset;
  18511. this.radius -= this.inertialRadiusOffset;
  18512. this.inertialAlphaOffset *= this.inertia;
  18513. this.inertialBetaOffset *= this.inertia;
  18514. this.inertialRadiusOffset *= this.inertia;
  18515. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18516. this.inertialAlphaOffset = 0;
  18517. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18518. this.inertialBetaOffset = 0;
  18519. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18520. this.inertialRadiusOffset = 0;
  18521. }
  18522. // Panning inertia
  18523. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18524. if (!this._localDirection) {
  18525. this._localDirection = BABYLON.Vector3.Zero();
  18526. this._transformedDirection = BABYLON.Vector3.Zero();
  18527. }
  18528. this.inertialPanningX *= this.inertia;
  18529. this.inertialPanningY *= this.inertia;
  18530. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18531. this.inertialPanningX = 0;
  18532. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18533. this.inertialPanningY = 0;
  18534. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18535. this._localDirection.multiplyInPlace(this.panningAxis);
  18536. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18537. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18538. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18539. if (!this.panningAxis.y) {
  18540. this._transformedDirection.y = 0;
  18541. }
  18542. if (!this.target.getAbsolutePosition) {
  18543. this.target.addInPlace(this._transformedDirection);
  18544. }
  18545. }
  18546. // Limits
  18547. this._checkLimits();
  18548. _super.prototype._checkInputs.call(this);
  18549. };
  18550. ArcRotateCamera.prototype._checkLimits = function () {
  18551. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18552. if (this.allowUpsideDown && this.beta > Math.PI) {
  18553. this.beta = this.beta - (2 * Math.PI);
  18554. }
  18555. }
  18556. else {
  18557. if (this.beta < this.lowerBetaLimit) {
  18558. this.beta = this.lowerBetaLimit;
  18559. }
  18560. }
  18561. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18562. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18563. this.beta = this.beta + (2 * Math.PI);
  18564. }
  18565. }
  18566. else {
  18567. if (this.beta > this.upperBetaLimit) {
  18568. this.beta = this.upperBetaLimit;
  18569. }
  18570. }
  18571. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18572. this.alpha = this.lowerAlphaLimit;
  18573. }
  18574. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18575. this.alpha = this.upperAlphaLimit;
  18576. }
  18577. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18578. this.radius = this.lowerRadiusLimit;
  18579. }
  18580. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18581. this.radius = this.upperRadiusLimit;
  18582. }
  18583. };
  18584. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18585. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18586. this.radius = radiusv3.length();
  18587. // Alpha
  18588. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18589. if (radiusv3.z < 0) {
  18590. this.alpha = 2 * Math.PI - this.alpha;
  18591. }
  18592. // Beta
  18593. this.beta = Math.acos(radiusv3.y / this.radius);
  18594. this._checkLimits();
  18595. };
  18596. ArcRotateCamera.prototype.setPosition = function (position) {
  18597. if (this.position.equals(position)) {
  18598. return;
  18599. }
  18600. this.position.copyFrom(position);
  18601. this.rebuildAnglesAndRadius();
  18602. };
  18603. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18604. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18605. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18606. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18607. return;
  18608. }
  18609. if (toBoundingCenter && target.getBoundingInfo) {
  18610. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  18611. }
  18612. else {
  18613. this._targetBoundingCenter = null;
  18614. }
  18615. this.target = target;
  18616. this.rebuildAnglesAndRadius();
  18617. };
  18618. ArcRotateCamera.prototype._getViewMatrix = function () {
  18619. // Compute
  18620. var cosa = Math.cos(this.alpha);
  18621. var sina = Math.sin(this.alpha);
  18622. var cosb = Math.cos(this.beta);
  18623. var sinb = Math.sin(this.beta);
  18624. if (sinb === 0) {
  18625. sinb = 0.0001;
  18626. }
  18627. var target = this._getTargetPosition();
  18628. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18629. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18630. this._collider.radius = this.collisionRadius;
  18631. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18632. this._collisionTriggered = true;
  18633. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18634. }
  18635. else {
  18636. this.position.copyFrom(this._newPosition);
  18637. var up = this.upVector;
  18638. if (this.allowUpsideDown && sinb < 0) {
  18639. up = up.clone();
  18640. up = up.negate();
  18641. }
  18642. if (this.getScene().useRightHandedSystem) {
  18643. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18644. }
  18645. else {
  18646. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18647. }
  18648. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18649. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18650. }
  18651. this._currentTarget = target;
  18652. return this._viewMatrix;
  18653. };
  18654. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18655. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18656. meshes = meshes || this.getScene().meshes;
  18657. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18658. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18659. this.radius = distance * this.zoomOnFactor;
  18660. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18661. };
  18662. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18663. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18664. var meshesOrMinMaxVector;
  18665. var distance;
  18666. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18667. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18668. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18669. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18670. }
  18671. else {
  18672. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18673. distance = meshesOrMinMaxVectorAndDistance.distance;
  18674. }
  18675. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18676. if (!doNotUpdateMaxZ) {
  18677. this.maxZ = distance * 2;
  18678. }
  18679. };
  18680. /**
  18681. * @override
  18682. * Override Camera.createRigCamera
  18683. */
  18684. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18685. var alphaShift;
  18686. switch (this.cameraRigMode) {
  18687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18690. case BABYLON.Camera.RIG_MODE_VR:
  18691. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18692. break;
  18693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18694. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18695. break;
  18696. }
  18697. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18698. rigCam._cameraRigParams = {};
  18699. return rigCam;
  18700. };
  18701. /**
  18702. * @override
  18703. * Override Camera._updateRigCameras
  18704. */
  18705. ArcRotateCamera.prototype._updateRigCameras = function () {
  18706. var camLeft = this._rigCameras[0];
  18707. var camRight = this._rigCameras[1];
  18708. camLeft.beta = camRight.beta = this.beta;
  18709. camLeft.radius = camRight.radius = this.radius;
  18710. switch (this.cameraRigMode) {
  18711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18714. case BABYLON.Camera.RIG_MODE_VR:
  18715. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18716. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18717. break;
  18718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18719. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18720. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18721. break;
  18722. }
  18723. _super.prototype._updateRigCameras.call(this);
  18724. };
  18725. ArcRotateCamera.prototype.dispose = function () {
  18726. this.inputs.clear();
  18727. _super.prototype.dispose.call(this);
  18728. };
  18729. ArcRotateCamera.prototype.getClassName = function () {
  18730. return "ArcRotateCamera";
  18731. };
  18732. return ArcRotateCamera;
  18733. }(BABYLON.TargetCamera));
  18734. __decorate([
  18735. BABYLON.serialize()
  18736. ], ArcRotateCamera.prototype, "alpha", void 0);
  18737. __decorate([
  18738. BABYLON.serialize()
  18739. ], ArcRotateCamera.prototype, "beta", void 0);
  18740. __decorate([
  18741. BABYLON.serialize()
  18742. ], ArcRotateCamera.prototype, "radius", void 0);
  18743. __decorate([
  18744. BABYLON.serializeAsVector3()
  18745. ], ArcRotateCamera.prototype, "target", void 0);
  18746. __decorate([
  18747. BABYLON.serialize()
  18748. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18749. __decorate([
  18750. BABYLON.serialize()
  18751. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18752. __decorate([
  18753. BABYLON.serialize()
  18754. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18755. __decorate([
  18756. BABYLON.serialize()
  18757. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18758. __decorate([
  18759. BABYLON.serialize()
  18760. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18761. __decorate([
  18762. BABYLON.serialize()
  18763. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18764. __decorate([
  18765. BABYLON.serialize()
  18766. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18767. __decorate([
  18768. BABYLON.serialize()
  18769. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18770. __decorate([
  18771. BABYLON.serialize()
  18772. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18773. __decorate([
  18774. BABYLON.serialize()
  18775. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18776. __decorate([
  18777. BABYLON.serialize()
  18778. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18779. __decorate([
  18780. BABYLON.serialize()
  18781. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18782. __decorate([
  18783. BABYLON.serialize()
  18784. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18785. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18786. })(BABYLON || (BABYLON = {}));
  18787. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18788. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18789. var BABYLON;
  18790. (function (BABYLON) {
  18791. var ArcRotateCameraInputsManager = (function (_super) {
  18792. __extends(ArcRotateCameraInputsManager, _super);
  18793. function ArcRotateCameraInputsManager(camera) {
  18794. return _super.call(this, camera) || this;
  18795. }
  18796. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18797. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18798. return this;
  18799. };
  18800. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18801. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18802. return this;
  18803. };
  18804. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18805. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18806. return this;
  18807. };
  18808. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18809. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18810. return this;
  18811. };
  18812. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18813. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18814. return this;
  18815. };
  18816. return ArcRotateCameraInputsManager;
  18817. }(BABYLON.CameraInputsManager));
  18818. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18819. })(BABYLON || (BABYLON = {}));
  18820. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18821. var BABYLON;
  18822. (function (BABYLON) {
  18823. var RenderingManager = (function () {
  18824. function RenderingManager(scene) {
  18825. this._renderingGroups = new Array();
  18826. this._autoClearDepthStencil = {};
  18827. this._customOpaqueSortCompareFn = {};
  18828. this._customAlphaTestSortCompareFn = {};
  18829. this._customTransparentSortCompareFn = {};
  18830. this._renderinGroupInfo = null;
  18831. this._scene = scene;
  18832. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18833. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18834. }
  18835. }
  18836. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18837. if (depth === void 0) { depth = true; }
  18838. if (stencil === void 0) { stencil = true; }
  18839. if (this._depthStencilBufferAlreadyCleaned) {
  18840. return;
  18841. }
  18842. this._scene.getEngine().clear(null, false, depth, stencil);
  18843. this._depthStencilBufferAlreadyCleaned = true;
  18844. };
  18845. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18846. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18847. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18848. var info = null;
  18849. if (observable) {
  18850. if (!this._renderinGroupInfo) {
  18851. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18852. }
  18853. info = this._renderinGroupInfo;
  18854. info.scene = this._scene;
  18855. info.camera = this._scene.activeCamera;
  18856. }
  18857. // Dispatch sprites
  18858. if (renderSprites) {
  18859. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18860. var manager = this._scene.spriteManagers[index];
  18861. this.dispatchSprites(manager);
  18862. }
  18863. }
  18864. // Render
  18865. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18866. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18867. var renderingGroup = this._renderingGroups[index];
  18868. if (!renderingGroup && !observable)
  18869. continue;
  18870. this._currentIndex = index;
  18871. var renderingGroupMask = 0;
  18872. // Fire PRECLEAR stage
  18873. if (observable) {
  18874. renderingGroupMask = Math.pow(2, index);
  18875. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18876. info.renderingGroupId = index;
  18877. observable.notifyObservers(info, renderingGroupMask);
  18878. }
  18879. // Clear depth/stencil if needed
  18880. var autoClear = this._autoClearDepthStencil[index];
  18881. if (autoClear && autoClear.autoClear) {
  18882. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18883. }
  18884. if (observable) {
  18885. // Fire PREOPAQUE stage
  18886. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18887. observable.notifyObservers(info, renderingGroupMask);
  18888. // Fire PRETRANSPARENT stage
  18889. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18890. observable.notifyObservers(info, renderingGroupMask);
  18891. }
  18892. if (renderingGroup)
  18893. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18894. // Fire POSTTRANSPARENT stage
  18895. if (observable) {
  18896. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18897. observable.notifyObservers(info, renderingGroupMask);
  18898. }
  18899. }
  18900. };
  18901. RenderingManager.prototype.reset = function () {
  18902. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18903. var renderingGroup = this._renderingGroups[index];
  18904. if (renderingGroup) {
  18905. renderingGroup.prepare();
  18906. }
  18907. }
  18908. };
  18909. RenderingManager.prototype.dispose = function () {
  18910. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18911. var renderingGroup = this._renderingGroups[index];
  18912. if (renderingGroup) {
  18913. renderingGroup.dispose();
  18914. }
  18915. }
  18916. this._renderingGroups.length = 0;
  18917. };
  18918. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18919. if (!this._renderingGroups[renderingGroupId]) {
  18920. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18921. }
  18922. };
  18923. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18924. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18925. this._prepareRenderingGroup(renderingGroupId);
  18926. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18927. };
  18928. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18929. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18930. this._prepareRenderingGroup(renderingGroupId);
  18931. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18932. };
  18933. RenderingManager.prototype.dispatch = function (subMesh) {
  18934. var mesh = subMesh.getMesh();
  18935. var renderingGroupId = mesh.renderingGroupId || 0;
  18936. this._prepareRenderingGroup(renderingGroupId);
  18937. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18938. };
  18939. /**
  18940. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18941. * This allowed control for front to back rendering or reversly depending of the special needs.
  18942. *
  18943. * @param renderingGroupId The rendering group id corresponding to its index
  18944. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18945. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18946. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18947. */
  18948. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18949. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18950. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18951. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18952. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18953. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18954. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18955. if (this._renderingGroups[renderingGroupId]) {
  18956. var group = this._renderingGroups[renderingGroupId];
  18957. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18958. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18959. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18960. }
  18961. };
  18962. /**
  18963. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18964. *
  18965. * @param renderingGroupId The rendering group id corresponding to its index
  18966. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18967. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18968. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18969. */
  18970. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18971. if (depth === void 0) { depth = true; }
  18972. if (stencil === void 0) { stencil = true; }
  18973. this._autoClearDepthStencil[renderingGroupId] = {
  18974. autoClear: autoClearDepthStencil,
  18975. depth: depth,
  18976. stencil: stencil
  18977. };
  18978. };
  18979. return RenderingManager;
  18980. }());
  18981. /**
  18982. * The max id used for rendering groups (not included)
  18983. */
  18984. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18985. /**
  18986. * The min id used for rendering groups (included)
  18987. */
  18988. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18989. BABYLON.RenderingManager = RenderingManager;
  18990. })(BABYLON || (BABYLON = {}));
  18991. //# sourceMappingURL=babylon.renderingManager.js.map
  18992. var BABYLON;
  18993. (function (BABYLON) {
  18994. var RenderingGroup = (function () {
  18995. /**
  18996. * Creates a new rendering group.
  18997. * @param index The rendering group index
  18998. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18999. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19000. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19001. */
  19002. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19003. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19004. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19005. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19006. this.index = index;
  19007. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19008. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19009. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19010. this._particleSystems = new BABYLON.SmartArray(256);
  19011. this._spriteManagers = new BABYLON.SmartArray(256);
  19012. this._scene = scene;
  19013. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19014. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19015. this.transparentSortCompareFn = transparentSortCompareFn;
  19016. }
  19017. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19018. /**
  19019. * Set the opaque sort comparison function.
  19020. * If null the sub meshes will be render in the order they were created
  19021. */
  19022. set: function (value) {
  19023. this._opaqueSortCompareFn = value;
  19024. if (value) {
  19025. this._renderOpaque = this.renderOpaqueSorted;
  19026. }
  19027. else {
  19028. this._renderOpaque = RenderingGroup.renderUnsorted;
  19029. }
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19035. /**
  19036. * Set the alpha test sort comparison function.
  19037. * If null the sub meshes will be render in the order they were created
  19038. */
  19039. set: function (value) {
  19040. this._alphaTestSortCompareFn = value;
  19041. if (value) {
  19042. this._renderAlphaTest = this.renderAlphaTestSorted;
  19043. }
  19044. else {
  19045. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19046. }
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19052. /**
  19053. * Set the transparent sort comparison function.
  19054. * If null the sub meshes will be render in the order they were created
  19055. */
  19056. set: function (value) {
  19057. if (value) {
  19058. this._transparentSortCompareFn = value;
  19059. }
  19060. else {
  19061. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19062. }
  19063. this._renderTransparent = this.renderTransparentSorted;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. /**
  19069. * Render all the sub meshes contained in the group.
  19070. * @param customRenderFunction Used to override the default render behaviour of the group.
  19071. * @returns true if rendered some submeshes.
  19072. */
  19073. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19074. if (customRenderFunction) {
  19075. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19076. return;
  19077. }
  19078. var engine = this._scene.getEngine();
  19079. // Opaque
  19080. if (this._opaqueSubMeshes.length !== 0) {
  19081. this._renderOpaque(this._opaqueSubMeshes);
  19082. }
  19083. // Alpha test
  19084. if (this._alphaTestSubMeshes.length !== 0) {
  19085. engine.setAlphaTesting(true);
  19086. this._renderAlphaTest(this._alphaTestSubMeshes);
  19087. engine.setAlphaTesting(false);
  19088. }
  19089. // Sprites
  19090. if (renderSprites) {
  19091. this._renderSprites();
  19092. }
  19093. // Particles
  19094. if (renderParticles) {
  19095. this._renderParticles(activeMeshes);
  19096. }
  19097. if (this.onBeforeTransparentRendering) {
  19098. this.onBeforeTransparentRendering();
  19099. }
  19100. // Transparent
  19101. if (this._transparentSubMeshes.length !== 0) {
  19102. this._renderTransparent(this._transparentSubMeshes);
  19103. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19104. }
  19105. };
  19106. /**
  19107. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19108. * @param subMeshes The submeshes to render
  19109. */
  19110. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19111. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19112. };
  19113. /**
  19114. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19115. * @param subMeshes The submeshes to render
  19116. */
  19117. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19118. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19119. };
  19120. /**
  19121. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19122. * @param subMeshes The submeshes to render
  19123. */
  19124. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19125. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19126. };
  19127. /**
  19128. * Renders the submeshes in a specified order.
  19129. * @param subMeshes The submeshes to sort before render
  19130. * @param sortCompareFn The comparison function use to sort
  19131. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19132. * @param transparent Specifies to activate blending if true
  19133. */
  19134. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19135. var subIndex = 0;
  19136. var subMesh;
  19137. for (; subIndex < subMeshes.length; subIndex++) {
  19138. subMesh = subMeshes.data[subIndex];
  19139. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19140. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19141. }
  19142. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19143. sortedArray.sort(sortCompareFn);
  19144. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19145. subMesh = sortedArray[subIndex];
  19146. subMesh.render(transparent);
  19147. }
  19148. };
  19149. /**
  19150. * Renders the submeshes in the order they were dispatched (no sort applied).
  19151. * @param subMeshes The submeshes to render
  19152. */
  19153. RenderingGroup.renderUnsorted = function (subMeshes) {
  19154. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19155. var submesh = subMeshes.data[subIndex];
  19156. submesh.render(false);
  19157. }
  19158. };
  19159. /**
  19160. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19161. * are rendered back to front if in the same alpha index.
  19162. *
  19163. * @param a The first submesh
  19164. * @param b The second submesh
  19165. * @returns The result of the comparison
  19166. */
  19167. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19168. // Alpha index first
  19169. if (a._alphaIndex > b._alphaIndex) {
  19170. return 1;
  19171. }
  19172. if (a._alphaIndex < b._alphaIndex) {
  19173. return -1;
  19174. }
  19175. // Then distance to camera
  19176. return RenderingGroup.backToFrontSortCompare(a, b);
  19177. };
  19178. /**
  19179. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19180. * are rendered back to front.
  19181. *
  19182. * @param a The first submesh
  19183. * @param b The second submesh
  19184. * @returns The result of the comparison
  19185. */
  19186. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19187. // Then distance to camera
  19188. if (a._distanceToCamera < b._distanceToCamera) {
  19189. return 1;
  19190. }
  19191. if (a._distanceToCamera > b._distanceToCamera) {
  19192. return -1;
  19193. }
  19194. return 0;
  19195. };
  19196. /**
  19197. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19198. * are rendered front to back (prevent overdraw).
  19199. *
  19200. * @param a The first submesh
  19201. * @param b The second submesh
  19202. * @returns The result of the comparison
  19203. */
  19204. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19205. // Then distance to camera
  19206. if (a._distanceToCamera < b._distanceToCamera) {
  19207. return -1;
  19208. }
  19209. if (a._distanceToCamera > b._distanceToCamera) {
  19210. return 1;
  19211. }
  19212. return 0;
  19213. };
  19214. /**
  19215. * Resets the different lists of submeshes to prepare a new frame.
  19216. */
  19217. RenderingGroup.prototype.prepare = function () {
  19218. this._opaqueSubMeshes.reset();
  19219. this._transparentSubMeshes.reset();
  19220. this._alphaTestSubMeshes.reset();
  19221. this._particleSystems.reset();
  19222. this._spriteManagers.reset();
  19223. };
  19224. RenderingGroup.prototype.dispose = function () {
  19225. this._opaqueSubMeshes.dispose();
  19226. this._transparentSubMeshes.dispose();
  19227. this._alphaTestSubMeshes.dispose();
  19228. this._particleSystems.dispose();
  19229. this._spriteManagers.dispose();
  19230. };
  19231. /**
  19232. * Inserts the submesh in its correct queue depending on its material.
  19233. * @param subMesh The submesh to dispatch
  19234. */
  19235. RenderingGroup.prototype.dispatch = function (subMesh) {
  19236. var material = subMesh.getMaterial();
  19237. var mesh = subMesh.getMesh();
  19238. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19239. this._transparentSubMeshes.push(subMesh);
  19240. }
  19241. else if (material.needAlphaTesting()) {
  19242. this._alphaTestSubMeshes.push(subMesh);
  19243. }
  19244. else {
  19245. this._opaqueSubMeshes.push(subMesh); // Opaque
  19246. }
  19247. };
  19248. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19249. this._spriteManagers.push(spriteManager);
  19250. };
  19251. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19252. this._particleSystems.push(particleSystem);
  19253. };
  19254. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19255. if (this._particleSystems.length === 0) {
  19256. return;
  19257. }
  19258. // Particles
  19259. var activeCamera = this._scene.activeCamera;
  19260. this._scene._particlesDuration.beginMonitoring();
  19261. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19262. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19263. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19264. continue;
  19265. }
  19266. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19267. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19268. }
  19269. }
  19270. this._scene._particlesDuration.endMonitoring(false);
  19271. };
  19272. RenderingGroup.prototype._renderSprites = function () {
  19273. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19274. return;
  19275. }
  19276. // Sprites
  19277. var activeCamera = this._scene.activeCamera;
  19278. this._scene._spritesDuration.beginMonitoring();
  19279. for (var id = 0; id < this._spriteManagers.length; id++) {
  19280. var spriteManager = this._spriteManagers.data[id];
  19281. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19282. spriteManager.render();
  19283. }
  19284. }
  19285. this._scene._spritesDuration.endMonitoring(false);
  19286. };
  19287. return RenderingGroup;
  19288. }());
  19289. BABYLON.RenderingGroup = RenderingGroup;
  19290. })(BABYLON || (BABYLON = {}));
  19291. //# sourceMappingURL=babylon.renderingGroup.js.map
  19292. var BABYLON;
  19293. (function (BABYLON) {
  19294. var ClickInfo = (function () {
  19295. function ClickInfo() {
  19296. this._singleClick = false;
  19297. this._doubleClick = false;
  19298. this._hasSwiped = false;
  19299. this._ignore = false;
  19300. }
  19301. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19302. get: function () {
  19303. return this._singleClick;
  19304. },
  19305. set: function (b) {
  19306. this._singleClick = b;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19312. get: function () {
  19313. return this._doubleClick;
  19314. },
  19315. set: function (b) {
  19316. this._doubleClick = b;
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19322. get: function () {
  19323. return this._hasSwiped;
  19324. },
  19325. set: function (b) {
  19326. this._hasSwiped = b;
  19327. },
  19328. enumerable: true,
  19329. configurable: true
  19330. });
  19331. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19332. get: function () {
  19333. return this._ignore;
  19334. },
  19335. set: function (b) {
  19336. this._ignore = b;
  19337. },
  19338. enumerable: true,
  19339. configurable: true
  19340. });
  19341. return ClickInfo;
  19342. }());
  19343. var PointerEventTypes = (function () {
  19344. function PointerEventTypes() {
  19345. }
  19346. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19347. get: function () {
  19348. return PointerEventTypes._POINTERDOWN;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19354. get: function () {
  19355. return PointerEventTypes._POINTERUP;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19361. get: function () {
  19362. return PointerEventTypes._POINTERMOVE;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19368. get: function () {
  19369. return PointerEventTypes._POINTERWHEEL;
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19375. get: function () {
  19376. return PointerEventTypes._POINTERPICK;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19382. get: function () {
  19383. return PointerEventTypes._POINTERTAP;
  19384. },
  19385. enumerable: true,
  19386. configurable: true
  19387. });
  19388. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19389. get: function () {
  19390. return PointerEventTypes._POINTERDOUBLETAP;
  19391. },
  19392. enumerable: true,
  19393. configurable: true
  19394. });
  19395. return PointerEventTypes;
  19396. }());
  19397. PointerEventTypes._POINTERDOWN = 0x01;
  19398. PointerEventTypes._POINTERUP = 0x02;
  19399. PointerEventTypes._POINTERMOVE = 0x04;
  19400. PointerEventTypes._POINTERWHEEL = 0x08;
  19401. PointerEventTypes._POINTERPICK = 0x10;
  19402. PointerEventTypes._POINTERTAP = 0x20;
  19403. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19404. BABYLON.PointerEventTypes = PointerEventTypes;
  19405. var PointerInfoBase = (function () {
  19406. function PointerInfoBase(type, event) {
  19407. this.type = type;
  19408. this.event = event;
  19409. }
  19410. return PointerInfoBase;
  19411. }());
  19412. BABYLON.PointerInfoBase = PointerInfoBase;
  19413. /**
  19414. * This class is used to store pointer related info for the onPrePointerObservable event.
  19415. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19416. */
  19417. var PointerInfoPre = (function (_super) {
  19418. __extends(PointerInfoPre, _super);
  19419. function PointerInfoPre(type, event, localX, localY) {
  19420. var _this = _super.call(this, type, event) || this;
  19421. _this.skipOnPointerObservable = false;
  19422. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19423. return _this;
  19424. }
  19425. return PointerInfoPre;
  19426. }(PointerInfoBase));
  19427. BABYLON.PointerInfoPre = PointerInfoPre;
  19428. /**
  19429. * This type contains all the data related to a pointer event in Babylon.js.
  19430. * 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.
  19431. */
  19432. var PointerInfo = (function (_super) {
  19433. __extends(PointerInfo, _super);
  19434. function PointerInfo(type, event, pickInfo) {
  19435. var _this = _super.call(this, type, event) || this;
  19436. _this.pickInfo = pickInfo;
  19437. return _this;
  19438. }
  19439. return PointerInfo;
  19440. }(PointerInfoBase));
  19441. BABYLON.PointerInfo = PointerInfo;
  19442. /**
  19443. * This class is used by the onRenderingGroupObservable
  19444. */
  19445. var RenderingGroupInfo = (function () {
  19446. function RenderingGroupInfo() {
  19447. }
  19448. return RenderingGroupInfo;
  19449. }());
  19450. /**
  19451. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19452. * This stage will be fired no matter what
  19453. */
  19454. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19455. /**
  19456. * Called before opaque object are rendered.
  19457. * This stage will be fired only if there's 3D Opaque content to render
  19458. */
  19459. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19460. /**
  19461. * Called after the opaque objects are rendered and before the transparent ones
  19462. * This stage will be fired only if there's 3D transparent content to render
  19463. */
  19464. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19465. /**
  19466. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19467. * This stage will be fired no matter what
  19468. */
  19469. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19470. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19471. /**
  19472. * Represents a scene to be rendered by the engine.
  19473. * @see http://doc.babylonjs.com/page.php?p=21911
  19474. */
  19475. var Scene = (function () {
  19476. /**
  19477. * @constructor
  19478. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19479. */
  19480. function Scene(engine) {
  19481. // Members
  19482. this.autoClear = true;
  19483. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19484. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19485. this.forceWireframe = false;
  19486. this.forcePointsCloud = false;
  19487. this.forceShowBoundingBoxes = false;
  19488. this.animationsEnabled = true;
  19489. this.constantlyUpdateMeshUnderPointer = false;
  19490. this.useRightHandedSystem = false;
  19491. this.hoverCursor = "pointer";
  19492. // Metadata
  19493. this.metadata = null;
  19494. // Events
  19495. /**
  19496. * An event triggered when the scene is disposed.
  19497. * @type {BABYLON.Observable}
  19498. */
  19499. this.onDisposeObservable = new BABYLON.Observable();
  19500. /**
  19501. * An event triggered before rendering the scene
  19502. * @type {BABYLON.Observable}
  19503. */
  19504. this.onBeforeRenderObservable = new BABYLON.Observable();
  19505. /**
  19506. * An event triggered after rendering the scene
  19507. * @type {BABYLON.Observable}
  19508. */
  19509. this.onAfterRenderObservable = new BABYLON.Observable();
  19510. /**
  19511. * An event triggered when the scene is ready
  19512. * @type {BABYLON.Observable}
  19513. */
  19514. this.onReadyObservable = new BABYLON.Observable();
  19515. /**
  19516. * An event triggered before rendering a camera
  19517. * @type {BABYLON.Observable}
  19518. */
  19519. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19520. /**
  19521. * An event triggered after rendering a camera
  19522. * @type {BABYLON.Observable}
  19523. */
  19524. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19525. /**
  19526. * An event triggered when a camera is created
  19527. * @type {BABYLON.Observable}
  19528. */
  19529. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19530. /**
  19531. * An event triggered when a camera is removed
  19532. * @type {BABYLON.Observable}
  19533. */
  19534. this.onCameraRemovedObservable = new BABYLON.Observable();
  19535. /**
  19536. * An event triggered when a light is created
  19537. * @type {BABYLON.Observable}
  19538. */
  19539. this.onNewLightAddedObservable = new BABYLON.Observable();
  19540. /**
  19541. * An event triggered when a light is removed
  19542. * @type {BABYLON.Observable}
  19543. */
  19544. this.onLightRemovedObservable = new BABYLON.Observable();
  19545. /**
  19546. * An event triggered when a geometry is created
  19547. * @type {BABYLON.Observable}
  19548. */
  19549. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19550. /**
  19551. * An event triggered when a geometry is removed
  19552. * @type {BABYLON.Observable}
  19553. */
  19554. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19555. /**
  19556. * An event triggered when a mesh is created
  19557. * @type {BABYLON.Observable}
  19558. */
  19559. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19560. /**
  19561. * An event triggered when a mesh is removed
  19562. * @type {BABYLON.Observable}
  19563. */
  19564. this.onMeshRemovedObservable = new BABYLON.Observable();
  19565. /**
  19566. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19567. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19568. * 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)
  19569. */
  19570. this.onRenderingGroupObservable = new BABYLON.Observable();
  19571. // Animations
  19572. this.animations = [];
  19573. /**
  19574. * 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).
  19575. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19576. */
  19577. this.onPrePointerObservable = new BABYLON.Observable();
  19578. /**
  19579. * Observable event triggered each time an input event is received from the rendering canvas
  19580. */
  19581. this.onPointerObservable = new BABYLON.Observable();
  19582. this._meshPickProceed = false;
  19583. this._previousHasSwiped = false;
  19584. this._currentPickResult = null;
  19585. this._previousPickResult = null;
  19586. this._isButtonPressed = false;
  19587. this._doubleClickOccured = false;
  19588. 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
  19589. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19590. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19591. this._startingPointerTime = 0;
  19592. this._previousStartingPointerTime = 0;
  19593. // Fog
  19594. /**
  19595. * is fog enabled on this scene.
  19596. * @type {boolean}
  19597. */
  19598. this.fogEnabled = true;
  19599. this.fogMode = Scene.FOGMODE_NONE;
  19600. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19601. this.fogDensity = 0.1;
  19602. this.fogStart = 0;
  19603. this.fogEnd = 1000.0;
  19604. // Lights
  19605. /**
  19606. * is shadow enabled on this scene.
  19607. * @type {boolean}
  19608. */
  19609. this.shadowsEnabled = true;
  19610. /**
  19611. * is light enabled on this scene.
  19612. * @type {boolean}
  19613. */
  19614. this.lightsEnabled = true;
  19615. /**
  19616. * All of the lights added to this scene.
  19617. * @see BABYLON.Light
  19618. * @type {BABYLON.Light[]}
  19619. */
  19620. this.lights = new Array();
  19621. // Cameras
  19622. /**
  19623. * All of the cameras added to this scene.
  19624. * @see BABYLON.Camera
  19625. * @type {BABYLON.Camera[]}
  19626. */
  19627. this.cameras = new Array();
  19628. this.activeCameras = new Array();
  19629. // Meshes
  19630. /**
  19631. * All of the (abstract) meshes added to this scene.
  19632. * @see BABYLON.AbstractMesh
  19633. * @type {BABYLON.AbstractMesh[]}
  19634. */
  19635. this.meshes = new Array();
  19636. // Geometries
  19637. this._geometries = new Array();
  19638. this.materials = new Array();
  19639. this.multiMaterials = new Array();
  19640. // Textures
  19641. this.texturesEnabled = true;
  19642. this.textures = new Array();
  19643. // Particles
  19644. this.particlesEnabled = true;
  19645. this.particleSystems = new Array();
  19646. // Sprites
  19647. this.spritesEnabled = true;
  19648. this.spriteManagers = new Array();
  19649. // Layers
  19650. this.layers = new Array();
  19651. this.highlightLayers = new Array();
  19652. // Skeletons
  19653. this.skeletonsEnabled = true;
  19654. this.skeletons = new Array();
  19655. // Lens flares
  19656. this.lensFlaresEnabled = true;
  19657. this.lensFlareSystems = new Array();
  19658. // Collisions
  19659. this.collisionsEnabled = true;
  19660. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19661. // Postprocesses
  19662. this.postProcessesEnabled = true;
  19663. // Customs render targets
  19664. this.renderTargetsEnabled = true;
  19665. this.dumpNextRenderTargets = false;
  19666. this.customRenderTargets = new Array();
  19667. // Imported meshes
  19668. this.importedMeshesFiles = new Array();
  19669. // Probes
  19670. this.probesEnabled = true;
  19671. this.reflectionProbes = new Array();
  19672. this._actionManagers = new Array();
  19673. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19674. // Procedural textures
  19675. this.proceduralTexturesEnabled = true;
  19676. this._proceduralTextures = new Array();
  19677. this.soundTracks = new Array();
  19678. this._audioEnabled = true;
  19679. this._headphone = false;
  19680. // Performance counters
  19681. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19682. this._totalLightsCounter = new BABYLON.PerfCounter();
  19683. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19684. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19685. this._totalVertices = new BABYLON.PerfCounter();
  19686. this._activeIndices = new BABYLON.PerfCounter();
  19687. this._activeParticles = new BABYLON.PerfCounter();
  19688. this._lastFrameDuration = new BABYLON.PerfCounter();
  19689. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19690. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19691. this._particlesDuration = new BABYLON.PerfCounter();
  19692. this._renderDuration = new BABYLON.PerfCounter();
  19693. this._spritesDuration = new BABYLON.PerfCounter();
  19694. this._activeBones = new BABYLON.PerfCounter();
  19695. this._animationTime = 0;
  19696. this.animationTimeScale = 1;
  19697. this._renderId = 0;
  19698. this._executeWhenReadyTimeoutId = -1;
  19699. this._intermediateRendering = false;
  19700. this._toBeDisposed = new BABYLON.SmartArray(256);
  19701. this._pendingData = []; //ANY
  19702. this._activeMeshes = new BABYLON.SmartArray(256);
  19703. this._processedMaterials = new BABYLON.SmartArray(256);
  19704. this._renderTargets = new BABYLON.SmartArray(256);
  19705. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19706. this._activeSkeletons = new BABYLON.SmartArray(32);
  19707. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19708. this._activeAnimatables = new Array();
  19709. this._transformMatrix = BABYLON.Matrix.Zero();
  19710. this._edgesRenderers = new BABYLON.SmartArray(16);
  19711. this._uniqueIdCounter = 0;
  19712. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19713. this._engine.scenes.push(this);
  19714. this._externalData = new BABYLON.StringDictionary();
  19715. this._uid = null;
  19716. this._renderingManager = new BABYLON.RenderingManager(this);
  19717. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19718. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19719. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19720. if (BABYLON.OutlineRenderer) {
  19721. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19722. }
  19723. this.attachControl();
  19724. if (BABYLON.SoundTrack) {
  19725. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19726. }
  19727. //simplification queue
  19728. if (BABYLON.SimplificationQueue) {
  19729. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19730. }
  19731. //collision coordinator initialization. For now legacy per default.
  19732. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19733. }
  19734. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19735. get: function () {
  19736. return Scene._FOGMODE_NONE;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19742. get: function () {
  19743. return Scene._FOGMODE_EXP;
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19749. get: function () {
  19750. return Scene._FOGMODE_EXP2;
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19756. get: function () {
  19757. return Scene._FOGMODE_LINEAR;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(Scene.prototype, "onDispose", {
  19763. set: function (callback) {
  19764. if (this._onDisposeObserver) {
  19765. this.onDisposeObservable.remove(this._onDisposeObserver);
  19766. }
  19767. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Scene.prototype, "beforeRender", {
  19773. set: function (callback) {
  19774. if (this._onBeforeRenderObserver) {
  19775. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19776. }
  19777. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(Scene.prototype, "afterRender", {
  19783. set: function (callback) {
  19784. if (this._onAfterRenderObserver) {
  19785. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19786. }
  19787. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19793. set: function (callback) {
  19794. if (this._onBeforeCameraRenderObserver) {
  19795. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19796. }
  19797. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19803. set: function (callback) {
  19804. if (this._onAfterCameraRenderObserver) {
  19805. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19806. }
  19807. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19813. get: function () {
  19814. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19820. get: function () {
  19821. if (!this._defaultMaterial) {
  19822. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19823. }
  19824. return this._defaultMaterial;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19830. get: function () {
  19831. return this._frustumPlanes;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(Scene.prototype, "debugLayer", {
  19837. // Properties
  19838. get: function () {
  19839. if (!this._debugLayer) {
  19840. this._debugLayer = new BABYLON.DebugLayer(this);
  19841. }
  19842. return this._debugLayer;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19848. get: function () {
  19849. return this._workerCollisions;
  19850. },
  19851. set: function (enabled) {
  19852. enabled = (enabled && !!Worker);
  19853. this._workerCollisions = enabled;
  19854. if (this.collisionCoordinator) {
  19855. this.collisionCoordinator.destroy();
  19856. }
  19857. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19858. this.collisionCoordinator.init(this);
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19864. get: function () {
  19865. return this._selectionOctree;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19871. /**
  19872. * The mesh that is currently under the pointer.
  19873. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19874. */
  19875. get: function () {
  19876. return this._pointerOverMesh;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Scene.prototype, "pointerX", {
  19882. /**
  19883. * Current on-screen X position of the pointer
  19884. * @return {number} X position of the pointer
  19885. */
  19886. get: function () {
  19887. return this._pointerX;
  19888. },
  19889. enumerable: true,
  19890. configurable: true
  19891. });
  19892. Object.defineProperty(Scene.prototype, "pointerY", {
  19893. /**
  19894. * Current on-screen Y position of the pointer
  19895. * @return {number} Y position of the pointer
  19896. */
  19897. get: function () {
  19898. return this._pointerY;
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Scene.prototype.getCachedMaterial = function () {
  19904. return this._cachedMaterial;
  19905. };
  19906. Scene.prototype.getBoundingBoxRenderer = function () {
  19907. return this._boundingBoxRenderer;
  19908. };
  19909. Scene.prototype.getOutlineRenderer = function () {
  19910. return this._outlineRenderer;
  19911. };
  19912. Scene.prototype.getEngine = function () {
  19913. return this._engine;
  19914. };
  19915. Scene.prototype.getTotalVertices = function () {
  19916. return this._totalVertices.current;
  19917. };
  19918. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19919. get: function () {
  19920. return this._totalVertices;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Scene.prototype.getActiveIndices = function () {
  19926. return this._activeIndices.current;
  19927. };
  19928. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19929. get: function () {
  19930. return this._activeIndices;
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. Scene.prototype.getActiveParticles = function () {
  19936. return this._activeParticles.current;
  19937. };
  19938. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19939. get: function () {
  19940. return this._activeParticles;
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Scene.prototype.getActiveBones = function () {
  19946. return this._activeBones.current;
  19947. };
  19948. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19949. get: function () {
  19950. return this._activeBones;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. // Stats
  19956. Scene.prototype.getLastFrameDuration = function () {
  19957. return this._lastFrameDuration.current;
  19958. };
  19959. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19960. get: function () {
  19961. return this._lastFrameDuration;
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19967. return this._evaluateActiveMeshesDuration.current;
  19968. };
  19969. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19970. get: function () {
  19971. return this._evaluateActiveMeshesDuration;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Scene.prototype.getActiveMeshes = function () {
  19977. return this._activeMeshes;
  19978. };
  19979. Scene.prototype.getRenderTargetsDuration = function () {
  19980. return this._renderTargetsDuration.current;
  19981. };
  19982. Scene.prototype.getRenderDuration = function () {
  19983. return this._renderDuration.current;
  19984. };
  19985. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19986. get: function () {
  19987. return this._renderDuration;
  19988. },
  19989. enumerable: true,
  19990. configurable: true
  19991. });
  19992. Scene.prototype.getParticlesDuration = function () {
  19993. return this._particlesDuration.current;
  19994. };
  19995. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19996. get: function () {
  19997. return this._particlesDuration;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Scene.prototype.getSpritesDuration = function () {
  20003. return this._spritesDuration.current;
  20004. };
  20005. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20006. get: function () {
  20007. return this._spritesDuration;
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Scene.prototype.getAnimationRatio = function () {
  20013. return this._animationRatio;
  20014. };
  20015. Scene.prototype.getRenderId = function () {
  20016. return this._renderId;
  20017. };
  20018. Scene.prototype.incrementRenderId = function () {
  20019. this._renderId++;
  20020. };
  20021. Scene.prototype._updatePointerPosition = function (evt) {
  20022. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20023. this._pointerX = evt.clientX - canvasRect.left;
  20024. this._pointerY = evt.clientY - canvasRect.top;
  20025. this._unTranslatedPointerX = this._pointerX;
  20026. this._unTranslatedPointerY = this._pointerY;
  20027. if (this.cameraToUseForPointers) {
  20028. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  20029. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  20030. }
  20031. };
  20032. // Pointers handling
  20033. /**
  20034. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20035. * @param attachUp defines if you want to attach events to pointerup
  20036. * @param attachDown defines if you want to attach events to pointerdown
  20037. * @param attachMove defines if you want to attach events to pointermove
  20038. */
  20039. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20040. var _this = this;
  20041. if (attachUp === void 0) { attachUp = true; }
  20042. if (attachDown === void 0) { attachDown = true; }
  20043. if (attachMove === void 0) { attachMove = true; }
  20044. this._initActionManager = function (act, clickInfo) {
  20045. if (!_this._meshPickProceed) {
  20046. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20047. _this._currentPickResult = pickResult;
  20048. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20049. _this._meshPickProceed = true;
  20050. }
  20051. return act;
  20052. };
  20053. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20054. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20055. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20056. btn !== _this._previousButtonPressed) {
  20057. _this._doubleClickOccured = false;
  20058. clickInfo.singleClick = true;
  20059. clickInfo.ignore = false;
  20060. cb(clickInfo, _this._currentPickResult);
  20061. }
  20062. };
  20063. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20064. var clickInfo = new ClickInfo();
  20065. _this._currentPickResult = null;
  20066. var act;
  20067. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20068. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20069. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20070. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20071. act = _this._initActionManager(act, clickInfo);
  20072. if (act)
  20073. checkPicking = act.hasPickTriggers;
  20074. }
  20075. if (checkPicking) {
  20076. var btn = evt.button;
  20077. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20078. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20079. if (!clickInfo.hasSwiped) {
  20080. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20081. if (!checkSingleClickImmediately) {
  20082. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20083. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20084. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20085. act = _this._initActionManager(act, clickInfo);
  20086. if (act)
  20087. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20088. }
  20089. }
  20090. if (checkSingleClickImmediately) {
  20091. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20092. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20093. btn !== _this._previousButtonPressed) {
  20094. clickInfo.singleClick = true;
  20095. cb(clickInfo, _this._currentPickResult);
  20096. }
  20097. }
  20098. else {
  20099. // wait that no double click has been raised during the double click delay
  20100. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20101. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20102. }
  20103. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20104. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20105. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20106. act = _this._initActionManager(act, clickInfo);
  20107. if (act)
  20108. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20109. }
  20110. if (checkDoubleClick) {
  20111. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20112. if (btn === _this._previousButtonPressed &&
  20113. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20114. !_this._doubleClickOccured) {
  20115. // pointer has not moved for 2 clicks, it's a double click
  20116. if (!clickInfo.hasSwiped &&
  20117. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20118. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20119. _this._previousStartingPointerTime = 0;
  20120. _this._doubleClickOccured = true;
  20121. clickInfo.doubleClick = true;
  20122. clickInfo.ignore = false;
  20123. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20124. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20125. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20126. cb(clickInfo, _this._currentPickResult);
  20127. }
  20128. else {
  20129. _this._doubleClickOccured = false;
  20130. _this._previousStartingPointerTime = _this._startingPointerTime;
  20131. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20132. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20133. _this._previousButtonPressed = btn;
  20134. _this._previousHasSwiped = clickInfo.hasSwiped;
  20135. if (Scene.ExclusiveDoubleClickMode) {
  20136. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20137. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20138. }
  20139. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20140. cb(clickInfo, _this._previousPickResult);
  20141. }
  20142. else {
  20143. cb(clickInfo, _this._currentPickResult);
  20144. }
  20145. }
  20146. }
  20147. else {
  20148. _this._doubleClickOccured = false;
  20149. _this._previousStartingPointerTime = _this._startingPointerTime;
  20150. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20151. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20152. _this._previousButtonPressed = btn;
  20153. _this._previousHasSwiped = clickInfo.hasSwiped;
  20154. }
  20155. }
  20156. }
  20157. }
  20158. clickInfo.ignore = true;
  20159. cb(clickInfo, _this._currentPickResult);
  20160. };
  20161. var spritePredicate = function (sprite) {
  20162. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20163. };
  20164. this._onPointerMove = function (evt) {
  20165. _this._updatePointerPosition(evt);
  20166. // PreObservable support
  20167. if (_this.onPrePointerObservable.hasObservers()) {
  20168. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20169. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20170. _this.onPrePointerObservable.notifyObservers(pi, type);
  20171. if (pi.skipOnPointerObservable) {
  20172. return;
  20173. }
  20174. }
  20175. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20176. return;
  20177. }
  20178. var canvas = _this._engine.getRenderingCanvas();
  20179. if (!_this.pointerMovePredicate) {
  20180. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20181. }
  20182. // Meshes
  20183. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20184. if (pickResult.hit && pickResult.pickedMesh) {
  20185. _this.setPointerOverSprite(null);
  20186. _this.setPointerOverMesh(pickResult.pickedMesh);
  20187. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20188. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20189. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20190. }
  20191. else {
  20192. canvas.style.cursor = _this.hoverCursor;
  20193. }
  20194. }
  20195. else {
  20196. canvas.style.cursor = "";
  20197. }
  20198. }
  20199. else {
  20200. _this.setPointerOverMesh(null);
  20201. // Sprites
  20202. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20203. if (pickResult.hit && pickResult.pickedSprite) {
  20204. _this.setPointerOverSprite(pickResult.pickedSprite);
  20205. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20206. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20207. }
  20208. else {
  20209. canvas.style.cursor = _this.hoverCursor;
  20210. }
  20211. }
  20212. else {
  20213. _this.setPointerOverSprite(null);
  20214. // Restore pointer
  20215. canvas.style.cursor = "";
  20216. }
  20217. }
  20218. if (_this.onPointerMove) {
  20219. _this.onPointerMove(evt, pickResult);
  20220. }
  20221. if (_this.onPointerObservable.hasObservers()) {
  20222. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20223. var pi = new PointerInfo(type, evt, pickResult);
  20224. _this.onPointerObservable.notifyObservers(pi, type);
  20225. }
  20226. };
  20227. this._onPointerDown = function (evt) {
  20228. _this._isButtonPressed = true;
  20229. _this._pickedDownMesh = null;
  20230. _this._meshPickProceed = false;
  20231. _this._updatePointerPosition(evt);
  20232. // PreObservable support
  20233. if (_this.onPrePointerObservable.hasObservers()) {
  20234. var type = PointerEventTypes.POINTERDOWN;
  20235. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20236. _this.onPrePointerObservable.notifyObservers(pi, type);
  20237. if (pi.skipOnPointerObservable) {
  20238. return;
  20239. }
  20240. }
  20241. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20242. return;
  20243. }
  20244. _this._startingPointerPosition.x = _this._pointerX;
  20245. _this._startingPointerPosition.y = _this._pointerY;
  20246. _this._startingPointerTime = new Date().getTime();
  20247. if (!_this.pointerDownPredicate) {
  20248. _this.pointerDownPredicate = function (mesh) {
  20249. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20250. };
  20251. }
  20252. // Meshes
  20253. _this._pickedDownMesh = null;
  20254. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20255. if (pickResult.hit && pickResult.pickedMesh) {
  20256. _this._pickedDownMesh = pickResult.pickedMesh;
  20257. var actionManager = pickResult.pickedMesh.actionManager;
  20258. if (actionManager) {
  20259. if (actionManager.hasPickTriggers) {
  20260. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20261. switch (evt.button) {
  20262. case 0:
  20263. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20264. break;
  20265. case 1:
  20266. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20267. break;
  20268. case 2:
  20269. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20270. break;
  20271. }
  20272. }
  20273. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20274. window.setTimeout((function () {
  20275. var _this = this;
  20276. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  20277. if (pickResult.hit && pickResult.pickedMesh) {
  20278. if (this._isButtonPressed &&
  20279. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20280. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20281. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20282. this._startingPointerTime = 0;
  20283. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20284. }
  20285. }
  20286. }).bind(_this), Scene.LongPressDelay);
  20287. }
  20288. }
  20289. }
  20290. if (_this.onPointerDown) {
  20291. _this.onPointerDown(evt, pickResult);
  20292. }
  20293. if (_this.onPointerObservable.hasObservers()) {
  20294. var type = PointerEventTypes.POINTERDOWN;
  20295. var pi = new PointerInfo(type, evt, pickResult);
  20296. _this.onPointerObservable.notifyObservers(pi, type);
  20297. }
  20298. // Sprites
  20299. _this._pickedDownSprite = null;
  20300. if (_this.spriteManagers.length > 0) {
  20301. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20302. if (pickResult.hit && pickResult.pickedSprite) {
  20303. if (pickResult.pickedSprite.actionManager) {
  20304. _this._pickedDownSprite = pickResult.pickedSprite;
  20305. switch (evt.button) {
  20306. case 0:
  20307. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20308. break;
  20309. case 1:
  20310. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20311. break;
  20312. case 2:
  20313. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20314. break;
  20315. }
  20316. if (pickResult.pickedSprite.actionManager) {
  20317. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20318. }
  20319. }
  20320. }
  20321. }
  20322. };
  20323. this._onPointerUp = function (evt) {
  20324. _this._isButtonPressed = false;
  20325. _this._pickedUpMesh = null;
  20326. _this._meshPickProceed = false;
  20327. _this._updatePointerPosition(evt);
  20328. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20329. // PreObservable support
  20330. if (this.onPrePointerObservable.hasObservers()) {
  20331. if (!clickInfo.ignore) {
  20332. if (!clickInfo.hasSwiped) {
  20333. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20334. var type = PointerEventTypes.POINTERTAP;
  20335. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20336. this.onPrePointerObservable.notifyObservers(pi, type);
  20337. if (pi.skipOnPointerObservable) {
  20338. return;
  20339. }
  20340. }
  20341. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20342. var type = PointerEventTypes.POINTERDOUBLETAP;
  20343. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20344. this.onPrePointerObservable.notifyObservers(pi, type);
  20345. if (pi.skipOnPointerObservable) {
  20346. return;
  20347. }
  20348. }
  20349. }
  20350. }
  20351. else {
  20352. var type = PointerEventTypes.POINTERUP;
  20353. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20354. this.onPrePointerObservable.notifyObservers(pi, type);
  20355. if (pi.skipOnPointerObservable) {
  20356. return;
  20357. }
  20358. }
  20359. }
  20360. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20361. return;
  20362. }
  20363. if (!this.pointerUpPredicate) {
  20364. this.pointerUpPredicate = function (mesh) {
  20365. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20366. };
  20367. }
  20368. // Meshes
  20369. if (!this._meshPickProceed && (BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  20370. this._initActionManager(null, clickInfo);
  20371. }
  20372. if (!pickResult) {
  20373. pickResult = this._currentPickResult;
  20374. }
  20375. if (pickResult && pickResult.pickedMesh) {
  20376. this._pickedUpMesh = pickResult.pickedMesh;
  20377. if (this._pickedDownMesh === this._pickedUpMesh) {
  20378. if (this.onPointerPick) {
  20379. this.onPointerPick(evt, pickResult);
  20380. }
  20381. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20382. var type = PointerEventTypes.POINTERPICK;
  20383. var pi = new PointerInfo(type, evt, pickResult);
  20384. this.onPointerObservable.notifyObservers(pi, type);
  20385. }
  20386. }
  20387. if (pickResult.pickedMesh.actionManager) {
  20388. if (clickInfo.ignore) {
  20389. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20390. }
  20391. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20392. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20393. }
  20394. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20395. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20396. }
  20397. }
  20398. }
  20399. if (this._pickedDownMesh &&
  20400. this._pickedDownMesh.actionManager &&
  20401. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20402. this._pickedDownMesh !== this._pickedUpMesh) {
  20403. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20404. }
  20405. if (this.onPointerUp) {
  20406. this.onPointerUp(evt, pickResult);
  20407. }
  20408. if (this.onPointerObservable.hasObservers()) {
  20409. if (!clickInfo.ignore) {
  20410. if (!clickInfo.hasSwiped) {
  20411. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20412. var type = PointerEventTypes.POINTERTAP;
  20413. var pi = new PointerInfo(type, evt, pickResult);
  20414. this.onPointerObservable.notifyObservers(pi, type);
  20415. }
  20416. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20417. var type = PointerEventTypes.POINTERDOUBLETAP;
  20418. var pi = new PointerInfo(type, evt, pickResult);
  20419. this.onPointerObservable.notifyObservers(pi, type);
  20420. }
  20421. }
  20422. }
  20423. else {
  20424. var type = PointerEventTypes.POINTERUP;
  20425. var pi = new PointerInfo(type, evt, pickResult);
  20426. this.onPointerObservable.notifyObservers(pi, type);
  20427. }
  20428. }
  20429. // Sprites
  20430. if (this.spriteManagers.length > 0) {
  20431. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20432. if (pickResult.hit && pickResult.pickedSprite) {
  20433. if (pickResult.pickedSprite.actionManager) {
  20434. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20435. if (pickResult.pickedSprite.actionManager) {
  20436. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20437. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20438. }
  20439. }
  20440. }
  20441. }
  20442. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20443. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20444. }
  20445. }
  20446. this._previousPickResult = this._currentPickResult;
  20447. }).bind(_this));
  20448. };
  20449. this._onKeyDown = function (evt) {
  20450. if (_this.actionManager) {
  20451. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20452. }
  20453. };
  20454. this._onKeyUp = function (evt) {
  20455. if (_this.actionManager) {
  20456. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20457. }
  20458. };
  20459. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20460. var canvas = this._engine.getRenderingCanvas();
  20461. if (attachMove) {
  20462. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20463. // Wheel
  20464. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20465. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20466. }
  20467. if (attachDown) {
  20468. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20469. }
  20470. if (attachUp) {
  20471. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20472. }
  20473. canvas.tabIndex = 1;
  20474. canvas.addEventListener("keydown", this._onKeyDown, false);
  20475. canvas.addEventListener("keyup", this._onKeyUp, false);
  20476. };
  20477. Scene.prototype.detachControl = function () {
  20478. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20479. var canvas = this._engine.getRenderingCanvas();
  20480. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20481. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20482. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20483. // Wheel
  20484. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20485. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20486. canvas.removeEventListener("keydown", this._onKeyDown);
  20487. canvas.removeEventListener("keyup", this._onKeyUp);
  20488. };
  20489. // Ready
  20490. Scene.prototype.isReady = function () {
  20491. if (this._pendingData.length > 0) {
  20492. return false;
  20493. }
  20494. var index;
  20495. for (index = 0; index < this._geometries.length; index++) {
  20496. var geometry = this._geometries[index];
  20497. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20498. return false;
  20499. }
  20500. }
  20501. for (index = 0; index < this.meshes.length; index++) {
  20502. var mesh = this.meshes[index];
  20503. if (!mesh.isEnabled()) {
  20504. continue;
  20505. }
  20506. if (!mesh.isReady()) {
  20507. return false;
  20508. }
  20509. var mat = mesh.material;
  20510. if (mat) {
  20511. if (!mat.isReady(mesh)) {
  20512. return false;
  20513. }
  20514. }
  20515. }
  20516. return true;
  20517. };
  20518. Scene.prototype.resetCachedMaterial = function () {
  20519. this._cachedMaterial = null;
  20520. };
  20521. Scene.prototype.registerBeforeRender = function (func) {
  20522. this.onBeforeRenderObservable.add(func);
  20523. };
  20524. Scene.prototype.unregisterBeforeRender = function (func) {
  20525. this.onBeforeRenderObservable.removeCallback(func);
  20526. };
  20527. Scene.prototype.registerAfterRender = function (func) {
  20528. this.onAfterRenderObservable.add(func);
  20529. };
  20530. Scene.prototype.unregisterAfterRender = function (func) {
  20531. this.onAfterRenderObservable.removeCallback(func);
  20532. };
  20533. Scene.prototype._addPendingData = function (data) {
  20534. this._pendingData.push(data);
  20535. };
  20536. Scene.prototype._removePendingData = function (data) {
  20537. var index = this._pendingData.indexOf(data);
  20538. if (index !== -1) {
  20539. this._pendingData.splice(index, 1);
  20540. }
  20541. };
  20542. Scene.prototype.getWaitingItemsCount = function () {
  20543. return this._pendingData.length;
  20544. };
  20545. /**
  20546. * Registers a function to be executed when the scene is ready.
  20547. * @param {Function} func - the function to be executed.
  20548. */
  20549. Scene.prototype.executeWhenReady = function (func) {
  20550. var _this = this;
  20551. this.onReadyObservable.add(func);
  20552. if (this._executeWhenReadyTimeoutId !== -1) {
  20553. return;
  20554. }
  20555. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20556. _this._checkIsReady();
  20557. }, 150);
  20558. };
  20559. Scene.prototype._checkIsReady = function () {
  20560. var _this = this;
  20561. if (this.isReady()) {
  20562. this.onReadyObservable.notifyObservers(this);
  20563. this.onReadyObservable.clear();
  20564. this._executeWhenReadyTimeoutId = -1;
  20565. return;
  20566. }
  20567. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20568. _this._checkIsReady();
  20569. }, 150);
  20570. };
  20571. // Animations
  20572. /**
  20573. * Will start the animation sequence of a given target
  20574. * @param target - the target
  20575. * @param {number} from - from which frame should animation start
  20576. * @param {number} to - till which frame should animation run.
  20577. * @param {boolean} [loop] - should the animation loop
  20578. * @param {number} [speedRatio] - the speed in which to run the animation
  20579. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20580. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20581. * @return {BABYLON.Animatable} the animatable object created for this animation
  20582. * @see BABYLON.Animatable
  20583. * @see http://doc.babylonjs.com/page.php?p=22081
  20584. */
  20585. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20586. if (speedRatio === void 0) { speedRatio = 1.0; }
  20587. this.stopAnimation(target);
  20588. if (!animatable) {
  20589. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20590. }
  20591. // Local animations
  20592. if (target.animations) {
  20593. animatable.appendAnimations(target, target.animations);
  20594. }
  20595. // Children animations
  20596. if (target.getAnimatables) {
  20597. var animatables = target.getAnimatables();
  20598. for (var index = 0; index < animatables.length; index++) {
  20599. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20600. }
  20601. }
  20602. animatable.reset();
  20603. return animatable;
  20604. };
  20605. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20606. if (speedRatio === undefined) {
  20607. speedRatio = 1.0;
  20608. }
  20609. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20610. return animatable;
  20611. };
  20612. Scene.prototype.getAnimatableByTarget = function (target) {
  20613. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20614. if (this._activeAnimatables[index].target === target) {
  20615. return this._activeAnimatables[index];
  20616. }
  20617. }
  20618. return null;
  20619. };
  20620. Object.defineProperty(Scene.prototype, "Animatables", {
  20621. get: function () {
  20622. return this._activeAnimatables;
  20623. },
  20624. enumerable: true,
  20625. configurable: true
  20626. });
  20627. /**
  20628. * Will stop the animation of the given target
  20629. * @param target - the target
  20630. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20631. * @see beginAnimation
  20632. */
  20633. Scene.prototype.stopAnimation = function (target, animationName) {
  20634. var animatable = this.getAnimatableByTarget(target);
  20635. if (animatable) {
  20636. animatable.stop(animationName);
  20637. }
  20638. };
  20639. Scene.prototype._animate = function () {
  20640. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20641. return;
  20642. }
  20643. // Getting time
  20644. var now = BABYLON.Tools.Now;
  20645. if (!this._animationTimeLast) {
  20646. if (this._pendingData.length > 0) {
  20647. return;
  20648. }
  20649. this._animationTimeLast = now;
  20650. }
  20651. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20652. this._animationTime += deltaTime;
  20653. this._animationTimeLast = now;
  20654. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20655. this._activeAnimatables[index]._animate(this._animationTime);
  20656. }
  20657. };
  20658. // Matrix
  20659. Scene.prototype.getViewMatrix = function () {
  20660. return this._viewMatrix;
  20661. };
  20662. Scene.prototype.getProjectionMatrix = function () {
  20663. return this._projectionMatrix;
  20664. };
  20665. Scene.prototype.getTransformMatrix = function () {
  20666. return this._transformMatrix;
  20667. };
  20668. Scene.prototype.setTransformMatrix = function (view, projection) {
  20669. this._viewMatrix = view;
  20670. this._projectionMatrix = projection;
  20671. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20672. // Update frustum
  20673. if (!this._frustumPlanes) {
  20674. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20675. }
  20676. else {
  20677. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20678. }
  20679. };
  20680. // Methods
  20681. Scene.prototype.addMesh = function (newMesh) {
  20682. newMesh.uniqueId = this._uniqueIdCounter++;
  20683. var position = this.meshes.push(newMesh);
  20684. //notify the collision coordinator
  20685. this.collisionCoordinator.onMeshAdded(newMesh);
  20686. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20687. };
  20688. Scene.prototype.removeMesh = function (toRemove) {
  20689. var index = this.meshes.indexOf(toRemove);
  20690. if (index !== -1) {
  20691. // Remove from the scene if mesh found
  20692. this.meshes.splice(index, 1);
  20693. }
  20694. //notify the collision coordinator
  20695. this.collisionCoordinator.onMeshRemoved(toRemove);
  20696. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20697. return index;
  20698. };
  20699. Scene.prototype.removeSkeleton = function (toRemove) {
  20700. var index = this.skeletons.indexOf(toRemove);
  20701. if (index !== -1) {
  20702. // Remove from the scene if mesh found
  20703. this.skeletons.splice(index, 1);
  20704. }
  20705. return index;
  20706. };
  20707. Scene.prototype.removeLight = function (toRemove) {
  20708. var index = this.lights.indexOf(toRemove);
  20709. if (index !== -1) {
  20710. // Remove from the scene if mesh found
  20711. this.lights.splice(index, 1);
  20712. }
  20713. this.onLightRemovedObservable.notifyObservers(toRemove);
  20714. return index;
  20715. };
  20716. Scene.prototype.removeCamera = function (toRemove) {
  20717. var index = this.cameras.indexOf(toRemove);
  20718. if (index !== -1) {
  20719. // Remove from the scene if mesh found
  20720. this.cameras.splice(index, 1);
  20721. }
  20722. // Remove from activeCameras
  20723. var index2 = this.activeCameras.indexOf(toRemove);
  20724. if (index2 !== -1) {
  20725. // Remove from the scene if mesh found
  20726. this.activeCameras.splice(index2, 1);
  20727. }
  20728. // Reset the activeCamera
  20729. if (this.activeCamera === toRemove) {
  20730. if (this.cameras.length > 0) {
  20731. this.activeCamera = this.cameras[0];
  20732. }
  20733. else {
  20734. this.activeCamera = null;
  20735. }
  20736. }
  20737. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20738. return index;
  20739. };
  20740. Scene.prototype.addLight = function (newLight) {
  20741. newLight.uniqueId = this._uniqueIdCounter++;
  20742. var position = this.lights.push(newLight);
  20743. this.onNewLightAddedObservable.notifyObservers(newLight);
  20744. };
  20745. Scene.prototype.addCamera = function (newCamera) {
  20746. newCamera.uniqueId = this._uniqueIdCounter++;
  20747. var position = this.cameras.push(newCamera);
  20748. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20749. };
  20750. /**
  20751. * Switch active camera
  20752. * @param {Camera} newCamera - new active camera
  20753. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20754. */
  20755. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20756. if (attachControl === void 0) { attachControl = true; }
  20757. var canvas = this._engine.getRenderingCanvas();
  20758. this.activeCamera.detachControl(canvas);
  20759. this.activeCamera = newCamera;
  20760. if (attachControl) {
  20761. newCamera.attachControl(canvas);
  20762. }
  20763. };
  20764. /**
  20765. * sets the active camera of the scene using its ID
  20766. * @param {string} id - the camera's ID
  20767. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20768. * @see activeCamera
  20769. */
  20770. Scene.prototype.setActiveCameraByID = function (id) {
  20771. var camera = this.getCameraByID(id);
  20772. if (camera) {
  20773. this.activeCamera = camera;
  20774. return camera;
  20775. }
  20776. return null;
  20777. };
  20778. /**
  20779. * sets the active camera of the scene using its name
  20780. * @param {string} name - the camera's name
  20781. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20782. * @see activeCamera
  20783. */
  20784. Scene.prototype.setActiveCameraByName = function (name) {
  20785. var camera = this.getCameraByName(name);
  20786. if (camera) {
  20787. this.activeCamera = camera;
  20788. return camera;
  20789. }
  20790. return null;
  20791. };
  20792. /**
  20793. * get a material using its id
  20794. * @param {string} the material's ID
  20795. * @return {BABYLON.Material|null} the material or null if none found.
  20796. */
  20797. Scene.prototype.getMaterialByID = function (id) {
  20798. for (var index = 0; index < this.materials.length; index++) {
  20799. if (this.materials[index].id === id) {
  20800. return this.materials[index];
  20801. }
  20802. }
  20803. return null;
  20804. };
  20805. /**
  20806. * get a material using its name
  20807. * @param {string} the material's name
  20808. * @return {BABYLON.Material|null} the material or null if none found.
  20809. */
  20810. Scene.prototype.getMaterialByName = function (name) {
  20811. for (var index = 0; index < this.materials.length; index++) {
  20812. if (this.materials[index].name === name) {
  20813. return this.materials[index];
  20814. }
  20815. }
  20816. return null;
  20817. };
  20818. Scene.prototype.getLensFlareSystemByName = function (name) {
  20819. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20820. if (this.lensFlareSystems[index].name === name) {
  20821. return this.lensFlareSystems[index];
  20822. }
  20823. }
  20824. return null;
  20825. };
  20826. Scene.prototype.getLensFlareSystemByID = function (id) {
  20827. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20828. if (this.lensFlareSystems[index].id === id) {
  20829. return this.lensFlareSystems[index];
  20830. }
  20831. }
  20832. return null;
  20833. };
  20834. Scene.prototype.getCameraByID = function (id) {
  20835. for (var index = 0; index < this.cameras.length; index++) {
  20836. if (this.cameras[index].id === id) {
  20837. return this.cameras[index];
  20838. }
  20839. }
  20840. return null;
  20841. };
  20842. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20843. for (var index = 0; index < this.cameras.length; index++) {
  20844. if (this.cameras[index].uniqueId === uniqueId) {
  20845. return this.cameras[index];
  20846. }
  20847. }
  20848. return null;
  20849. };
  20850. /**
  20851. * get a camera using its name
  20852. * @param {string} the camera's name
  20853. * @return {BABYLON.Camera|null} the camera or null if none found.
  20854. */
  20855. Scene.prototype.getCameraByName = function (name) {
  20856. for (var index = 0; index < this.cameras.length; index++) {
  20857. if (this.cameras[index].name === name) {
  20858. return this.cameras[index];
  20859. }
  20860. }
  20861. return null;
  20862. };
  20863. /**
  20864. * get a bone using its id
  20865. * @param {string} the bone's id
  20866. * @return {BABYLON.Bone|null} the bone or null if not found
  20867. */
  20868. Scene.prototype.getBoneByID = function (id) {
  20869. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20870. var skeleton = this.skeletons[skeletonIndex];
  20871. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20872. if (skeleton.bones[boneIndex].id === id) {
  20873. return skeleton.bones[boneIndex];
  20874. }
  20875. }
  20876. }
  20877. return null;
  20878. };
  20879. /**
  20880. * get a bone using its id
  20881. * @param {string} the bone's name
  20882. * @return {BABYLON.Bone|null} the bone or null if not found
  20883. */
  20884. Scene.prototype.getBoneByName = function (name) {
  20885. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20886. var skeleton = this.skeletons[skeletonIndex];
  20887. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20888. if (skeleton.bones[boneIndex].name === name) {
  20889. return skeleton.bones[boneIndex];
  20890. }
  20891. }
  20892. }
  20893. return null;
  20894. };
  20895. /**
  20896. * get a light node using its name
  20897. * @param {string} the light's name
  20898. * @return {BABYLON.Light|null} the light or null if none found.
  20899. */
  20900. Scene.prototype.getLightByName = function (name) {
  20901. for (var index = 0; index < this.lights.length; index++) {
  20902. if (this.lights[index].name === name) {
  20903. return this.lights[index];
  20904. }
  20905. }
  20906. return null;
  20907. };
  20908. /**
  20909. * get a light node using its ID
  20910. * @param {string} the light's id
  20911. * @return {BABYLON.Light|null} the light or null if none found.
  20912. */
  20913. Scene.prototype.getLightByID = function (id) {
  20914. for (var index = 0; index < this.lights.length; index++) {
  20915. if (this.lights[index].id === id) {
  20916. return this.lights[index];
  20917. }
  20918. }
  20919. return null;
  20920. };
  20921. /**
  20922. * get a light node using its scene-generated unique ID
  20923. * @param {number} the light's unique id
  20924. * @return {BABYLON.Light|null} the light or null if none found.
  20925. */
  20926. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20927. for (var index = 0; index < this.lights.length; index++) {
  20928. if (this.lights[index].uniqueId === uniqueId) {
  20929. return this.lights[index];
  20930. }
  20931. }
  20932. return null;
  20933. };
  20934. /**
  20935. * get a particle system by id
  20936. * @param id {number} the particle system id
  20937. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20938. */
  20939. Scene.prototype.getParticleSystemByID = function (id) {
  20940. for (var index = 0; index < this.particleSystems.length; index++) {
  20941. if (this.particleSystems[index].id === id) {
  20942. return this.particleSystems[index];
  20943. }
  20944. }
  20945. return null;
  20946. };
  20947. /**
  20948. * get a geometry using its ID
  20949. * @param {string} the geometry's id
  20950. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20951. */
  20952. Scene.prototype.getGeometryByID = function (id) {
  20953. for (var index = 0; index < this._geometries.length; index++) {
  20954. if (this._geometries[index].id === id) {
  20955. return this._geometries[index];
  20956. }
  20957. }
  20958. return null;
  20959. };
  20960. /**
  20961. * add a new geometry to this scene.
  20962. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20963. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20964. * @return {boolean} was the geometry added or not
  20965. */
  20966. Scene.prototype.pushGeometry = function (geometry, force) {
  20967. if (!force && this.getGeometryByID(geometry.id)) {
  20968. return false;
  20969. }
  20970. this._geometries.push(geometry);
  20971. //notify the collision coordinator
  20972. this.collisionCoordinator.onGeometryAdded(geometry);
  20973. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20974. return true;
  20975. };
  20976. /**
  20977. * Removes an existing geometry
  20978. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20979. * @return {boolean} was the geometry removed or not
  20980. */
  20981. Scene.prototype.removeGeometry = function (geometry) {
  20982. var index = this._geometries.indexOf(geometry);
  20983. if (index > -1) {
  20984. this._geometries.splice(index, 1);
  20985. //notify the collision coordinator
  20986. this.collisionCoordinator.onGeometryDeleted(geometry);
  20987. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20988. return true;
  20989. }
  20990. return false;
  20991. };
  20992. Scene.prototype.getGeometries = function () {
  20993. return this._geometries;
  20994. };
  20995. /**
  20996. * Get the first added mesh found of a given ID
  20997. * @param {string} id - the id to search for
  20998. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20999. */
  21000. Scene.prototype.getMeshByID = function (id) {
  21001. for (var index = 0; index < this.meshes.length; index++) {
  21002. if (this.meshes[index].id === id) {
  21003. return this.meshes[index];
  21004. }
  21005. }
  21006. return null;
  21007. };
  21008. Scene.prototype.getMeshesByID = function (id) {
  21009. return this.meshes.filter(function (m) {
  21010. return m.id === id;
  21011. });
  21012. };
  21013. /**
  21014. * Get a mesh with its auto-generated unique id
  21015. * @param {number} uniqueId - the unique id to search for
  21016. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21017. */
  21018. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21019. for (var index = 0; index < this.meshes.length; index++) {
  21020. if (this.meshes[index].uniqueId === uniqueId) {
  21021. return this.meshes[index];
  21022. }
  21023. }
  21024. return null;
  21025. };
  21026. /**
  21027. * Get a the last added mesh found of a given ID
  21028. * @param {string} id - the id to search for
  21029. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21030. */
  21031. Scene.prototype.getLastMeshByID = function (id) {
  21032. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21033. if (this.meshes[index].id === id) {
  21034. return this.meshes[index];
  21035. }
  21036. }
  21037. return null;
  21038. };
  21039. /**
  21040. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21041. * @param {string} id - the id to search for
  21042. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21043. */
  21044. Scene.prototype.getLastEntryByID = function (id) {
  21045. var index;
  21046. for (index = this.meshes.length - 1; index >= 0; index--) {
  21047. if (this.meshes[index].id === id) {
  21048. return this.meshes[index];
  21049. }
  21050. }
  21051. for (index = this.cameras.length - 1; index >= 0; index--) {
  21052. if (this.cameras[index].id === id) {
  21053. return this.cameras[index];
  21054. }
  21055. }
  21056. for (index = this.lights.length - 1; index >= 0; index--) {
  21057. if (this.lights[index].id === id) {
  21058. return this.lights[index];
  21059. }
  21060. }
  21061. return null;
  21062. };
  21063. Scene.prototype.getNodeByID = function (id) {
  21064. var mesh = this.getMeshByID(id);
  21065. if (mesh) {
  21066. return mesh;
  21067. }
  21068. var light = this.getLightByID(id);
  21069. if (light) {
  21070. return light;
  21071. }
  21072. var camera = this.getCameraByID(id);
  21073. if (camera) {
  21074. return camera;
  21075. }
  21076. var bone = this.getBoneByID(id);
  21077. return bone;
  21078. };
  21079. Scene.prototype.getNodeByName = function (name) {
  21080. var mesh = this.getMeshByName(name);
  21081. if (mesh) {
  21082. return mesh;
  21083. }
  21084. var light = this.getLightByName(name);
  21085. if (light) {
  21086. return light;
  21087. }
  21088. var camera = this.getCameraByName(name);
  21089. if (camera) {
  21090. return camera;
  21091. }
  21092. var bone = this.getBoneByName(name);
  21093. return bone;
  21094. };
  21095. Scene.prototype.getMeshByName = function (name) {
  21096. for (var index = 0; index < this.meshes.length; index++) {
  21097. if (this.meshes[index].name === name) {
  21098. return this.meshes[index];
  21099. }
  21100. }
  21101. return null;
  21102. };
  21103. Scene.prototype.getSoundByName = function (name) {
  21104. var index;
  21105. if (BABYLON.AudioEngine) {
  21106. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21107. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21108. return this.mainSoundTrack.soundCollection[index];
  21109. }
  21110. }
  21111. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21112. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21113. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21114. return this.soundTracks[sdIndex].soundCollection[index];
  21115. }
  21116. }
  21117. }
  21118. }
  21119. return null;
  21120. };
  21121. Scene.prototype.getLastSkeletonByID = function (id) {
  21122. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21123. if (this.skeletons[index].id === id) {
  21124. return this.skeletons[index];
  21125. }
  21126. }
  21127. return null;
  21128. };
  21129. Scene.prototype.getSkeletonById = function (id) {
  21130. for (var index = 0; index < this.skeletons.length; index++) {
  21131. if (this.skeletons[index].id === id) {
  21132. return this.skeletons[index];
  21133. }
  21134. }
  21135. return null;
  21136. };
  21137. Scene.prototype.getSkeletonByName = function (name) {
  21138. for (var index = 0; index < this.skeletons.length; index++) {
  21139. if (this.skeletons[index].name === name) {
  21140. return this.skeletons[index];
  21141. }
  21142. }
  21143. return null;
  21144. };
  21145. Scene.prototype.isActiveMesh = function (mesh) {
  21146. return (this._activeMeshes.indexOf(mesh) !== -1);
  21147. };
  21148. /**
  21149. * Return a the first highlight layer of the scene with a given name.
  21150. * @param name The name of the highlight layer to look for.
  21151. * @return The highlight layer if found otherwise null.
  21152. */
  21153. Scene.prototype.getHighlightLayerByName = function (name) {
  21154. for (var index = 0; index < this.highlightLayers.length; index++) {
  21155. if (this.highlightLayers[index].name === name) {
  21156. return this.highlightLayers[index];
  21157. }
  21158. }
  21159. return null;
  21160. };
  21161. Object.defineProperty(Scene.prototype, "uid", {
  21162. /**
  21163. * Return a unique id as a string which can serve as an identifier for the scene
  21164. */
  21165. get: function () {
  21166. if (!this._uid) {
  21167. this._uid = BABYLON.Tools.RandomId();
  21168. }
  21169. return this._uid;
  21170. },
  21171. enumerable: true,
  21172. configurable: true
  21173. });
  21174. /**
  21175. * Add an externaly attached data from its key.
  21176. * This method call will fail and return false, if such key already exists.
  21177. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21178. * @param key the unique key that identifies the data
  21179. * @param data the data object to associate to the key for this Engine instance
  21180. * @return true if no such key were already present and the data was added successfully, false otherwise
  21181. */
  21182. Scene.prototype.addExternalData = function (key, data) {
  21183. return this._externalData.add(key, data);
  21184. };
  21185. /**
  21186. * Get an externaly attached data from its key
  21187. * @param key the unique key that identifies the data
  21188. * @return the associated data, if present (can be null), or undefined if not present
  21189. */
  21190. Scene.prototype.getExternalData = function (key) {
  21191. return this._externalData.get(key);
  21192. };
  21193. /**
  21194. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21195. * @param key the unique key that identifies the data
  21196. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21197. * @return the associated data, can be null if the factory returned null.
  21198. */
  21199. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21200. return this._externalData.getOrAddWithFactory(key, factory);
  21201. };
  21202. /**
  21203. * Remove an externaly attached data from the Engine instance
  21204. * @param key the unique key that identifies the data
  21205. * @return true if the data was successfully removed, false if it doesn't exist
  21206. */
  21207. Scene.prototype.removeExternalData = function (key) {
  21208. return this._externalData.remove(key);
  21209. };
  21210. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21211. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21212. var material = subMesh.getMaterial();
  21213. if (mesh.showSubMeshesBoundingBox) {
  21214. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21215. }
  21216. if (material) {
  21217. // Render targets
  21218. if (material.getRenderTargetTextures) {
  21219. if (this._processedMaterials.indexOf(material) === -1) {
  21220. this._processedMaterials.push(material);
  21221. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21222. }
  21223. }
  21224. // Dispatch
  21225. this._activeIndices.addCount(subMesh.indexCount, false);
  21226. this._renderingManager.dispatch(subMesh);
  21227. }
  21228. }
  21229. };
  21230. Scene.prototype._isInIntermediateRendering = function () {
  21231. return this._intermediateRendering;
  21232. };
  21233. Scene.prototype._evaluateActiveMeshes = function () {
  21234. this.activeCamera._activeMeshes.reset();
  21235. this._activeMeshes.reset();
  21236. this._renderingManager.reset();
  21237. this._processedMaterials.reset();
  21238. this._activeParticleSystems.reset();
  21239. this._activeSkeletons.reset();
  21240. this._softwareSkinnedMeshes.reset();
  21241. this._boundingBoxRenderer.reset();
  21242. this._edgesRenderers.reset();
  21243. // Meshes
  21244. var meshes;
  21245. var len;
  21246. if (this._selectionOctree) {
  21247. var selection = this._selectionOctree.select(this._frustumPlanes);
  21248. meshes = selection.data;
  21249. len = selection.length;
  21250. }
  21251. else {
  21252. len = this.meshes.length;
  21253. meshes = this.meshes;
  21254. }
  21255. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21256. var mesh = meshes[meshIndex];
  21257. if (mesh.isBlocked) {
  21258. continue;
  21259. }
  21260. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21261. if (!mesh.isReady() || !mesh.isEnabled()) {
  21262. continue;
  21263. }
  21264. mesh.computeWorldMatrix();
  21265. // Intersections
  21266. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21267. this._meshesForIntersections.pushNoDuplicate(mesh);
  21268. }
  21269. // Switch to current LOD
  21270. var meshLOD = mesh.getLOD(this.activeCamera);
  21271. if (!meshLOD) {
  21272. continue;
  21273. }
  21274. mesh._preActivate();
  21275. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21276. this._activeMeshes.push(mesh);
  21277. this.activeCamera._activeMeshes.push(mesh);
  21278. mesh._activate(this._renderId);
  21279. this._activeMesh(mesh, meshLOD);
  21280. }
  21281. }
  21282. // Particle systems
  21283. this._particlesDuration.beginMonitoring();
  21284. var beforeParticlesDate = BABYLON.Tools.Now;
  21285. if (this.particlesEnabled) {
  21286. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21287. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21288. var particleSystem = this.particleSystems[particleIndex];
  21289. if (!particleSystem.isStarted()) {
  21290. continue;
  21291. }
  21292. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21293. this._activeParticleSystems.push(particleSystem);
  21294. particleSystem.animate();
  21295. this._renderingManager.dispatchParticles(particleSystem);
  21296. }
  21297. }
  21298. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21299. }
  21300. this._particlesDuration.endMonitoring(false);
  21301. };
  21302. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21303. if (mesh.skeleton && this.skeletonsEnabled) {
  21304. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21305. mesh.skeleton.prepare();
  21306. }
  21307. if (!mesh.computeBonesUsingShaders) {
  21308. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21309. }
  21310. }
  21311. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21312. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21313. }
  21314. if (sourceMesh._edgesRenderer) {
  21315. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21316. }
  21317. if (mesh && mesh.subMeshes) {
  21318. // Submeshes Octrees
  21319. var len;
  21320. var subMeshes;
  21321. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21322. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21323. len = intersections.length;
  21324. subMeshes = intersections.data;
  21325. }
  21326. else {
  21327. subMeshes = mesh.subMeshes;
  21328. len = subMeshes.length;
  21329. }
  21330. for (var subIndex = 0; subIndex < len; subIndex++) {
  21331. var subMesh = subMeshes[subIndex];
  21332. this._evaluateSubMesh(subMesh, mesh);
  21333. }
  21334. }
  21335. };
  21336. Scene.prototype.updateTransformMatrix = function (force) {
  21337. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21338. };
  21339. Scene.prototype._renderForCamera = function (camera) {
  21340. var engine = this._engine;
  21341. var startTime = BABYLON.Tools.Now;
  21342. this.activeCamera = camera;
  21343. if (!this.activeCamera)
  21344. throw new Error("Active camera not set");
  21345. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21346. // Viewport
  21347. engine.setViewport(this.activeCamera.viewport);
  21348. // Camera
  21349. this.resetCachedMaterial();
  21350. this._renderId++;
  21351. this.updateTransformMatrix();
  21352. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21353. // Meshes
  21354. this._evaluateActiveMeshesDuration.beginMonitoring();
  21355. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21356. this._evaluateActiveMeshes();
  21357. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21358. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21359. // Software skinning
  21360. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21361. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21362. mesh.applySkeleton(mesh.skeleton);
  21363. }
  21364. // Render targets
  21365. this._renderTargetsDuration.beginMonitoring();
  21366. var needsRestoreFrameBuffer = false;
  21367. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21368. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21369. this._intermediateRendering = true;
  21370. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21371. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21372. var renderTarget = this._renderTargets.data[renderIndex];
  21373. if (renderTarget._shouldRender()) {
  21374. this._renderId++;
  21375. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21376. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21377. }
  21378. }
  21379. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21380. this._intermediateRendering = false;
  21381. this._renderId++;
  21382. needsRestoreFrameBuffer = true; // Restore back buffer
  21383. }
  21384. // Render HighlightLayer Texture
  21385. var stencilState = this._engine.getStencilBuffer();
  21386. var renderhighlights = false;
  21387. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21388. this._intermediateRendering = true;
  21389. for (var i = 0; i < this.highlightLayers.length; i++) {
  21390. var highlightLayer = this.highlightLayers[i];
  21391. if (highlightLayer.shouldRender() &&
  21392. (!highlightLayer.camera ||
  21393. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21394. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21395. renderhighlights = true;
  21396. var renderTarget = highlightLayer._mainTexture;
  21397. if (renderTarget._shouldRender()) {
  21398. this._renderId++;
  21399. renderTarget.render(false, false);
  21400. needsRestoreFrameBuffer = true;
  21401. }
  21402. }
  21403. }
  21404. this._intermediateRendering = false;
  21405. this._renderId++;
  21406. }
  21407. if (needsRestoreFrameBuffer) {
  21408. engine.restoreDefaultFramebuffer();
  21409. }
  21410. this._renderTargetsDuration.endMonitoring(false);
  21411. // Prepare Frame
  21412. this.postProcessManager._prepareFrame();
  21413. this._renderDuration.beginMonitoring();
  21414. // Backgrounds
  21415. var layerIndex;
  21416. var layer;
  21417. if (this.layers.length) {
  21418. engine.setDepthBuffer(false);
  21419. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21420. layer = this.layers[layerIndex];
  21421. if (layer.isBackground) {
  21422. layer.render();
  21423. }
  21424. }
  21425. engine.setDepthBuffer(true);
  21426. }
  21427. // Render
  21428. BABYLON.Tools.StartPerformanceCounter("Main render");
  21429. // Activate HighlightLayer stencil
  21430. if (renderhighlights) {
  21431. this._engine.setStencilBuffer(true);
  21432. }
  21433. this._renderingManager.render(null, null, true, true);
  21434. // Restore HighlightLayer stencil
  21435. if (renderhighlights) {
  21436. this._engine.setStencilBuffer(stencilState);
  21437. }
  21438. BABYLON.Tools.EndPerformanceCounter("Main render");
  21439. // Bounding boxes
  21440. this._boundingBoxRenderer.render();
  21441. // Edges
  21442. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21443. this._edgesRenderers.data[edgesRendererIndex].render();
  21444. }
  21445. // Lens flares
  21446. if (this.lensFlaresEnabled) {
  21447. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21448. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21449. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21450. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21451. lensFlareSystem.render();
  21452. }
  21453. }
  21454. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21455. }
  21456. // Foregrounds
  21457. if (this.layers.length) {
  21458. engine.setDepthBuffer(false);
  21459. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21460. layer = this.layers[layerIndex];
  21461. if (!layer.isBackground) {
  21462. layer.render();
  21463. }
  21464. }
  21465. engine.setDepthBuffer(true);
  21466. }
  21467. // Highlight Layer
  21468. if (renderhighlights) {
  21469. engine.setDepthBuffer(false);
  21470. for (var i = 0; i < this.highlightLayers.length; i++) {
  21471. if (this.highlightLayers[i].shouldRender()) {
  21472. this.highlightLayers[i].render();
  21473. }
  21474. }
  21475. engine.setDepthBuffer(true);
  21476. }
  21477. this._renderDuration.endMonitoring(false);
  21478. // Finalize frame
  21479. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21480. // Update camera
  21481. this.activeCamera._updateFromScene();
  21482. // Reset some special arrays
  21483. this._renderTargets.reset();
  21484. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21485. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21486. };
  21487. Scene.prototype._processSubCameras = function (camera) {
  21488. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21489. this._renderForCamera(camera);
  21490. return;
  21491. }
  21492. // rig cameras
  21493. for (var index = 0; index < camera._rigCameras.length; index++) {
  21494. this._renderForCamera(camera._rigCameras[index]);
  21495. }
  21496. this.activeCamera = camera;
  21497. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21498. // Update camera
  21499. this.activeCamera._updateFromScene();
  21500. };
  21501. Scene.prototype._checkIntersections = function () {
  21502. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21503. var sourceMesh = this._meshesForIntersections.data[index];
  21504. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21505. var action = sourceMesh.actionManager.actions[actionIndex];
  21506. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21507. var parameters = action.getTriggerParameter();
  21508. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21509. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21510. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21511. if (areIntersecting && currentIntersectionInProgress === -1) {
  21512. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21513. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21514. sourceMesh._intersectionsInProgress.push(otherMesh);
  21515. }
  21516. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21517. sourceMesh._intersectionsInProgress.push(otherMesh);
  21518. }
  21519. }
  21520. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21521. //They intersected, and now they don't.
  21522. //is this trigger an exit trigger? execute an event.
  21523. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21524. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21525. }
  21526. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21527. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21528. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21529. }
  21530. }
  21531. }
  21532. }
  21533. }
  21534. };
  21535. Scene.prototype.render = function () {
  21536. if (this.isDisposed) {
  21537. return;
  21538. }
  21539. this._lastFrameDuration.beginMonitoring();
  21540. this._particlesDuration.fetchNewFrame();
  21541. this._spritesDuration.fetchNewFrame();
  21542. this._activeParticles.fetchNewFrame();
  21543. this._renderDuration.fetchNewFrame();
  21544. this._renderTargetsDuration.fetchNewFrame();
  21545. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21546. this._totalVertices.fetchNewFrame();
  21547. this._activeIndices.fetchNewFrame();
  21548. this._activeBones.fetchNewFrame();
  21549. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21550. this._meshesForIntersections.reset();
  21551. this.resetCachedMaterial();
  21552. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21553. // Actions
  21554. if (this.actionManager) {
  21555. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21556. }
  21557. //Simplification Queue
  21558. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21559. this.simplificationQueue.executeNext();
  21560. }
  21561. // Animations
  21562. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21563. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21564. this._animate();
  21565. // Physics
  21566. if (this._physicsEngine) {
  21567. BABYLON.Tools.StartPerformanceCounter("Physics");
  21568. this._physicsEngine._step(deltaTime / 1000.0);
  21569. BABYLON.Tools.EndPerformanceCounter("Physics");
  21570. }
  21571. // Before render
  21572. this.onBeforeRenderObservable.notifyObservers(this);
  21573. // Customs render targets
  21574. this._renderTargetsDuration.beginMonitoring();
  21575. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21576. var engine = this.getEngine();
  21577. var currentActiveCamera = this.activeCamera;
  21578. if (this.renderTargetsEnabled) {
  21579. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21580. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21581. var renderTarget = this.customRenderTargets[customIndex];
  21582. if (renderTarget._shouldRender()) {
  21583. this._renderId++;
  21584. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21585. if (!this.activeCamera)
  21586. throw new Error("Active camera not set");
  21587. // Viewport
  21588. engine.setViewport(this.activeCamera.viewport);
  21589. // Camera
  21590. this.updateTransformMatrix();
  21591. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21592. }
  21593. }
  21594. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21595. this._renderId++;
  21596. }
  21597. if (this.customRenderTargets.length > 0) {
  21598. engine.restoreDefaultFramebuffer();
  21599. }
  21600. this._renderTargetsDuration.endMonitoring();
  21601. this.activeCamera = currentActiveCamera;
  21602. // Procedural textures
  21603. if (this.proceduralTexturesEnabled) {
  21604. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21605. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21606. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21607. if (proceduralTexture._shouldRender()) {
  21608. proceduralTexture.render();
  21609. }
  21610. }
  21611. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21612. }
  21613. // Clear
  21614. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21615. // Shadows
  21616. if (this.shadowsEnabled) {
  21617. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21618. var light = this.lights[lightIndex];
  21619. var shadowGenerator = light.getShadowGenerator();
  21620. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21621. this._renderTargets.push(shadowGenerator.getShadowMap());
  21622. }
  21623. }
  21624. }
  21625. // Depth renderer
  21626. if (this._depthRenderer) {
  21627. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21628. }
  21629. // RenderPipeline
  21630. this.postProcessRenderPipelineManager.update();
  21631. // Multi-cameras?
  21632. if (this.activeCameras.length > 0) {
  21633. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21634. if (cameraIndex > 0) {
  21635. this._engine.clear(null, false, true, true);
  21636. }
  21637. this._processSubCameras(this.activeCameras[cameraIndex]);
  21638. }
  21639. }
  21640. else {
  21641. if (!this.activeCamera) {
  21642. throw new Error("No camera defined");
  21643. }
  21644. this._processSubCameras(this.activeCamera);
  21645. }
  21646. // Intersection checks
  21647. this._checkIntersections();
  21648. // Update the audio listener attached to the camera
  21649. if (BABYLON.AudioEngine) {
  21650. this._updateAudioParameters();
  21651. }
  21652. // After render
  21653. if (this.afterRender) {
  21654. this.afterRender();
  21655. }
  21656. this.onAfterRenderObservable.notifyObservers(this);
  21657. // Cleaning
  21658. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21659. this._toBeDisposed.data[index].dispose();
  21660. this._toBeDisposed[index] = null;
  21661. }
  21662. this._toBeDisposed.reset();
  21663. if (this.dumpNextRenderTargets) {
  21664. this.dumpNextRenderTargets = false;
  21665. }
  21666. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21667. this._lastFrameDuration.endMonitoring();
  21668. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21669. this._totalLightsCounter.addCount(this.lights.length, true);
  21670. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21671. this._totalTexturesCounter.addCount(this.textures.length, true);
  21672. this._activeBones.addCount(0, true);
  21673. this._activeIndices.addCount(0, true);
  21674. this._activeParticles.addCount(0, true);
  21675. };
  21676. Scene.prototype._updateAudioParameters = function () {
  21677. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21678. return;
  21679. }
  21680. var listeningCamera;
  21681. var audioEngine = BABYLON.Engine.audioEngine;
  21682. if (this.activeCameras.length > 0) {
  21683. listeningCamera = this.activeCameras[0];
  21684. }
  21685. else {
  21686. listeningCamera = this.activeCamera;
  21687. }
  21688. if (listeningCamera && audioEngine.canUseWebAudio) {
  21689. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21690. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21691. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21692. cameraDirection.normalize();
  21693. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21694. var i;
  21695. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21696. var sound = this.mainSoundTrack.soundCollection[i];
  21697. if (sound.useCustomAttenuation) {
  21698. sound.updateDistanceFromListener();
  21699. }
  21700. }
  21701. for (i = 0; i < this.soundTracks.length; i++) {
  21702. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21703. sound = this.soundTracks[i].soundCollection[j];
  21704. if (sound.useCustomAttenuation) {
  21705. sound.updateDistanceFromListener();
  21706. }
  21707. }
  21708. }
  21709. }
  21710. };
  21711. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21712. // Audio
  21713. get: function () {
  21714. return this._audioEnabled;
  21715. },
  21716. set: function (value) {
  21717. this._audioEnabled = value;
  21718. if (BABYLON.AudioEngine) {
  21719. if (this._audioEnabled) {
  21720. this._enableAudio();
  21721. }
  21722. else {
  21723. this._disableAudio();
  21724. }
  21725. }
  21726. },
  21727. enumerable: true,
  21728. configurable: true
  21729. });
  21730. Scene.prototype._disableAudio = function () {
  21731. var i;
  21732. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21733. this.mainSoundTrack.soundCollection[i].pause();
  21734. }
  21735. for (i = 0; i < this.soundTracks.length; i++) {
  21736. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21737. this.soundTracks[i].soundCollection[j].pause();
  21738. }
  21739. }
  21740. };
  21741. Scene.prototype._enableAudio = function () {
  21742. var i;
  21743. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21744. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21745. this.mainSoundTrack.soundCollection[i].play();
  21746. }
  21747. }
  21748. for (i = 0; i < this.soundTracks.length; i++) {
  21749. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21750. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21751. this.soundTracks[i].soundCollection[j].play();
  21752. }
  21753. }
  21754. }
  21755. };
  21756. Object.defineProperty(Scene.prototype, "headphone", {
  21757. get: function () {
  21758. return this._headphone;
  21759. },
  21760. set: function (value) {
  21761. this._headphone = value;
  21762. if (BABYLON.AudioEngine) {
  21763. if (this._headphone) {
  21764. this._switchAudioModeForHeadphones();
  21765. }
  21766. else {
  21767. this._switchAudioModeForNormalSpeakers();
  21768. }
  21769. }
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Scene.prototype._switchAudioModeForHeadphones = function () {
  21775. this.mainSoundTrack.switchPanningModelToHRTF();
  21776. for (var i = 0; i < this.soundTracks.length; i++) {
  21777. this.soundTracks[i].switchPanningModelToHRTF();
  21778. }
  21779. };
  21780. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21781. this.mainSoundTrack.switchPanningModelToEqualPower();
  21782. for (var i = 0; i < this.soundTracks.length; i++) {
  21783. this.soundTracks[i].switchPanningModelToEqualPower();
  21784. }
  21785. };
  21786. Scene.prototype.enableDepthRenderer = function () {
  21787. if (this._depthRenderer) {
  21788. return this._depthRenderer;
  21789. }
  21790. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21791. return this._depthRenderer;
  21792. };
  21793. Scene.prototype.disableDepthRenderer = function () {
  21794. if (!this._depthRenderer) {
  21795. return;
  21796. }
  21797. this._depthRenderer.dispose();
  21798. this._depthRenderer = null;
  21799. };
  21800. Scene.prototype.freezeMaterials = function () {
  21801. for (var i = 0; i < this.materials.length; i++) {
  21802. this.materials[i].freeze();
  21803. }
  21804. };
  21805. Scene.prototype.unfreezeMaterials = function () {
  21806. for (var i = 0; i < this.materials.length; i++) {
  21807. this.materials[i].unfreeze();
  21808. }
  21809. };
  21810. Scene.prototype.dispose = function () {
  21811. this.beforeRender = null;
  21812. this.afterRender = null;
  21813. this.skeletons = [];
  21814. this._boundingBoxRenderer.dispose();
  21815. if (this._depthRenderer) {
  21816. this._depthRenderer.dispose();
  21817. }
  21818. // Smart arrays
  21819. if (this.activeCamera) {
  21820. this.activeCamera._activeMeshes.dispose();
  21821. this.activeCamera = null;
  21822. }
  21823. this._activeMeshes.dispose();
  21824. this._renderingManager.dispose();
  21825. this._processedMaterials.dispose();
  21826. this._activeParticleSystems.dispose();
  21827. this._activeSkeletons.dispose();
  21828. this._softwareSkinnedMeshes.dispose();
  21829. this._boundingBoxRenderer.dispose();
  21830. this._edgesRenderers.dispose();
  21831. this._meshesForIntersections.dispose();
  21832. this._toBeDisposed.dispose();
  21833. // Debug layer
  21834. if (this._debugLayer) {
  21835. this._debugLayer.hide();
  21836. }
  21837. // Events
  21838. this.onDisposeObservable.notifyObservers(this);
  21839. this.onDisposeObservable.clear();
  21840. this.onBeforeRenderObservable.clear();
  21841. this.onAfterRenderObservable.clear();
  21842. this.detachControl();
  21843. // Release sounds & sounds tracks
  21844. if (BABYLON.AudioEngine) {
  21845. this.disposeSounds();
  21846. }
  21847. // Detach cameras
  21848. var canvas = this._engine.getRenderingCanvas();
  21849. var index;
  21850. for (index = 0; index < this.cameras.length; index++) {
  21851. this.cameras[index].detachControl(canvas);
  21852. }
  21853. // Release lights
  21854. while (this.lights.length) {
  21855. this.lights[0].dispose();
  21856. }
  21857. // Release meshes
  21858. while (this.meshes.length) {
  21859. this.meshes[0].dispose(true);
  21860. }
  21861. // Release cameras
  21862. while (this.cameras.length) {
  21863. this.cameras[0].dispose();
  21864. }
  21865. // Release materials
  21866. while (this.materials.length) {
  21867. this.materials[0].dispose();
  21868. }
  21869. // Release particles
  21870. while (this.particleSystems.length) {
  21871. this.particleSystems[0].dispose();
  21872. }
  21873. // Release sprites
  21874. while (this.spriteManagers.length) {
  21875. this.spriteManagers[0].dispose();
  21876. }
  21877. // Release layers
  21878. while (this.layers.length) {
  21879. this.layers[0].dispose();
  21880. }
  21881. while (this.highlightLayers.length) {
  21882. this.highlightLayers[0].dispose();
  21883. }
  21884. // Release textures
  21885. while (this.textures.length) {
  21886. this.textures[0].dispose();
  21887. }
  21888. // Post-processes
  21889. this.postProcessManager.dispose();
  21890. // Physics
  21891. if (this._physicsEngine) {
  21892. this.disablePhysicsEngine();
  21893. }
  21894. // Remove from engine
  21895. index = this._engine.scenes.indexOf(this);
  21896. if (index > -1) {
  21897. this._engine.scenes.splice(index, 1);
  21898. }
  21899. this._engine.wipeCaches();
  21900. this._engine = null;
  21901. };
  21902. Object.defineProperty(Scene.prototype, "isDisposed", {
  21903. get: function () {
  21904. return !this._engine;
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. // Release sounds & sounds tracks
  21910. Scene.prototype.disposeSounds = function () {
  21911. this.mainSoundTrack.dispose();
  21912. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21913. this.soundTracks[scIndex].dispose();
  21914. }
  21915. };
  21916. // Octrees
  21917. Scene.prototype.getWorldExtends = function () {
  21918. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21919. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21920. for (var index = 0; index < this.meshes.length; index++) {
  21921. var mesh = this.meshes[index];
  21922. mesh.computeWorldMatrix(true);
  21923. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21924. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21925. BABYLON.Tools.CheckExtends(minBox, min, max);
  21926. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21927. }
  21928. return {
  21929. min: min,
  21930. max: max
  21931. };
  21932. };
  21933. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21934. if (maxCapacity === void 0) { maxCapacity = 64; }
  21935. if (maxDepth === void 0) { maxDepth = 2; }
  21936. if (!this._selectionOctree) {
  21937. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21938. }
  21939. var worldExtends = this.getWorldExtends();
  21940. // Update octree
  21941. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21942. return this._selectionOctree;
  21943. };
  21944. // Picking
  21945. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21946. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21947. var engine = this._engine;
  21948. if (!camera) {
  21949. if (!this.activeCamera)
  21950. throw new Error("Active camera not set");
  21951. camera = this.activeCamera;
  21952. }
  21953. var cameraViewport = camera.viewport;
  21954. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21955. // Moving coordinates to local viewport world
  21956. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21957. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21958. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21959. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21960. };
  21961. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21962. var engine = this._engine;
  21963. if (!camera) {
  21964. if (!this.activeCamera)
  21965. throw new Error("Active camera not set");
  21966. camera = this.activeCamera;
  21967. }
  21968. var cameraViewport = camera.viewport;
  21969. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21970. var identity = BABYLON.Matrix.Identity();
  21971. // Moving coordinates to local viewport world
  21972. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21973. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21974. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21975. };
  21976. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21977. var pickingInfo = null;
  21978. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21979. var mesh = this.meshes[meshIndex];
  21980. if (predicate) {
  21981. if (!predicate(mesh)) {
  21982. continue;
  21983. }
  21984. }
  21985. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21986. continue;
  21987. }
  21988. var world = mesh.getWorldMatrix();
  21989. var ray = rayFunction(world);
  21990. var result = mesh.intersects(ray, fastCheck);
  21991. if (!result || !result.hit)
  21992. continue;
  21993. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21994. continue;
  21995. pickingInfo = result;
  21996. if (fastCheck) {
  21997. break;
  21998. }
  21999. }
  22000. return pickingInfo || new BABYLON.PickingInfo();
  22001. };
  22002. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22003. var pickingInfos = new Array();
  22004. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22005. var mesh = this.meshes[meshIndex];
  22006. if (predicate) {
  22007. if (!predicate(mesh)) {
  22008. continue;
  22009. }
  22010. }
  22011. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22012. continue;
  22013. }
  22014. var world = mesh.getWorldMatrix();
  22015. var ray = rayFunction(world);
  22016. var result = mesh.intersects(ray, false);
  22017. if (!result || !result.hit)
  22018. continue;
  22019. pickingInfos.push(result);
  22020. }
  22021. return pickingInfos;
  22022. };
  22023. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22024. var pickingInfo = null;
  22025. camera = camera || this.activeCamera;
  22026. if (this.spriteManagers.length > 0) {
  22027. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22028. var spriteManager = this.spriteManagers[spriteIndex];
  22029. if (!spriteManager.isPickable) {
  22030. continue;
  22031. }
  22032. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22033. if (!result || !result.hit)
  22034. continue;
  22035. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22036. continue;
  22037. pickingInfo = result;
  22038. if (fastCheck) {
  22039. break;
  22040. }
  22041. }
  22042. }
  22043. return pickingInfo || new BABYLON.PickingInfo();
  22044. };
  22045. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22046. /// <param name="x">X position on screen</param>
  22047. /// <param name="y">Y position on screen</param>
  22048. /// <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>
  22049. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22050. /// <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>
  22051. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22052. var _this = this;
  22053. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22054. };
  22055. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22056. /// <param name="x">X position on screen</param>
  22057. /// <param name="y">Y position on screen</param>
  22058. /// <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>
  22059. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22060. /// <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>
  22061. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22062. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22063. };
  22064. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22065. var _this = this;
  22066. return this._internalPick(function (world) {
  22067. if (!_this._pickWithRayInverseMatrix) {
  22068. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22069. }
  22070. world.invertToRef(_this._pickWithRayInverseMatrix);
  22071. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22072. }, predicate, fastCheck);
  22073. };
  22074. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22075. /// <param name="x">X position on screen</param>
  22076. /// <param name="y">Y position on screen</param>
  22077. /// <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>
  22078. /// <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>
  22079. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22080. var _this = this;
  22081. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22082. };
  22083. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22084. /// <param name="ray">Ray to use</param>
  22085. /// <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>
  22086. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22087. var _this = this;
  22088. return this._internalMultiPick(function (world) {
  22089. if (!_this._pickWithRayInverseMatrix) {
  22090. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22091. }
  22092. world.invertToRef(_this._pickWithRayInverseMatrix);
  22093. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22094. }, predicate);
  22095. };
  22096. Scene.prototype.setPointerOverMesh = function (mesh) {
  22097. if (this._pointerOverMesh === mesh) {
  22098. return;
  22099. }
  22100. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22101. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22102. }
  22103. this._pointerOverMesh = mesh;
  22104. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22105. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22106. }
  22107. };
  22108. Scene.prototype.getPointerOverMesh = function () {
  22109. return this._pointerOverMesh;
  22110. };
  22111. Scene.prototype.setPointerOverSprite = function (sprite) {
  22112. if (this._pointerOverSprite === sprite) {
  22113. return;
  22114. }
  22115. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22116. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22117. }
  22118. this._pointerOverSprite = sprite;
  22119. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22120. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22121. }
  22122. };
  22123. Scene.prototype.getPointerOverSprite = function () {
  22124. return this._pointerOverSprite;
  22125. };
  22126. // Physics
  22127. Scene.prototype.getPhysicsEngine = function () {
  22128. return this._physicsEngine;
  22129. };
  22130. /**
  22131. * Enables physics to the current scene
  22132. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22133. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22134. * @return {boolean} was the physics engine initialized
  22135. */
  22136. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22137. if (this._physicsEngine) {
  22138. return true;
  22139. }
  22140. try {
  22141. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22142. return true;
  22143. }
  22144. catch (e) {
  22145. BABYLON.Tools.Error(e.message);
  22146. return false;
  22147. }
  22148. };
  22149. Scene.prototype.disablePhysicsEngine = function () {
  22150. if (!this._physicsEngine) {
  22151. return;
  22152. }
  22153. this._physicsEngine.dispose();
  22154. this._physicsEngine = undefined;
  22155. };
  22156. Scene.prototype.isPhysicsEnabled = function () {
  22157. return this._physicsEngine !== undefined;
  22158. };
  22159. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22160. var mesh = compound.parts[0].mesh;
  22161. mesh.physicsImpostor.dispose();
  22162. mesh.physicsImpostor = null;
  22163. };
  22164. // Misc.
  22165. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22166. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22167. // Light
  22168. if (this.lights.length === 0) {
  22169. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22170. }
  22171. // Camera
  22172. if (!this.activeCamera) {
  22173. // Compute position
  22174. var worldExtends = this.getWorldExtends();
  22175. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22176. var camera;
  22177. if (createArcRotateCamera) {
  22178. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22179. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22180. camera.setTarget(worldCenter);
  22181. }
  22182. else {
  22183. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22184. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22185. camera.setTarget(worldCenter);
  22186. }
  22187. this.activeCamera = camera;
  22188. }
  22189. };
  22190. // Tags
  22191. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22192. if (tagsQuery === undefined) {
  22193. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22194. return list;
  22195. }
  22196. var listByTags = [];
  22197. forEach = forEach || (function (item) { return; });
  22198. for (var i in list) {
  22199. var item = list[i];
  22200. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22201. listByTags.push(item);
  22202. forEach(item);
  22203. }
  22204. }
  22205. return listByTags;
  22206. };
  22207. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22208. return this._getByTags(this.meshes, tagsQuery, forEach);
  22209. };
  22210. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22211. return this._getByTags(this.cameras, tagsQuery, forEach);
  22212. };
  22213. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22214. return this._getByTags(this.lights, tagsQuery, forEach);
  22215. };
  22216. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22217. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22218. };
  22219. /**
  22220. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22221. * This allowed control for front to back rendering or reversly depending of the special needs.
  22222. *
  22223. * @param renderingGroupId The rendering group id corresponding to its index
  22224. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22225. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22226. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22227. */
  22228. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22229. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22230. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22231. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22232. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22233. };
  22234. /**
  22235. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22236. *
  22237. * @param renderingGroupId The rendering group id corresponding to its index
  22238. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22239. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22240. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22241. */
  22242. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22243. if (depth === void 0) { depth = true; }
  22244. if (stencil === void 0) { stencil = true; }
  22245. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22246. };
  22247. return Scene;
  22248. }());
  22249. // Statics
  22250. Scene._FOGMODE_NONE = 0;
  22251. Scene._FOGMODE_EXP = 1;
  22252. Scene._FOGMODE_EXP2 = 2;
  22253. Scene._FOGMODE_LINEAR = 3;
  22254. Scene.MinDeltaTime = 1.0;
  22255. Scene.MaxDeltaTime = 1000.0;
  22256. Scene.DragMovementThreshold = 10; // in pixels
  22257. Scene.LongPressDelay = 500; // in milliseconds
  22258. Scene.DoubleClickDelay = 300; // in milliseconds
  22259. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22260. BABYLON.Scene = Scene;
  22261. })(BABYLON || (BABYLON = {}));
  22262. //# sourceMappingURL=babylon.scene.js.map
  22263. var BABYLON;
  22264. (function (BABYLON) {
  22265. var Buffer = (function () {
  22266. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22267. if (engine instanceof BABYLON.Mesh) {
  22268. this._engine = engine.getScene().getEngine();
  22269. }
  22270. else {
  22271. this._engine = engine;
  22272. }
  22273. this._updatable = updatable;
  22274. this._data = data;
  22275. this._strideSize = stride;
  22276. if (!postponeInternalCreation) {
  22277. this.create();
  22278. }
  22279. this._instanced = instanced;
  22280. }
  22281. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22282. // a lot of these parameters are ignored as they are overriden by the buffer
  22283. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22284. };
  22285. // Properties
  22286. Buffer.prototype.isUpdatable = function () {
  22287. return this._updatable;
  22288. };
  22289. Buffer.prototype.getData = function () {
  22290. return this._data;
  22291. };
  22292. Buffer.prototype.getBuffer = function () {
  22293. return this._buffer;
  22294. };
  22295. Buffer.prototype.getStrideSize = function () {
  22296. return this._strideSize;
  22297. };
  22298. Buffer.prototype.getIsInstanced = function () {
  22299. return this._instanced;
  22300. };
  22301. // Methods
  22302. Buffer.prototype.create = function (data) {
  22303. if (!data && this._buffer) {
  22304. return; // nothing to do
  22305. }
  22306. data = data || this._data;
  22307. if (!this._buffer) {
  22308. if (this._updatable) {
  22309. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22310. this._data = data;
  22311. }
  22312. else {
  22313. this._buffer = this._engine.createVertexBuffer(data);
  22314. }
  22315. }
  22316. else if (this._updatable) {
  22317. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22318. this._data = data;
  22319. }
  22320. };
  22321. Buffer.prototype.update = function (data) {
  22322. this.create(data);
  22323. };
  22324. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22325. if (!this._buffer) {
  22326. return;
  22327. }
  22328. if (this._updatable) {
  22329. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22330. this._data = null;
  22331. }
  22332. };
  22333. Buffer.prototype.dispose = function () {
  22334. if (!this._buffer) {
  22335. return;
  22336. }
  22337. if (this._engine._releaseBuffer(this._buffer)) {
  22338. this._buffer = null;
  22339. }
  22340. };
  22341. return Buffer;
  22342. }());
  22343. BABYLON.Buffer = Buffer;
  22344. })(BABYLON || (BABYLON = {}));
  22345. //# sourceMappingURL=babylon.buffer.js.map
  22346. var BABYLON;
  22347. (function (BABYLON) {
  22348. var VertexBuffer = (function () {
  22349. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22350. if (!stride) {
  22351. // Deduce stride from kind
  22352. switch (kind) {
  22353. case VertexBuffer.PositionKind:
  22354. stride = 3;
  22355. break;
  22356. case VertexBuffer.NormalKind:
  22357. stride = 3;
  22358. break;
  22359. case VertexBuffer.UVKind:
  22360. case VertexBuffer.UV2Kind:
  22361. case VertexBuffer.UV3Kind:
  22362. case VertexBuffer.UV4Kind:
  22363. case VertexBuffer.UV5Kind:
  22364. case VertexBuffer.UV6Kind:
  22365. stride = 2;
  22366. break;
  22367. case VertexBuffer.TangentKind:
  22368. case VertexBuffer.ColorKind:
  22369. stride = 4;
  22370. break;
  22371. case VertexBuffer.MatricesIndicesKind:
  22372. case VertexBuffer.MatricesIndicesExtraKind:
  22373. stride = 4;
  22374. break;
  22375. case VertexBuffer.MatricesWeightsKind:
  22376. case VertexBuffer.MatricesWeightsExtraKind:
  22377. stride = 4;
  22378. break;
  22379. }
  22380. }
  22381. if (data instanceof BABYLON.Buffer) {
  22382. if (!stride) {
  22383. stride = data.getStrideSize();
  22384. }
  22385. this._buffer = data;
  22386. this._ownsBuffer = false;
  22387. }
  22388. else {
  22389. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22390. this._ownsBuffer = true;
  22391. }
  22392. this._stride = stride;
  22393. this._offset = offset ? offset : 0;
  22394. this._size = size ? size : stride;
  22395. this._kind = kind;
  22396. }
  22397. /**
  22398. * Returns the kind of the VertexBuffer (string).
  22399. */
  22400. VertexBuffer.prototype.getKind = function () {
  22401. return this._kind;
  22402. };
  22403. // Properties
  22404. /**
  22405. * Boolean : is the VertexBuffer updatable ?
  22406. */
  22407. VertexBuffer.prototype.isUpdatable = function () {
  22408. return this._buffer.isUpdatable();
  22409. };
  22410. /**
  22411. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22412. */
  22413. VertexBuffer.prototype.getData = function () {
  22414. return this._buffer.getData();
  22415. };
  22416. /**
  22417. * Returns the WebGLBuffer associated to the VertexBuffer.
  22418. */
  22419. VertexBuffer.prototype.getBuffer = function () {
  22420. return this._buffer.getBuffer();
  22421. };
  22422. /**
  22423. * Returns the stride of the VertexBuffer (integer).
  22424. */
  22425. VertexBuffer.prototype.getStrideSize = function () {
  22426. return this._stride;
  22427. };
  22428. /**
  22429. * Returns the offset (integer).
  22430. */
  22431. VertexBuffer.prototype.getOffset = function () {
  22432. return this._offset;
  22433. };
  22434. /**
  22435. * Returns the VertexBuffer total size (integer).
  22436. */
  22437. VertexBuffer.prototype.getSize = function () {
  22438. return this._size;
  22439. };
  22440. /**
  22441. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22442. */
  22443. VertexBuffer.prototype.getIsInstanced = function () {
  22444. return this._buffer.getIsInstanced();
  22445. };
  22446. // Methods
  22447. /**
  22448. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22449. * Returns the created WebGLBuffer.
  22450. */
  22451. VertexBuffer.prototype.create = function (data) {
  22452. return this._buffer.create(data);
  22453. };
  22454. /**
  22455. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22456. * Returns the updated WebGLBuffer.
  22457. */
  22458. VertexBuffer.prototype.update = function (data) {
  22459. return this._buffer.update(data);
  22460. };
  22461. /**
  22462. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22463. * Returns the directly updated WebGLBuffer.
  22464. */
  22465. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22466. return this._buffer.updateDirectly(data, offset);
  22467. };
  22468. /**
  22469. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22470. */
  22471. VertexBuffer.prototype.dispose = function () {
  22472. if (this._ownsBuffer) {
  22473. this._buffer.dispose();
  22474. }
  22475. };
  22476. Object.defineProperty(VertexBuffer, "PositionKind", {
  22477. get: function () {
  22478. return VertexBuffer._PositionKind;
  22479. },
  22480. enumerable: true,
  22481. configurable: true
  22482. });
  22483. Object.defineProperty(VertexBuffer, "NormalKind", {
  22484. get: function () {
  22485. return VertexBuffer._NormalKind;
  22486. },
  22487. enumerable: true,
  22488. configurable: true
  22489. });
  22490. Object.defineProperty(VertexBuffer, "TangentKind", {
  22491. get: function () {
  22492. return VertexBuffer._TangentKind;
  22493. },
  22494. enumerable: true,
  22495. configurable: true
  22496. });
  22497. Object.defineProperty(VertexBuffer, "UVKind", {
  22498. get: function () {
  22499. return VertexBuffer._UVKind;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22505. get: function () {
  22506. return VertexBuffer._UV2Kind;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22512. get: function () {
  22513. return VertexBuffer._UV3Kind;
  22514. },
  22515. enumerable: true,
  22516. configurable: true
  22517. });
  22518. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22519. get: function () {
  22520. return VertexBuffer._UV4Kind;
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22526. get: function () {
  22527. return VertexBuffer._UV5Kind;
  22528. },
  22529. enumerable: true,
  22530. configurable: true
  22531. });
  22532. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22533. get: function () {
  22534. return VertexBuffer._UV6Kind;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. Object.defineProperty(VertexBuffer, "ColorKind", {
  22540. get: function () {
  22541. return VertexBuffer._ColorKind;
  22542. },
  22543. enumerable: true,
  22544. configurable: true
  22545. });
  22546. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22547. get: function () {
  22548. return VertexBuffer._MatricesIndicesKind;
  22549. },
  22550. enumerable: true,
  22551. configurable: true
  22552. });
  22553. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22554. get: function () {
  22555. return VertexBuffer._MatricesWeightsKind;
  22556. },
  22557. enumerable: true,
  22558. configurable: true
  22559. });
  22560. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22561. get: function () {
  22562. return VertexBuffer._MatricesIndicesExtraKind;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22568. get: function () {
  22569. return VertexBuffer._MatricesWeightsExtraKind;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. return VertexBuffer;
  22575. }());
  22576. // Enums
  22577. VertexBuffer._PositionKind = "position";
  22578. VertexBuffer._NormalKind = "normal";
  22579. VertexBuffer._TangentKind = "tangent";
  22580. VertexBuffer._UVKind = "uv";
  22581. VertexBuffer._UV2Kind = "uv2";
  22582. VertexBuffer._UV3Kind = "uv3";
  22583. VertexBuffer._UV4Kind = "uv4";
  22584. VertexBuffer._UV5Kind = "uv5";
  22585. VertexBuffer._UV6Kind = "uv6";
  22586. VertexBuffer._ColorKind = "color";
  22587. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22588. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22589. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22590. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22591. BABYLON.VertexBuffer = VertexBuffer;
  22592. })(BABYLON || (BABYLON = {}));
  22593. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22594. var BABYLON;
  22595. (function (BABYLON) {
  22596. /**
  22597. * Creates an instance based on a source mesh.
  22598. */
  22599. var InstancedMesh = (function (_super) {
  22600. __extends(InstancedMesh, _super);
  22601. function InstancedMesh(name, source) {
  22602. var _this = _super.call(this, name, source.getScene()) || this;
  22603. source.instances.push(_this);
  22604. _this._sourceMesh = source;
  22605. _this.position.copyFrom(source.position);
  22606. _this.rotation.copyFrom(source.rotation);
  22607. _this.scaling.copyFrom(source.scaling);
  22608. if (source.rotationQuaternion) {
  22609. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22610. }
  22611. _this.infiniteDistance = source.infiniteDistance;
  22612. _this.setPivotMatrix(source.getPivotMatrix());
  22613. _this.refreshBoundingInfo();
  22614. _this._syncSubMeshes();
  22615. return _this;
  22616. }
  22617. /**
  22618. * Returns the string "InstancedMesh".
  22619. */
  22620. InstancedMesh.prototype.getClassName = function () {
  22621. return "InstancedMesh";
  22622. };
  22623. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22624. // Methods
  22625. get: function () {
  22626. return this._sourceMesh.receiveShadows;
  22627. },
  22628. enumerable: true,
  22629. configurable: true
  22630. });
  22631. Object.defineProperty(InstancedMesh.prototype, "material", {
  22632. get: function () {
  22633. return this._sourceMesh.material;
  22634. },
  22635. enumerable: true,
  22636. configurable: true
  22637. });
  22638. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22639. get: function () {
  22640. return this._sourceMesh.visibility;
  22641. },
  22642. enumerable: true,
  22643. configurable: true
  22644. });
  22645. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22646. get: function () {
  22647. return this._sourceMesh.skeleton;
  22648. },
  22649. enumerable: true,
  22650. configurable: true
  22651. });
  22652. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22653. get: function () {
  22654. return this._sourceMesh.renderingGroupId;
  22655. },
  22656. enumerable: true,
  22657. configurable: true
  22658. });
  22659. /**
  22660. * Returns the total number of vertices (integer).
  22661. */
  22662. InstancedMesh.prototype.getTotalVertices = function () {
  22663. return this._sourceMesh.getTotalVertices();
  22664. };
  22665. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22666. get: function () {
  22667. return this._sourceMesh;
  22668. },
  22669. enumerable: true,
  22670. configurable: true
  22671. });
  22672. /**
  22673. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22674. */
  22675. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22676. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22677. };
  22678. /**
  22679. * Boolean : True if the mesh owns the requested kind of data.
  22680. */
  22681. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22682. return this._sourceMesh.isVerticesDataPresent(kind);
  22683. };
  22684. /**
  22685. * Returns an array of indices (IndicesArray).
  22686. */
  22687. InstancedMesh.prototype.getIndices = function () {
  22688. return this._sourceMesh.getIndices();
  22689. };
  22690. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22691. get: function () {
  22692. return this._sourceMesh._positions;
  22693. },
  22694. enumerable: true,
  22695. configurable: true
  22696. });
  22697. /**
  22698. * Sets a new updated BoundingInfo to the mesh.
  22699. * Returns the mesh.
  22700. */
  22701. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22702. var meshBB = this._sourceMesh.getBoundingInfo();
  22703. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22704. this._updateBoundingInfo();
  22705. return this;
  22706. };
  22707. InstancedMesh.prototype._preActivate = function () {
  22708. if (this._currentLOD) {
  22709. this._currentLOD._preActivate();
  22710. }
  22711. return this;
  22712. };
  22713. InstancedMesh.prototype._activate = function (renderId) {
  22714. if (this._currentLOD) {
  22715. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22716. }
  22717. return this;
  22718. };
  22719. /**
  22720. * Returns the current associated LOD AbstractMesh.
  22721. */
  22722. InstancedMesh.prototype.getLOD = function (camera) {
  22723. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22724. if (this._currentLOD === this.sourceMesh) {
  22725. return this;
  22726. }
  22727. return this._currentLOD;
  22728. };
  22729. InstancedMesh.prototype._syncSubMeshes = function () {
  22730. this.releaseSubMeshes();
  22731. if (this._sourceMesh.subMeshes) {
  22732. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22733. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22734. }
  22735. }
  22736. return this;
  22737. };
  22738. InstancedMesh.prototype._generatePointsArray = function () {
  22739. return this._sourceMesh._generatePointsArray();
  22740. };
  22741. /**
  22742. * Creates a new InstancedMesh from the current mesh.
  22743. * - name (string) : the cloned mesh name
  22744. * - newParent (optional Node) : the optional Node to parent the clone to.
  22745. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22746. *
  22747. * Returns the clone.
  22748. */
  22749. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22750. var result = this._sourceMesh.createInstance(name);
  22751. // Deep copy
  22752. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  22753. // Bounding info
  22754. this.refreshBoundingInfo();
  22755. // Parent
  22756. if (newParent) {
  22757. result.parent = newParent;
  22758. }
  22759. if (!doNotCloneChildren) {
  22760. // Children
  22761. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22762. var mesh = this.getScene().meshes[index];
  22763. if (mesh.parent === this) {
  22764. mesh.clone(mesh.name, result);
  22765. }
  22766. }
  22767. }
  22768. result.computeWorldMatrix(true);
  22769. return result;
  22770. };
  22771. /**
  22772. * Disposes the InstancedMesh.
  22773. * Returns nothing.
  22774. */
  22775. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22776. // Remove from mesh
  22777. var index = this._sourceMesh.instances.indexOf(this);
  22778. this._sourceMesh.instances.splice(index, 1);
  22779. _super.prototype.dispose.call(this, doNotRecurse);
  22780. };
  22781. return InstancedMesh;
  22782. }(BABYLON.AbstractMesh));
  22783. BABYLON.InstancedMesh = InstancedMesh;
  22784. })(BABYLON || (BABYLON = {}));
  22785. //# sourceMappingURL=babylon.instancedMesh.js.map
  22786. var BABYLON;
  22787. (function (BABYLON) {
  22788. var _InstancesBatch = (function () {
  22789. function _InstancesBatch() {
  22790. this.mustReturn = false;
  22791. this.visibleInstances = new Array();
  22792. this.renderSelf = new Array();
  22793. }
  22794. return _InstancesBatch;
  22795. }());
  22796. BABYLON._InstancesBatch = _InstancesBatch;
  22797. var Mesh = (function (_super) {
  22798. __extends(Mesh, _super);
  22799. /**
  22800. * @constructor
  22801. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22802. * @param {Scene} scene The scene to add this mesh to.
  22803. * @param {Node} parent The parent of this mesh, if it has one
  22804. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22805. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22806. * When false, achieved by calling a clone(), also passing False.
  22807. * This will make creation of children, recursive.
  22808. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22809. */
  22810. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22811. if (parent === void 0) { parent = null; }
  22812. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22813. var _this = _super.call(this, name, scene) || this;
  22814. // Events
  22815. /**
  22816. * An event triggered before rendering the mesh
  22817. * @type {BABYLON.Observable}
  22818. */
  22819. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22820. /**
  22821. * An event triggered after rendering the mesh
  22822. * @type {BABYLON.Observable}
  22823. */
  22824. _this.onAfterRenderObservable = new BABYLON.Observable();
  22825. /**
  22826. * An event triggered before drawing the mesh
  22827. * @type {BABYLON.Observable}
  22828. */
  22829. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22830. // Members
  22831. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22832. _this.instances = new Array();
  22833. _this._LODLevels = new Array();
  22834. _this._visibleInstances = {};
  22835. _this._renderIdForInstances = new Array();
  22836. _this._batchCache = new _InstancesBatch();
  22837. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22838. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22839. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22840. // Will be used to save a source mesh reference, If any
  22841. _this._source = null;
  22842. if (source) {
  22843. // Source mesh
  22844. _this._source = source;
  22845. // Geometry
  22846. if (source._geometry) {
  22847. source._geometry.applyToMesh(_this);
  22848. }
  22849. // Deep copy
  22850. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22851. // Parent
  22852. _this.parent = source.parent;
  22853. // Pivot
  22854. _this.setPivotMatrix(source.getPivotMatrix());
  22855. _this.id = name + "." + source.id;
  22856. // Material
  22857. _this.material = source.material;
  22858. var index;
  22859. if (!doNotCloneChildren) {
  22860. // Children
  22861. for (index = 0; index < scene.meshes.length; index++) {
  22862. var mesh = scene.meshes[index];
  22863. if (mesh.parent === source) {
  22864. // doNotCloneChildren is always going to be False
  22865. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22866. }
  22867. }
  22868. }
  22869. // Physics clone
  22870. var physicsEngine = _this.getScene().getPhysicsEngine();
  22871. if (clonePhysicsImpostor && physicsEngine) {
  22872. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22873. if (impostor) {
  22874. _this.physicsImpostor = impostor.clone(_this);
  22875. }
  22876. }
  22877. // Particles
  22878. for (index = 0; index < scene.particleSystems.length; index++) {
  22879. var system = scene.particleSystems[index];
  22880. if (system.emitter === source) {
  22881. system.clone(system.name, _this);
  22882. }
  22883. }
  22884. _this.computeWorldMatrix(true);
  22885. }
  22886. // Parent
  22887. if (parent !== null) {
  22888. _this.parent = parent;
  22889. }
  22890. return _this;
  22891. }
  22892. Object.defineProperty(Mesh, "FRONTSIDE", {
  22893. /**
  22894. * Mesh side orientation : usually the external or front surface
  22895. */
  22896. get: function () {
  22897. return Mesh._FRONTSIDE;
  22898. },
  22899. enumerable: true,
  22900. configurable: true
  22901. });
  22902. Object.defineProperty(Mesh, "BACKSIDE", {
  22903. /**
  22904. * Mesh side orientation : usually the internal or back surface
  22905. */
  22906. get: function () {
  22907. return Mesh._BACKSIDE;
  22908. },
  22909. enumerable: true,
  22910. configurable: true
  22911. });
  22912. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22913. /**
  22914. * Mesh side orientation : both internal and external or front and back surfaces
  22915. */
  22916. get: function () {
  22917. return Mesh._DOUBLESIDE;
  22918. },
  22919. enumerable: true,
  22920. configurable: true
  22921. });
  22922. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22923. /**
  22924. * Mesh side orientation : by default, `FRONTSIDE`
  22925. */
  22926. get: function () {
  22927. return Mesh._DEFAULTSIDE;
  22928. },
  22929. enumerable: true,
  22930. configurable: true
  22931. });
  22932. Object.defineProperty(Mesh, "NO_CAP", {
  22933. /**
  22934. * Mesh cap setting : no cap
  22935. */
  22936. get: function () {
  22937. return Mesh._NO_CAP;
  22938. },
  22939. enumerable: true,
  22940. configurable: true
  22941. });
  22942. Object.defineProperty(Mesh, "CAP_START", {
  22943. /**
  22944. * Mesh cap setting : one cap at the beginning of the mesh
  22945. */
  22946. get: function () {
  22947. return Mesh._CAP_START;
  22948. },
  22949. enumerable: true,
  22950. configurable: true
  22951. });
  22952. Object.defineProperty(Mesh, "CAP_END", {
  22953. /**
  22954. * Mesh cap setting : one cap at the end of the mesh
  22955. */
  22956. get: function () {
  22957. return Mesh._CAP_END;
  22958. },
  22959. enumerable: true,
  22960. configurable: true
  22961. });
  22962. Object.defineProperty(Mesh, "CAP_ALL", {
  22963. /**
  22964. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22965. */
  22966. get: function () {
  22967. return Mesh._CAP_ALL;
  22968. },
  22969. enumerable: true,
  22970. configurable: true
  22971. });
  22972. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22973. set: function (callback) {
  22974. if (this._onBeforeDrawObserver) {
  22975. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22976. }
  22977. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22978. },
  22979. enumerable: true,
  22980. configurable: true
  22981. });
  22982. Object.defineProperty(Mesh.prototype, "source", {
  22983. get: function () {
  22984. return this._source;
  22985. },
  22986. enumerable: true,
  22987. configurable: true
  22988. });
  22989. // Methods
  22990. /**
  22991. * Returns the string "Mesh".
  22992. */
  22993. Mesh.prototype.getClassName = function () {
  22994. return "Mesh";
  22995. };
  22996. /**
  22997. * Returns a string.
  22998. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22999. */
  23000. Mesh.prototype.toString = function (fullDetails) {
  23001. var ret = _super.prototype.toString.call(this, fullDetails);
  23002. ret += ", n vertices: " + this.getTotalVertices();
  23003. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23004. if (this.animations) {
  23005. for (var i = 0; i < this.animations.length; i++) {
  23006. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23007. }
  23008. }
  23009. if (fullDetails) {
  23010. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  23011. }
  23012. return ret;
  23013. };
  23014. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23015. /**
  23016. * True if the mesh has some Levels Of Details (LOD).
  23017. * Returns a boolean.
  23018. */
  23019. get: function () {
  23020. return this._LODLevels.length > 0;
  23021. },
  23022. enumerable: true,
  23023. configurable: true
  23024. });
  23025. Mesh.prototype._sortLODLevels = function () {
  23026. this._LODLevels.sort(function (a, b) {
  23027. if (a.distance < b.distance) {
  23028. return 1;
  23029. }
  23030. if (a.distance > b.distance) {
  23031. return -1;
  23032. }
  23033. return 0;
  23034. });
  23035. };
  23036. /**
  23037. * Add a mesh as LOD level triggered at the given distance.
  23038. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23039. * @param {number} distance The distance from the center of the object to show this level
  23040. * @param {Mesh} mesh The mesh to be added as LOD level
  23041. * @return {Mesh} This mesh (for chaining)
  23042. */
  23043. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23044. if (mesh && mesh._masterMesh) {
  23045. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23046. return this;
  23047. }
  23048. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23049. this._LODLevels.push(level);
  23050. if (mesh) {
  23051. mesh._masterMesh = this;
  23052. }
  23053. this._sortLODLevels();
  23054. return this;
  23055. };
  23056. /**
  23057. * Returns the LOD level mesh at the passed distance or null if not found.
  23058. * It is related to the method `addLODLevel(distance, mesh)`.
  23059. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23060. * Returns an object Mesh or `null`.
  23061. */
  23062. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23063. for (var index = 0; index < this._LODLevels.length; index++) {
  23064. var level = this._LODLevels[index];
  23065. if (level.distance === distance) {
  23066. return level.mesh;
  23067. }
  23068. }
  23069. return null;
  23070. };
  23071. /**
  23072. * Remove a mesh from the LOD array
  23073. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23074. * @param {Mesh} mesh The mesh to be removed.
  23075. * @return {Mesh} This mesh (for chaining)
  23076. */
  23077. Mesh.prototype.removeLODLevel = function (mesh) {
  23078. for (var index = 0; index < this._LODLevels.length; index++) {
  23079. if (this._LODLevels[index].mesh === mesh) {
  23080. this._LODLevels.splice(index, 1);
  23081. if (mesh) {
  23082. mesh._masterMesh = null;
  23083. }
  23084. }
  23085. }
  23086. this._sortLODLevels();
  23087. return this;
  23088. };
  23089. /**
  23090. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23091. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23092. */
  23093. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23094. if (!this._LODLevels || this._LODLevels.length === 0) {
  23095. return this;
  23096. }
  23097. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23098. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23099. if (this.onLODLevelSelection) {
  23100. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23101. }
  23102. return this;
  23103. }
  23104. for (var index = 0; index < this._LODLevels.length; index++) {
  23105. var level = this._LODLevels[index];
  23106. if (level.distance < distanceToCamera) {
  23107. if (level.mesh) {
  23108. level.mesh._preActivate();
  23109. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23110. }
  23111. if (this.onLODLevelSelection) {
  23112. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23113. }
  23114. return level.mesh;
  23115. }
  23116. }
  23117. if (this.onLODLevelSelection) {
  23118. this.onLODLevelSelection(distanceToCamera, this, this);
  23119. }
  23120. return this;
  23121. };
  23122. Object.defineProperty(Mesh.prototype, "geometry", {
  23123. /**
  23124. * Returns the mesh internal Geometry object.
  23125. */
  23126. get: function () {
  23127. return this._geometry;
  23128. },
  23129. enumerable: true,
  23130. configurable: true
  23131. });
  23132. /**
  23133. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23134. */
  23135. Mesh.prototype.getTotalVertices = function () {
  23136. if (!this._geometry) {
  23137. return 0;
  23138. }
  23139. return this._geometry.getTotalVertices();
  23140. };
  23141. /**
  23142. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23143. * 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.
  23144. * Returns null if the mesh has no geometry or no vertex buffer.
  23145. * Possible `kind` values :
  23146. * - BABYLON.VertexBuffer.PositionKind
  23147. * - BABYLON.VertexBuffer.UVKind
  23148. * - BABYLON.VertexBuffer.UV2Kind
  23149. * - BABYLON.VertexBuffer.UV3Kind
  23150. * - BABYLON.VertexBuffer.UV4Kind
  23151. * - BABYLON.VertexBuffer.UV5Kind
  23152. * - BABYLON.VertexBuffer.UV6Kind
  23153. * - BABYLON.VertexBuffer.ColorKind
  23154. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23155. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23156. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23157. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23158. */
  23159. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23160. if (!this._geometry) {
  23161. return null;
  23162. }
  23163. return this._geometry.getVerticesData(kind, copyWhenShared);
  23164. };
  23165. /**
  23166. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23167. * Returns `undefined` if the mesh has no geometry.
  23168. * Possible `kind` values :
  23169. * - BABYLON.VertexBuffer.PositionKind
  23170. * - BABYLON.VertexBuffer.UVKind
  23171. * - BABYLON.VertexBuffer.UV2Kind
  23172. * - BABYLON.VertexBuffer.UV3Kind
  23173. * - BABYLON.VertexBuffer.UV4Kind
  23174. * - BABYLON.VertexBuffer.UV5Kind
  23175. * - BABYLON.VertexBuffer.UV6Kind
  23176. * - BABYLON.VertexBuffer.ColorKind
  23177. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23178. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23179. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23180. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23181. */
  23182. Mesh.prototype.getVertexBuffer = function (kind) {
  23183. if (!this._geometry) {
  23184. return undefined;
  23185. }
  23186. return this._geometry.getVertexBuffer(kind);
  23187. };
  23188. /**
  23189. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23190. * Possible `kind` values :
  23191. * - BABYLON.VertexBuffer.PositionKind
  23192. * - BABYLON.VertexBuffer.UVKind
  23193. * - BABYLON.VertexBuffer.UV2Kind
  23194. * - BABYLON.VertexBuffer.UV3Kind
  23195. * - BABYLON.VertexBuffer.UV4Kind
  23196. * - BABYLON.VertexBuffer.UV5Kind
  23197. * - BABYLON.VertexBuffer.UV6Kind
  23198. * - BABYLON.VertexBuffer.ColorKind
  23199. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23200. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23201. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23202. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23203. */
  23204. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23205. if (!this._geometry) {
  23206. if (this._delayInfo) {
  23207. return this._delayInfo.indexOf(kind) !== -1;
  23208. }
  23209. return false;
  23210. }
  23211. return this._geometry.isVerticesDataPresent(kind);
  23212. };
  23213. /**
  23214. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23215. * Possible `kind` values :
  23216. * - BABYLON.VertexBuffer.PositionKind
  23217. * - BABYLON.VertexBuffer.UVKind
  23218. * - BABYLON.VertexBuffer.UV2Kind
  23219. * - BABYLON.VertexBuffer.UV3Kind
  23220. * - BABYLON.VertexBuffer.UV4Kind
  23221. * - BABYLON.VertexBuffer.UV5Kind
  23222. * - BABYLON.VertexBuffer.UV6Kind
  23223. * - BABYLON.VertexBuffer.ColorKind
  23224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23228. */
  23229. Mesh.prototype.getVerticesDataKinds = function () {
  23230. if (!this._geometry) {
  23231. var result = [];
  23232. if (this._delayInfo) {
  23233. this._delayInfo.forEach(function (kind, index, array) {
  23234. result.push(kind);
  23235. });
  23236. }
  23237. return result;
  23238. }
  23239. return this._geometry.getVerticesDataKinds();
  23240. };
  23241. /**
  23242. * Returns a positive integer : the total number of indices in this mesh geometry.
  23243. * Returns zero if the mesh has no geometry.
  23244. */
  23245. Mesh.prototype.getTotalIndices = function () {
  23246. if (!this._geometry) {
  23247. return 0;
  23248. }
  23249. return this._geometry.getTotalIndices();
  23250. };
  23251. /**
  23252. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23253. * 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.
  23254. * Returns an empty array if the mesh has no geometry.
  23255. */
  23256. Mesh.prototype.getIndices = function (copyWhenShared) {
  23257. if (!this._geometry) {
  23258. return [];
  23259. }
  23260. return this._geometry.getIndices(copyWhenShared);
  23261. };
  23262. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23263. get: function () {
  23264. return this._masterMesh !== null && this._masterMesh !== undefined;
  23265. },
  23266. enumerable: true,
  23267. configurable: true
  23268. });
  23269. /**
  23270. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23271. */
  23272. Mesh.prototype.isReady = function () {
  23273. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23274. return false;
  23275. }
  23276. return _super.prototype.isReady.call(this);
  23277. };
  23278. /**
  23279. * Boolean : true if the mesh has been disposed.
  23280. */
  23281. Mesh.prototype.isDisposed = function () {
  23282. return this._isDisposed;
  23283. };
  23284. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23285. get: function () {
  23286. return this._sideOrientation;
  23287. },
  23288. /**
  23289. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23290. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23291. */
  23292. set: function (sideO) {
  23293. this._sideOrientation = sideO;
  23294. },
  23295. enumerable: true,
  23296. configurable: true
  23297. });
  23298. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23299. /**
  23300. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23301. * This property is pertinent only for updatable parametric shapes.
  23302. */
  23303. get: function () {
  23304. return this._areNormalsFrozen;
  23305. },
  23306. enumerable: true,
  23307. configurable: true
  23308. });
  23309. /**
  23310. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23311. * It has no effect at all on other shapes.
  23312. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23313. * Returns the Mesh.
  23314. */
  23315. Mesh.prototype.freezeNormals = function () {
  23316. this._areNormalsFrozen = true;
  23317. return this;
  23318. };
  23319. /**
  23320. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23321. * It has no effect at all on other shapes.
  23322. * It reactivates the mesh normals computation if it was previously frozen.
  23323. * Returns the Mesh.
  23324. */
  23325. Mesh.prototype.unfreezeNormals = function () {
  23326. this._areNormalsFrozen = false;
  23327. return this;
  23328. };
  23329. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23330. /**
  23331. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23332. */
  23333. set: function (count) {
  23334. this._overridenInstanceCount = count;
  23335. },
  23336. enumerable: true,
  23337. configurable: true
  23338. });
  23339. // Methods
  23340. Mesh.prototype._preActivate = function () {
  23341. var sceneRenderId = this.getScene().getRenderId();
  23342. if (this._preActivateId === sceneRenderId) {
  23343. return this;
  23344. }
  23345. this._preActivateId = sceneRenderId;
  23346. this._visibleInstances = null;
  23347. return this;
  23348. };
  23349. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23350. if (this._visibleInstances) {
  23351. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23352. }
  23353. return this;
  23354. };
  23355. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23356. if (!this._visibleInstances) {
  23357. this._visibleInstances = {};
  23358. this._visibleInstances.defaultRenderId = renderId;
  23359. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23360. }
  23361. if (!this._visibleInstances[renderId]) {
  23362. this._visibleInstances[renderId] = new Array();
  23363. }
  23364. this._visibleInstances[renderId].push(instance);
  23365. return this;
  23366. };
  23367. /**
  23368. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23369. * This means the mesh underlying bounding box and sphere are recomputed.
  23370. * Returns the Mesh.
  23371. */
  23372. Mesh.prototype.refreshBoundingInfo = function () {
  23373. if (this._boundingInfo.isLocked) {
  23374. return;
  23375. }
  23376. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23377. if (data) {
  23378. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23379. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23380. }
  23381. if (this.subMeshes) {
  23382. for (var index = 0; index < this.subMeshes.length; index++) {
  23383. this.subMeshes[index].refreshBoundingInfo();
  23384. }
  23385. }
  23386. this._updateBoundingInfo();
  23387. return this;
  23388. };
  23389. Mesh.prototype._createGlobalSubMesh = function () {
  23390. var totalVertices = this.getTotalVertices();
  23391. if (!totalVertices || !this.getIndices()) {
  23392. return null;
  23393. }
  23394. this.releaseSubMeshes();
  23395. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23396. };
  23397. Mesh.prototype.subdivide = function (count) {
  23398. if (count < 1) {
  23399. return;
  23400. }
  23401. var totalIndices = this.getTotalIndices();
  23402. var subdivisionSize = (totalIndices / count) | 0;
  23403. var offset = 0;
  23404. // Ensure that subdivisionSize is a multiple of 3
  23405. while (subdivisionSize % 3 !== 0) {
  23406. subdivisionSize++;
  23407. }
  23408. this.releaseSubMeshes();
  23409. for (var index = 0; index < count; index++) {
  23410. if (offset >= totalIndices) {
  23411. break;
  23412. }
  23413. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23414. offset += subdivisionSize;
  23415. }
  23416. this.synchronizeInstances();
  23417. };
  23418. /**
  23419. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23420. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23421. * The `data` are either a numeric array either a Float32Array.
  23422. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23423. * 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).
  23424. * Note that a new underlying VertexBuffer object is created each call.
  23425. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23426. *
  23427. * Possible `kind` values :
  23428. * - BABYLON.VertexBuffer.PositionKind
  23429. * - BABYLON.VertexBuffer.UVKind
  23430. * - BABYLON.VertexBuffer.UV2Kind
  23431. * - BABYLON.VertexBuffer.UV3Kind
  23432. * - BABYLON.VertexBuffer.UV4Kind
  23433. * - BABYLON.VertexBuffer.UV5Kind
  23434. * - BABYLON.VertexBuffer.UV6Kind
  23435. * - BABYLON.VertexBuffer.ColorKind
  23436. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23437. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23438. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23439. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23440. *
  23441. * Returns the Mesh.
  23442. */
  23443. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23444. if (!this._geometry) {
  23445. var vertexData = new BABYLON.VertexData();
  23446. vertexData.set(data, kind);
  23447. var scene = this.getScene();
  23448. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23449. }
  23450. else {
  23451. this._geometry.setVerticesData(kind, data, updatable, stride);
  23452. }
  23453. return this;
  23454. };
  23455. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23456. if (updatable === void 0) { updatable = true; }
  23457. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23458. return;
  23459. }
  23460. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23461. };
  23462. /**
  23463. * Sets the mesh VertexBuffer.
  23464. * Returns the Mesh.
  23465. */
  23466. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23467. if (!this._geometry) {
  23468. var scene = this.getScene();
  23469. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  23470. }
  23471. this._geometry.setVerticesBuffer(buffer);
  23472. return this;
  23473. };
  23474. /**
  23475. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23476. * If the mesh has no geometry, it is simply returned as it is.
  23477. * The `data` are either a numeric array either a Float32Array.
  23478. * No new underlying VertexBuffer object is created.
  23479. * 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.
  23480. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23481. *
  23482. * Possible `kind` values :
  23483. * - BABYLON.VertexBuffer.PositionKind
  23484. * - BABYLON.VertexBuffer.UVKind
  23485. * - BABYLON.VertexBuffer.UV2Kind
  23486. * - BABYLON.VertexBuffer.UV3Kind
  23487. * - BABYLON.VertexBuffer.UV4Kind
  23488. * - BABYLON.VertexBuffer.UV5Kind
  23489. * - BABYLON.VertexBuffer.UV6Kind
  23490. * - BABYLON.VertexBuffer.ColorKind
  23491. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23492. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23493. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23494. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23495. *
  23496. * Returns the Mesh.
  23497. */
  23498. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23499. if (!this._geometry) {
  23500. return;
  23501. }
  23502. if (!makeItUnique) {
  23503. this._geometry.updateVerticesData(kind, data, updateExtends);
  23504. }
  23505. else {
  23506. this.makeGeometryUnique();
  23507. this.updateVerticesData(kind, data, updateExtends, false);
  23508. }
  23509. return this;
  23510. };
  23511. /**
  23512. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23513. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23514. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23515. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23516. * Returns the Mesh.
  23517. */
  23518. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23519. if (computeNormals === void 0) { computeNormals = true; }
  23520. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23521. positionFunction(positions);
  23522. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23523. if (computeNormals) {
  23524. var indices = this.getIndices();
  23525. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23526. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23527. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23528. }
  23529. return this;
  23530. };
  23531. /**
  23532. * Creates a un-shared specific occurence of the geometry for the mesh.
  23533. * Returns the Mesh.
  23534. */
  23535. Mesh.prototype.makeGeometryUnique = function () {
  23536. if (!this._geometry) {
  23537. return;
  23538. }
  23539. var oldGeometry = this._geometry;
  23540. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23541. oldGeometry.releaseForMesh(this, true);
  23542. geometry.applyToMesh(this);
  23543. return this;
  23544. };
  23545. /**
  23546. * Sets the mesh indices.
  23547. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23548. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23549. * This method creates a new index buffer each call.
  23550. * Returns the Mesh.
  23551. */
  23552. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23553. if (!this._geometry) {
  23554. var vertexData = new BABYLON.VertexData();
  23555. vertexData.indices = indices;
  23556. var scene = this.getScene();
  23557. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23558. }
  23559. else {
  23560. this._geometry.setIndices(indices, totalVertices);
  23561. }
  23562. return this;
  23563. };
  23564. /**
  23565. * Invert the geometry to move from a right handed system to a left handed one.
  23566. * Returns the Mesh.
  23567. */
  23568. Mesh.prototype.toLeftHanded = function () {
  23569. if (!this._geometry) {
  23570. return;
  23571. }
  23572. this._geometry.toLeftHanded();
  23573. return this;
  23574. };
  23575. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23576. var engine = this.getScene().getEngine();
  23577. // Wireframe
  23578. var indexToBind;
  23579. if (this._unIndexed) {
  23580. indexToBind = null;
  23581. }
  23582. else {
  23583. switch (fillMode) {
  23584. case BABYLON.Material.PointFillMode:
  23585. indexToBind = null;
  23586. break;
  23587. case BABYLON.Material.WireFrameFillMode:
  23588. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23589. break;
  23590. default:
  23591. case BABYLON.Material.TriangleFillMode:
  23592. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23593. break;
  23594. }
  23595. }
  23596. // VBOs
  23597. this._geometry._bind(effect, indexToBind);
  23598. return this;
  23599. };
  23600. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23601. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23602. return this;
  23603. }
  23604. this.onBeforeDrawObservable.notifyObservers(this);
  23605. var engine = this.getScene().getEngine();
  23606. // Draw order
  23607. switch (fillMode) {
  23608. case BABYLON.Material.PointFillMode:
  23609. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23610. break;
  23611. case BABYLON.Material.WireFrameFillMode:
  23612. if (this._unIndexed) {
  23613. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23614. }
  23615. else {
  23616. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23617. }
  23618. break;
  23619. default:
  23620. if (this._unIndexed) {
  23621. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23622. }
  23623. else {
  23624. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23625. }
  23626. }
  23627. return this;
  23628. };
  23629. /**
  23630. * Registers for this mesh a javascript function called just before the rendering process.
  23631. * This function is passed the current mesh.
  23632. * Return the Mesh.
  23633. */
  23634. Mesh.prototype.registerBeforeRender = function (func) {
  23635. this.onBeforeRenderObservable.add(func);
  23636. return this;
  23637. };
  23638. /**
  23639. * Disposes a previously registered javascript function called before the rendering.
  23640. * This function is passed the current mesh.
  23641. * Returns the Mesh.
  23642. */
  23643. Mesh.prototype.unregisterBeforeRender = function (func) {
  23644. this.onBeforeRenderObservable.removeCallback(func);
  23645. return this;
  23646. };
  23647. /**
  23648. * Registers for this mesh a javascript function called just after the rendering is complete.
  23649. * This function is passed the current mesh.
  23650. * Returns the Mesh.
  23651. */
  23652. Mesh.prototype.registerAfterRender = function (func) {
  23653. this.onAfterRenderObservable.add(func);
  23654. return this;
  23655. };
  23656. /**
  23657. * Disposes a previously registered javascript function called after the rendering.
  23658. * This function is passed the current mesh.
  23659. * Return the Mesh.
  23660. */
  23661. Mesh.prototype.unregisterAfterRender = function (func) {
  23662. this.onAfterRenderObservable.removeCallback(func);
  23663. return this;
  23664. };
  23665. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23666. var scene = this.getScene();
  23667. this._batchCache.mustReturn = false;
  23668. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23669. this._batchCache.visibleInstances[subMeshId] = null;
  23670. if (this._visibleInstances) {
  23671. var currentRenderId = scene.getRenderId();
  23672. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23673. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23674. var selfRenderId = this._renderId;
  23675. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23676. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23677. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23678. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23679. }
  23680. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23681. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23682. this._batchCache.mustReturn = true;
  23683. return this._batchCache;
  23684. }
  23685. if (currentRenderId !== selfRenderId) {
  23686. this._batchCache.renderSelf[subMeshId] = false;
  23687. }
  23688. }
  23689. this._renderIdForInstances[subMeshId] = currentRenderId;
  23690. }
  23691. return this._batchCache;
  23692. };
  23693. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23694. var visibleInstances = batch.visibleInstances[subMesh._id];
  23695. var matricesCount = visibleInstances.length + 1;
  23696. var bufferSize = matricesCount * 16 * 4;
  23697. var currentInstancesBufferSize = this._instancesBufferSize;
  23698. var instancesBuffer = this._instancesBuffer;
  23699. while (this._instancesBufferSize < bufferSize) {
  23700. this._instancesBufferSize *= 2;
  23701. }
  23702. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23703. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23704. }
  23705. var offset = 0;
  23706. var instancesCount = 0;
  23707. var world = this.getWorldMatrix();
  23708. if (batch.renderSelf[subMesh._id]) {
  23709. world.copyToArray(this._instancesData, offset);
  23710. offset += 16;
  23711. instancesCount++;
  23712. }
  23713. if (visibleInstances) {
  23714. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23715. var instance = visibleInstances[instanceIndex];
  23716. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23717. offset += 16;
  23718. instancesCount++;
  23719. }
  23720. }
  23721. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23722. if (instancesBuffer) {
  23723. instancesBuffer.dispose();
  23724. }
  23725. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23726. this._instancesBuffer = instancesBuffer;
  23727. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23728. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23729. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23730. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23731. }
  23732. else {
  23733. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23734. }
  23735. this.geometry._bind(effect);
  23736. this._draw(subMesh, fillMode, instancesCount);
  23737. engine.unbindInstanceAttributes();
  23738. return this;
  23739. };
  23740. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23741. var scene = this.getScene();
  23742. var engine = scene.getEngine();
  23743. if (hardwareInstancedRendering) {
  23744. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23745. }
  23746. else {
  23747. if (batch.renderSelf[subMesh._id]) {
  23748. // Draw
  23749. if (onBeforeDraw) {
  23750. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23751. }
  23752. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23753. }
  23754. if (batch.visibleInstances[subMesh._id]) {
  23755. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23756. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23757. // World
  23758. var world = instance.getWorldMatrix();
  23759. if (onBeforeDraw) {
  23760. onBeforeDraw(true, world, effectiveMaterial);
  23761. }
  23762. // Draw
  23763. this._draw(subMesh, fillMode);
  23764. }
  23765. }
  23766. }
  23767. return this;
  23768. };
  23769. /**
  23770. * Triggers the draw call for the mesh.
  23771. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23772. * Returns the Mesh.
  23773. */
  23774. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23775. var scene = this.getScene();
  23776. // Managing instances
  23777. var batch = this._getInstancesRenderList(subMesh._id);
  23778. if (batch.mustReturn) {
  23779. return this;
  23780. }
  23781. // Checking geometry state
  23782. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23783. return this;
  23784. }
  23785. var callbackIndex;
  23786. this.onBeforeRenderObservable.notifyObservers(this);
  23787. var engine = scene.getEngine();
  23788. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23789. // Material
  23790. var effectiveMaterial = subMesh.getMaterial();
  23791. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23792. return this;
  23793. }
  23794. // Outline - step 1
  23795. var savedDepthWrite = engine.getDepthWrite();
  23796. if (this.renderOutline) {
  23797. engine.setDepthWrite(false);
  23798. scene.getOutlineRenderer().render(subMesh, batch);
  23799. engine.setDepthWrite(savedDepthWrite);
  23800. }
  23801. effectiveMaterial._preBind();
  23802. var effect = effectiveMaterial.getEffect();
  23803. // Bind
  23804. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23805. this._bind(subMesh, effect, fillMode);
  23806. var world = this.getWorldMatrix();
  23807. effectiveMaterial.bind(world, this);
  23808. // Alpha mode
  23809. if (enableAlphaMode) {
  23810. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23811. }
  23812. // Draw
  23813. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23814. // Unbind
  23815. effectiveMaterial.unbind();
  23816. // Outline - step 2
  23817. if (this.renderOutline && savedDepthWrite) {
  23818. engine.setDepthWrite(true);
  23819. engine.setColorWrite(false);
  23820. scene.getOutlineRenderer().render(subMesh, batch);
  23821. engine.setColorWrite(true);
  23822. }
  23823. // Overlay
  23824. if (this.renderOverlay) {
  23825. var currentMode = engine.getAlphaMode();
  23826. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23827. scene.getOutlineRenderer().render(subMesh, batch, true);
  23828. engine.setAlphaMode(currentMode);
  23829. }
  23830. this.onAfterRenderObservable.notifyObservers(this);
  23831. return this;
  23832. };
  23833. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23834. if (isInstance) {
  23835. effectiveMaterial.bindOnlyWorldMatrix(world);
  23836. }
  23837. return this;
  23838. };
  23839. /**
  23840. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23841. */
  23842. Mesh.prototype.getEmittedParticleSystems = function () {
  23843. var results = new Array();
  23844. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23845. var particleSystem = this.getScene().particleSystems[index];
  23846. if (particleSystem.emitter === this) {
  23847. results.push(particleSystem);
  23848. }
  23849. }
  23850. return results;
  23851. };
  23852. /**
  23853. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23854. */
  23855. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23856. var results = new Array();
  23857. var descendants = this.getDescendants();
  23858. descendants.push(this);
  23859. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23860. var particleSystem = this.getScene().particleSystems[index];
  23861. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23862. results.push(particleSystem);
  23863. }
  23864. }
  23865. return results;
  23866. };
  23867. Mesh.prototype._checkDelayState = function () {
  23868. var scene = this.getScene();
  23869. if (this._geometry) {
  23870. this._geometry.load(scene);
  23871. }
  23872. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23873. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23874. this._queueLoad(this, scene);
  23875. }
  23876. return this;
  23877. };
  23878. Mesh.prototype._queueLoad = function (mesh, scene) {
  23879. var _this = this;
  23880. scene._addPendingData(mesh);
  23881. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23882. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23883. if (data instanceof ArrayBuffer) {
  23884. _this._delayLoadingFunction(data, _this);
  23885. }
  23886. else {
  23887. _this._delayLoadingFunction(JSON.parse(data), _this);
  23888. }
  23889. _this.instances.forEach(function (instance) {
  23890. instance._syncSubMeshes();
  23891. });
  23892. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23893. scene._removePendingData(_this);
  23894. }, function () { }, scene.database, getBinaryData);
  23895. return this;
  23896. };
  23897. /**
  23898. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23899. */
  23900. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23901. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23902. return false;
  23903. }
  23904. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23905. return false;
  23906. }
  23907. this._checkDelayState();
  23908. return true;
  23909. };
  23910. /**
  23911. * Sets the mesh material by the material or multiMaterial `id` property.
  23912. * The material `id` is a string identifying the material or the multiMaterial.
  23913. * This method returns the Mesh.
  23914. */
  23915. Mesh.prototype.setMaterialByID = function (id) {
  23916. var materials = this.getScene().materials;
  23917. var index;
  23918. for (index = 0; index < materials.length; index++) {
  23919. if (materials[index].id === id) {
  23920. this.material = materials[index];
  23921. return this;
  23922. }
  23923. }
  23924. // Multi
  23925. var multiMaterials = this.getScene().multiMaterials;
  23926. for (index = 0; index < multiMaterials.length; index++) {
  23927. if (multiMaterials[index].id === id) {
  23928. this.material = multiMaterials[index];
  23929. return this;
  23930. }
  23931. }
  23932. return this;
  23933. };
  23934. /**
  23935. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23936. */
  23937. Mesh.prototype.getAnimatables = function () {
  23938. var results = [];
  23939. if (this.material) {
  23940. results.push(this.material);
  23941. }
  23942. if (this.skeleton) {
  23943. results.push(this.skeleton);
  23944. }
  23945. return results;
  23946. };
  23947. /**
  23948. * Modifies the mesh geometry according to the passed transformation matrix.
  23949. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23950. * The mesh normals are modified accordingly the same transformation.
  23951. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23952. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23953. * Returns the Mesh.
  23954. */
  23955. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23956. // Position
  23957. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23958. return this;
  23959. }
  23960. var submeshes = this.subMeshes.splice(0);
  23961. this._resetPointsArrayCache();
  23962. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23963. var temp = [];
  23964. var index;
  23965. for (index = 0; index < data.length; index += 3) {
  23966. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23967. }
  23968. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23969. // Normals
  23970. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23971. return this;
  23972. }
  23973. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23974. temp = [];
  23975. for (index = 0; index < data.length; index += 3) {
  23976. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23977. }
  23978. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23979. // flip faces?
  23980. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23981. this.flipFaces();
  23982. }
  23983. // Restore submeshes
  23984. this.releaseSubMeshes();
  23985. this.subMeshes = submeshes;
  23986. return this;
  23987. };
  23988. /**
  23989. * Modifies the mesh geometry according to its own current World Matrix.
  23990. * The mesh World Matrix is then reset.
  23991. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23992. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23993. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23994. * Returns the Mesh.
  23995. */
  23996. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23997. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23998. this.scaling.copyFromFloats(1, 1, 1);
  23999. this.position.copyFromFloats(0, 0, 0);
  24000. this.rotation.copyFromFloats(0, 0, 0);
  24001. //only if quaternion is already set
  24002. if (this.rotationQuaternion) {
  24003. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24004. }
  24005. this._worldMatrix = BABYLON.Matrix.Identity();
  24006. return this;
  24007. };
  24008. // Cache
  24009. Mesh.prototype._resetPointsArrayCache = function () {
  24010. this._positions = null;
  24011. return this;
  24012. };
  24013. Mesh.prototype._generatePointsArray = function () {
  24014. if (this._positions)
  24015. return true;
  24016. this._positions = [];
  24017. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24018. if (!data) {
  24019. return false;
  24020. }
  24021. for (var index = 0; index < data.length; index += 3) {
  24022. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  24023. }
  24024. return true;
  24025. };
  24026. /**
  24027. * Returns a new Mesh object generated from the current mesh properties.
  24028. * This method must not get confused with createInstance().
  24029. * The parameter `name` is a string, the name given to the new mesh.
  24030. * The optional parameter `newParent` can be any Node object (default `null`).
  24031. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24032. * 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.
  24033. */
  24034. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24035. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24036. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24037. };
  24038. /**
  24039. * Disposes the mesh.
  24040. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  24041. */
  24042. Mesh.prototype.dispose = function (doNotRecurse) {
  24043. var _this = this;
  24044. if (this._geometry) {
  24045. this._geometry.releaseForMesh(this, true);
  24046. }
  24047. // Sources
  24048. var meshes = this.getScene().meshes;
  24049. meshes.forEach(function (mesh) {
  24050. if (mesh._source && mesh._source === _this) {
  24051. mesh._source = null;
  24052. }
  24053. });
  24054. this._source = null;
  24055. // Instances
  24056. if (this._instancesBuffer) {
  24057. this._instancesBuffer.dispose();
  24058. this._instancesBuffer = null;
  24059. }
  24060. while (this.instances.length) {
  24061. this.instances[0].dispose();
  24062. }
  24063. // Highlight layers.
  24064. var highlightLayers = this.getScene().highlightLayers;
  24065. for (var i = 0; i < highlightLayers.length; i++) {
  24066. var highlightLayer = highlightLayers[i];
  24067. if (highlightLayer) {
  24068. highlightLayer.removeMesh(this);
  24069. highlightLayer.removeExcludedMesh(this);
  24070. }
  24071. }
  24072. _super.prototype.dispose.call(this, doNotRecurse);
  24073. };
  24074. /**
  24075. * Modifies the mesh geometry according to a displacement map.
  24076. * 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.
  24077. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24078. * This method returns nothing.
  24079. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24080. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24081. * 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.
  24082. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24083. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24084. *
  24085. * Returns the Mesh.
  24086. */
  24087. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24088. var _this = this;
  24089. var scene = this.getScene();
  24090. var onload = function (img) {
  24091. // Getting height map data
  24092. var canvas = document.createElement("canvas");
  24093. var context = canvas.getContext("2d");
  24094. var heightMapWidth = img.width;
  24095. var heightMapHeight = img.height;
  24096. canvas.width = heightMapWidth;
  24097. canvas.height = heightMapHeight;
  24098. context.drawImage(img, 0, 0);
  24099. // Create VertexData from map data
  24100. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24101. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24102. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24103. //execute success callback, if set
  24104. if (onSuccess) {
  24105. onSuccess(_this);
  24106. }
  24107. };
  24108. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24109. return this;
  24110. };
  24111. /**
  24112. * Modifies the mesh geometry according to a displacementMap buffer.
  24113. * 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.
  24114. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24115. * This method returns nothing.
  24116. * 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.
  24117. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24118. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24119. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24120. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24121. *
  24122. * Returns the Mesh.
  24123. */
  24124. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24125. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24126. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24127. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24128. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24129. return this;
  24130. }
  24131. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24132. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24133. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24134. var position = BABYLON.Vector3.Zero();
  24135. var normal = BABYLON.Vector3.Zero();
  24136. var uv = BABYLON.Vector2.Zero();
  24137. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24138. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24139. for (var index = 0; index < positions.length; index += 3) {
  24140. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24141. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24142. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24143. // Compute height
  24144. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24145. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24146. var pos = (u + v * heightMapWidth) * 4;
  24147. var r = buffer[pos] / 255.0;
  24148. var g = buffer[pos + 1] / 255.0;
  24149. var b = buffer[pos + 2] / 255.0;
  24150. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24151. normal.normalize();
  24152. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24153. position = position.add(normal);
  24154. position.toArray(positions, index);
  24155. }
  24156. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24157. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24158. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24159. return this;
  24160. };
  24161. /**
  24162. * Modify the mesh to get a flat shading rendering.
  24163. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24164. * This method returns the Mesh.
  24165. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24166. */
  24167. Mesh.prototype.convertToFlatShadedMesh = function () {
  24168. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24169. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24170. var kinds = this.getVerticesDataKinds();
  24171. var vbs = [];
  24172. var data = [];
  24173. var newdata = [];
  24174. var updatableNormals = false;
  24175. var kindIndex;
  24176. var kind;
  24177. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24178. kind = kinds[kindIndex];
  24179. var vertexBuffer = this.getVertexBuffer(kind);
  24180. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24181. updatableNormals = vertexBuffer.isUpdatable();
  24182. kinds.splice(kindIndex, 1);
  24183. kindIndex--;
  24184. continue;
  24185. }
  24186. vbs[kind] = vertexBuffer;
  24187. data[kind] = vbs[kind].getData();
  24188. newdata[kind] = [];
  24189. }
  24190. // Save previous submeshes
  24191. var previousSubmeshes = this.subMeshes.slice(0);
  24192. var indices = this.getIndices();
  24193. var totalIndices = this.getTotalIndices();
  24194. // Generating unique vertices per face
  24195. var index;
  24196. for (index = 0; index < totalIndices; index++) {
  24197. var vertexIndex = indices[index];
  24198. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24199. kind = kinds[kindIndex];
  24200. var stride = vbs[kind].getStrideSize();
  24201. for (var offset = 0; offset < stride; offset++) {
  24202. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24203. }
  24204. }
  24205. }
  24206. // Updating faces & normal
  24207. var normals = [];
  24208. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24209. for (index = 0; index < totalIndices; index += 3) {
  24210. indices[index] = index;
  24211. indices[index + 1] = index + 1;
  24212. indices[index + 2] = index + 2;
  24213. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24214. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24215. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24216. var p1p2 = p1.subtract(p2);
  24217. var p3p2 = p3.subtract(p2);
  24218. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24219. // Store same normals for every vertex
  24220. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24221. normals.push(normal.x);
  24222. normals.push(normal.y);
  24223. normals.push(normal.z);
  24224. }
  24225. }
  24226. this.setIndices(indices);
  24227. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24228. // Updating vertex buffers
  24229. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24230. kind = kinds[kindIndex];
  24231. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24232. }
  24233. // Updating submeshes
  24234. this.releaseSubMeshes();
  24235. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24236. var previousOne = previousSubmeshes[submeshIndex];
  24237. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24238. }
  24239. this.synchronizeInstances();
  24240. return this;
  24241. };
  24242. /**
  24243. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24244. * In other words, more vertices, no more indices and a single bigger VBO.
  24245. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24246. * Returns the Mesh.
  24247. */
  24248. Mesh.prototype.convertToUnIndexedMesh = function () {
  24249. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24250. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24251. var kinds = this.getVerticesDataKinds();
  24252. var vbs = [];
  24253. var data = [];
  24254. var newdata = [];
  24255. var updatableNormals = false;
  24256. var kindIndex;
  24257. var kind;
  24258. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24259. kind = kinds[kindIndex];
  24260. var vertexBuffer = this.getVertexBuffer(kind);
  24261. vbs[kind] = vertexBuffer;
  24262. data[kind] = vbs[kind].getData();
  24263. newdata[kind] = [];
  24264. }
  24265. // Save previous submeshes
  24266. var previousSubmeshes = this.subMeshes.slice(0);
  24267. var indices = this.getIndices();
  24268. var totalIndices = this.getTotalIndices();
  24269. // Generating unique vertices per face
  24270. var index;
  24271. for (index = 0; index < totalIndices; index++) {
  24272. var vertexIndex = indices[index];
  24273. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24274. kind = kinds[kindIndex];
  24275. var stride = vbs[kind].getStrideSize();
  24276. for (var offset = 0; offset < stride; offset++) {
  24277. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24278. }
  24279. }
  24280. }
  24281. // Updating indices
  24282. for (index = 0; index < totalIndices; index += 3) {
  24283. indices[index] = index;
  24284. indices[index + 1] = index + 1;
  24285. indices[index + 2] = index + 2;
  24286. }
  24287. this.setIndices(indices);
  24288. // Updating vertex buffers
  24289. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24290. kind = kinds[kindIndex];
  24291. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24292. }
  24293. // Updating submeshes
  24294. this.releaseSubMeshes();
  24295. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24296. var previousOne = previousSubmeshes[submeshIndex];
  24297. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24298. }
  24299. this._unIndexed = true;
  24300. this.synchronizeInstances();
  24301. return this;
  24302. };
  24303. /**
  24304. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24305. * This method returns the Mesh.
  24306. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24307. */
  24308. Mesh.prototype.flipFaces = function (flipNormals) {
  24309. if (flipNormals === void 0) { flipNormals = false; }
  24310. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24311. var i;
  24312. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24313. for (i = 0; i < vertex_data.normals.length; i++) {
  24314. vertex_data.normals[i] *= -1;
  24315. }
  24316. }
  24317. var temp;
  24318. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24319. // reassign indices
  24320. temp = vertex_data.indices[i + 1];
  24321. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24322. vertex_data.indices[i + 2] = temp;
  24323. }
  24324. vertex_data.applyToMesh(this);
  24325. return this;
  24326. };
  24327. // Instances
  24328. /**
  24329. * Creates a new InstancedMesh object from the mesh model.
  24330. * An instance shares the same properties and the same material than its model.
  24331. * Only these properties of each instance can then be set individually :
  24332. * - position
  24333. * - rotation
  24334. * - rotationQuaternion
  24335. * - setPivotMatrix
  24336. * - scaling
  24337. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24338. * Warning : this method is not supported for Line mesh and LineSystem
  24339. */
  24340. Mesh.prototype.createInstance = function (name) {
  24341. return new BABYLON.InstancedMesh(name, this);
  24342. };
  24343. /**
  24344. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24345. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24346. * This method returns the Mesh.
  24347. */
  24348. Mesh.prototype.synchronizeInstances = function () {
  24349. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24350. var instance = this.instances[instanceIndex];
  24351. instance._syncSubMeshes();
  24352. }
  24353. return this;
  24354. };
  24355. /**
  24356. * Simplify the mesh according to the given array of settings.
  24357. * Function will return immediately and will simplify async. It returns the Mesh.
  24358. * @param settings a collection of simplification settings.
  24359. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24360. * @param type the type of simplification to run.
  24361. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24362. */
  24363. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24364. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24365. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24366. this.getScene().simplificationQueue.addTask({
  24367. settings: settings,
  24368. parallelProcessing: parallelProcessing,
  24369. mesh: this,
  24370. simplificationType: simplificationType,
  24371. successCallback: successCallback
  24372. });
  24373. return this;
  24374. };
  24375. /**
  24376. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24377. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24378. * This should be used together with the simplification to avoid disappearing triangles.
  24379. * Returns the Mesh.
  24380. * @param successCallback an optional success callback to be called after the optimization finished.
  24381. */
  24382. Mesh.prototype.optimizeIndices = function (successCallback) {
  24383. var _this = this;
  24384. var indices = this.getIndices();
  24385. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24386. var vectorPositions = [];
  24387. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24388. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24389. }
  24390. var dupes = [];
  24391. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24392. var realPos = vectorPositions.length - 1 - iteration;
  24393. var testedPosition = vectorPositions[realPos];
  24394. for (var j = 0; j < realPos; ++j) {
  24395. var againstPosition = vectorPositions[j];
  24396. if (testedPosition.equals(againstPosition)) {
  24397. dupes[realPos] = j;
  24398. break;
  24399. }
  24400. }
  24401. }, function () {
  24402. for (var i = 0; i < indices.length; ++i) {
  24403. indices[i] = dupes[indices[i]] || indices[i];
  24404. }
  24405. //indices are now reordered
  24406. var originalSubMeshes = _this.subMeshes.slice(0);
  24407. _this.setIndices(indices);
  24408. _this.subMeshes = originalSubMeshes;
  24409. if (successCallback) {
  24410. successCallback(_this);
  24411. }
  24412. });
  24413. return this;
  24414. };
  24415. Mesh.prototype.serialize = function (serializationObject) {
  24416. serializationObject.name = this.name;
  24417. serializationObject.id = this.id;
  24418. serializationObject.type = this.getClassName();
  24419. if (BABYLON.Tags.HasTags(this)) {
  24420. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24421. }
  24422. serializationObject.position = this.position.asArray();
  24423. if (this.rotationQuaternion) {
  24424. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24425. }
  24426. else if (this.rotation) {
  24427. serializationObject.rotation = this.rotation.asArray();
  24428. }
  24429. serializationObject.scaling = this.scaling.asArray();
  24430. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24431. serializationObject.isEnabled = this.isEnabled();
  24432. serializationObject.isVisible = this.isVisible;
  24433. serializationObject.infiniteDistance = this.infiniteDistance;
  24434. serializationObject.pickable = this.isPickable;
  24435. serializationObject.receiveShadows = this.receiveShadows;
  24436. serializationObject.billboardMode = this.billboardMode;
  24437. serializationObject.visibility = this.visibility;
  24438. serializationObject.checkCollisions = this.checkCollisions;
  24439. serializationObject.isBlocker = this.isBlocker;
  24440. // Parent
  24441. if (this.parent) {
  24442. serializationObject.parentId = this.parent.id;
  24443. }
  24444. // Geometry
  24445. var geometry = this._geometry;
  24446. if (geometry) {
  24447. var geometryId = geometry.id;
  24448. serializationObject.geometryId = geometryId;
  24449. // SubMeshes
  24450. serializationObject.subMeshes = [];
  24451. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24452. var subMesh = this.subMeshes[subIndex];
  24453. serializationObject.subMeshes.push({
  24454. materialIndex: subMesh.materialIndex,
  24455. verticesStart: subMesh.verticesStart,
  24456. verticesCount: subMesh.verticesCount,
  24457. indexStart: subMesh.indexStart,
  24458. indexCount: subMesh.indexCount
  24459. });
  24460. }
  24461. }
  24462. // Material
  24463. if (this.material) {
  24464. serializationObject.materialId = this.material.id;
  24465. }
  24466. else {
  24467. this.material = null;
  24468. }
  24469. // Skeleton
  24470. if (this.skeleton) {
  24471. serializationObject.skeletonId = this.skeleton.id;
  24472. }
  24473. // Physics
  24474. //TODO implement correct serialization for physics impostors.
  24475. if (this.getPhysicsImpostor()) {
  24476. var impostor = this.getPhysicsImpostor();
  24477. serializationObject.physicsMass = impostor.getParam("mass");
  24478. serializationObject.physicsFriction = impostor.getParam("friction");
  24479. serializationObject.physicsRestitution = impostor.getParam("mass");
  24480. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24481. }
  24482. // Metadata
  24483. if (this.metadata) {
  24484. serializationObject.metadata = this.metadata;
  24485. }
  24486. // Instances
  24487. serializationObject.instances = [];
  24488. for (var index = 0; index < this.instances.length; index++) {
  24489. var instance = this.instances[index];
  24490. var serializationInstance = {
  24491. name: instance.name,
  24492. position: instance.position.asArray(),
  24493. scaling: instance.scaling.asArray()
  24494. };
  24495. if (instance.rotationQuaternion) {
  24496. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24497. }
  24498. else if (instance.rotation) {
  24499. serializationInstance.rotation = instance.rotation.asArray();
  24500. }
  24501. serializationObject.instances.push(serializationInstance);
  24502. // Animations
  24503. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24504. serializationInstance.ranges = instance.serializeAnimationRanges();
  24505. }
  24506. // Animations
  24507. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24508. serializationObject.ranges = this.serializeAnimationRanges();
  24509. // Layer mask
  24510. serializationObject.layerMask = this.layerMask;
  24511. // Alpha
  24512. serializationObject.alphaIndex = this.alphaIndex;
  24513. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24514. // Overlay
  24515. serializationObject.overlayAlpha = this.overlayAlpha;
  24516. serializationObject.overlayColor = this.overlayColor.asArray();
  24517. serializationObject.renderOverlay = this.renderOverlay;
  24518. // Fog
  24519. serializationObject.applyFog = this.applyFog;
  24520. // Action Manager
  24521. if (this.actionManager) {
  24522. serializationObject.actions = this.actionManager.serialize(this.name);
  24523. }
  24524. };
  24525. // Statics
  24526. /**
  24527. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24528. * The parameter `parsedMesh` is the mesh to be copied.
  24529. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24530. */
  24531. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24532. var mesh;
  24533. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24534. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24535. }
  24536. else {
  24537. mesh = new Mesh(parsedMesh.name, scene);
  24538. }
  24539. mesh.id = parsedMesh.id;
  24540. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24541. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24542. if (parsedMesh.metadata !== undefined) {
  24543. mesh.metadata = parsedMesh.metadata;
  24544. }
  24545. if (parsedMesh.rotationQuaternion) {
  24546. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24547. }
  24548. else if (parsedMesh.rotation) {
  24549. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24550. }
  24551. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24552. if (parsedMesh.localMatrix) {
  24553. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24554. }
  24555. else if (parsedMesh.pivotMatrix) {
  24556. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24557. }
  24558. mesh.setEnabled(parsedMesh.isEnabled);
  24559. mesh.isVisible = parsedMesh.isVisible;
  24560. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24561. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24562. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24563. if (parsedMesh.applyFog !== undefined) {
  24564. mesh.applyFog = parsedMesh.applyFog;
  24565. }
  24566. if (parsedMesh.pickable !== undefined) {
  24567. mesh.isPickable = parsedMesh.pickable;
  24568. }
  24569. if (parsedMesh.alphaIndex !== undefined) {
  24570. mesh.alphaIndex = parsedMesh.alphaIndex;
  24571. }
  24572. mesh.receiveShadows = parsedMesh.receiveShadows;
  24573. mesh.billboardMode = parsedMesh.billboardMode;
  24574. if (parsedMesh.visibility !== undefined) {
  24575. mesh.visibility = parsedMesh.visibility;
  24576. }
  24577. mesh.checkCollisions = parsedMesh.checkCollisions;
  24578. if (parsedMesh.isBlocker !== undefined) {
  24579. mesh.isBlocker = parsedMesh.isBlocker;
  24580. }
  24581. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24582. // freezeWorldMatrix
  24583. if (parsedMesh.freezeWorldMatrix) {
  24584. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24585. }
  24586. // Parent
  24587. if (parsedMesh.parentId) {
  24588. mesh._waitingParentId = parsedMesh.parentId;
  24589. }
  24590. // Actions
  24591. if (parsedMesh.actions !== undefined) {
  24592. mesh._waitingActions = parsedMesh.actions;
  24593. }
  24594. // Overlay
  24595. if (parsedMesh.overlayAlpha !== undefined) {
  24596. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24597. }
  24598. if (parsedMesh.overlayColor !== undefined) {
  24599. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24600. }
  24601. if (parsedMesh.renderOverlay !== undefined) {
  24602. mesh.renderOverlay = parsedMesh.renderOverlay;
  24603. }
  24604. // Geometry
  24605. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24606. if (parsedMesh.delayLoadingFile) {
  24607. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24608. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24609. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24610. if (parsedMesh._binaryInfo) {
  24611. mesh._binaryInfo = parsedMesh._binaryInfo;
  24612. }
  24613. mesh._delayInfo = [];
  24614. if (parsedMesh.hasUVs) {
  24615. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24616. }
  24617. if (parsedMesh.hasUVs2) {
  24618. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24619. }
  24620. if (parsedMesh.hasUVs3) {
  24621. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24622. }
  24623. if (parsedMesh.hasUVs4) {
  24624. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24625. }
  24626. if (parsedMesh.hasUVs5) {
  24627. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24628. }
  24629. if (parsedMesh.hasUVs6) {
  24630. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24631. }
  24632. if (parsedMesh.hasColors) {
  24633. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24634. }
  24635. if (parsedMesh.hasMatricesIndices) {
  24636. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24637. }
  24638. if (parsedMesh.hasMatricesWeights) {
  24639. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24640. }
  24641. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24642. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24643. mesh._checkDelayState();
  24644. }
  24645. }
  24646. else {
  24647. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24648. }
  24649. // Material
  24650. if (parsedMesh.materialId) {
  24651. mesh.setMaterialByID(parsedMesh.materialId);
  24652. }
  24653. else {
  24654. mesh.material = null;
  24655. }
  24656. // Skeleton
  24657. if (parsedMesh.skeletonId > -1) {
  24658. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24659. if (parsedMesh.numBoneInfluencers) {
  24660. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24661. }
  24662. }
  24663. // Animations
  24664. if (parsedMesh.animations) {
  24665. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24666. var parsedAnimation = parsedMesh.animations[animationIndex];
  24667. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24668. }
  24669. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24670. }
  24671. if (parsedMesh.autoAnimate) {
  24672. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24673. }
  24674. // Layer Mask
  24675. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24676. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24677. }
  24678. else {
  24679. mesh.layerMask = 0x0FFFFFFF;
  24680. }
  24681. // Physics
  24682. if (parsedMesh.physicsImpostor) {
  24683. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24684. mass: parsedMesh.physicsMass,
  24685. friction: parsedMesh.physicsFriction,
  24686. restitution: parsedMesh.physicsRestitution
  24687. }, scene);
  24688. }
  24689. // Instances
  24690. if (parsedMesh.instances) {
  24691. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24692. var parsedInstance = parsedMesh.instances[index];
  24693. var instance = mesh.createInstance(parsedInstance.name);
  24694. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24695. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24696. if (parsedInstance.parentId) {
  24697. instance._waitingParentId = parsedInstance.parentId;
  24698. }
  24699. if (parsedInstance.rotationQuaternion) {
  24700. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24701. }
  24702. else if (parsedInstance.rotation) {
  24703. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24704. }
  24705. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24706. instance.checkCollisions = mesh.checkCollisions;
  24707. if (parsedMesh.animations) {
  24708. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24709. parsedAnimation = parsedMesh.animations[animationIndex];
  24710. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24711. }
  24712. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24713. }
  24714. }
  24715. }
  24716. return mesh;
  24717. };
  24718. /**
  24719. * Creates a ribbon mesh.
  24720. * Please consider using the same method from the MeshBuilder class instead.
  24721. * 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.
  24722. *
  24723. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24724. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24725. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24726. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24727. * 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.
  24728. * 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.
  24729. * 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
  24730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24733. */
  24734. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24735. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24736. pathArray: pathArray,
  24737. closeArray: closeArray,
  24738. closePath: closePath,
  24739. offset: offset,
  24740. updatable: updatable,
  24741. sideOrientation: sideOrientation,
  24742. instance: instance
  24743. }, scene);
  24744. };
  24745. /**
  24746. * Creates a plane polygonal mesh. By default, this is a disc.
  24747. * Please consider using the same method from the MeshBuilder class instead.
  24748. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24749. * 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.
  24750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24751. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24753. */
  24754. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24755. var options = {
  24756. radius: radius,
  24757. tessellation: tessellation,
  24758. sideOrientation: sideOrientation,
  24759. updatable: updatable
  24760. };
  24761. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24762. };
  24763. /**
  24764. * Creates a box mesh.
  24765. * Please consider using the same method from the MeshBuilder class instead.
  24766. * The parameter `size` sets the size (float) of each box side (default 1).
  24767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24770. */
  24771. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24772. var options = {
  24773. size: size,
  24774. sideOrientation: sideOrientation,
  24775. updatable: updatable
  24776. };
  24777. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24778. };
  24779. /**
  24780. * Creates a sphere mesh.
  24781. * Please consider using the same method from the MeshBuilder class instead.
  24782. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24783. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24787. */
  24788. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24789. var options = {
  24790. segments: segments,
  24791. diameterX: diameter,
  24792. diameterY: diameter,
  24793. diameterZ: diameter,
  24794. sideOrientation: sideOrientation,
  24795. updatable: updatable
  24796. };
  24797. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24798. };
  24799. /**
  24800. * Creates a cylinder or a cone mesh.
  24801. * Please consider using the same method from the MeshBuilder class instead.
  24802. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24803. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24804. * 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.
  24805. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24806. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24810. */
  24811. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24812. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24813. if (scene !== undefined) {
  24814. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24815. updatable = scene;
  24816. }
  24817. scene = subdivisions;
  24818. subdivisions = 1;
  24819. }
  24820. var options = {
  24821. height: height,
  24822. diameterTop: diameterTop,
  24823. diameterBottom: diameterBottom,
  24824. tessellation: tessellation,
  24825. subdivisions: subdivisions,
  24826. sideOrientation: sideOrientation,
  24827. updatable: updatable
  24828. };
  24829. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24830. };
  24831. // Torus (Code from SharpDX.org)
  24832. /**
  24833. * Creates a torus mesh.
  24834. * Please consider using the same method from the MeshBuilder class instead.
  24835. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24836. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24837. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24841. */
  24842. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24843. var options = {
  24844. diameter: diameter,
  24845. thickness: thickness,
  24846. tessellation: tessellation,
  24847. sideOrientation: sideOrientation,
  24848. updatable: updatable
  24849. };
  24850. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24851. };
  24852. /**
  24853. * Creates a torus knot mesh.
  24854. * Please consider using the same method from the MeshBuilder class instead.
  24855. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24856. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24857. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24858. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24860. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24862. */
  24863. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24864. var options = {
  24865. radius: radius,
  24866. tube: tube,
  24867. radialSegments: radialSegments,
  24868. tubularSegments: tubularSegments,
  24869. p: p,
  24870. q: q,
  24871. sideOrientation: sideOrientation,
  24872. updatable: updatable
  24873. };
  24874. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24875. };
  24876. /**
  24877. * Creates a line mesh.
  24878. * Please consider using the same method from the MeshBuilder class instead.
  24879. * 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.
  24880. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24881. * The parameter `points` is an array successive Vector3.
  24882. * 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
  24883. * When updating an instance, remember that only point positions can change, not the number of points.
  24884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24885. */
  24886. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24887. var options = {
  24888. points: points,
  24889. updatable: updatable,
  24890. instance: instance
  24891. };
  24892. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24893. };
  24894. /**
  24895. * Creates a dashed line mesh.
  24896. * Please consider using the same method from the MeshBuilder class instead.
  24897. * 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.
  24898. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24899. * The parameter `points` is an array successive Vector3.
  24900. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24901. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24902. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24903. * 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
  24904. * When updating an instance, remember that only point positions can change, not the number of points.
  24905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24906. */
  24907. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24908. var options = {
  24909. points: points,
  24910. dashSize: dashSize,
  24911. gapSize: gapSize,
  24912. dashNb: dashNb,
  24913. updatable: updatable,
  24914. instance: instance
  24915. };
  24916. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24917. };
  24918. /**
  24919. * Creates an extruded shape mesh.
  24920. * 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.
  24921. * Please consider using the same method from the MeshBuilder class instead.
  24922. *
  24923. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24924. * 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
  24925. * extruded along the Z axis.
  24926. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24927. * 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.
  24928. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24929. * 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
  24930. * 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
  24931. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24935. */
  24936. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24937. var options = {
  24938. shape: shape,
  24939. path: path,
  24940. scale: scale,
  24941. rotation: rotation,
  24942. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24943. sideOrientation: sideOrientation,
  24944. instance: instance,
  24945. updatable: updatable
  24946. };
  24947. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24948. };
  24949. /**
  24950. * Creates an custom extruded shape mesh.
  24951. * 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.
  24952. * Please consider using the same method from the MeshBuilder class instead.
  24953. *
  24954. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24955. * 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
  24956. * extruded along the Z axis.
  24957. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24958. * 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
  24959. * and the distance of this point from the begining of the path :
  24960. * ```javascript
  24961. * var rotationFunction = function(i, distance) {
  24962. * // do things
  24963. * return rotationValue; }
  24964. * ```
  24965. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24966. * 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
  24967. * and the distance of this point from the begining of the path :
  24968. * ```javascript
  24969. * var scaleFunction = function(i, distance) {
  24970. * // do things
  24971. * return scaleValue;}
  24972. * ```
  24973. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24974. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24975. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24976. * 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
  24977. * 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
  24978. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24982. */
  24983. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24984. var options = {
  24985. shape: shape,
  24986. path: path,
  24987. scaleFunction: scaleFunction,
  24988. rotationFunction: rotationFunction,
  24989. ribbonCloseArray: ribbonCloseArray,
  24990. ribbonClosePath: ribbonClosePath,
  24991. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24992. sideOrientation: sideOrientation,
  24993. instance: instance,
  24994. updatable: updatable
  24995. };
  24996. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24997. };
  24998. /**
  24999. * Creates lathe mesh.
  25000. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25001. * Please consider using the same method from the MeshBuilder class instead.
  25002. * 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
  25003. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25004. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25005. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25006. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25007. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25009. */
  25010. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25011. var options = {
  25012. shape: shape,
  25013. radius: radius,
  25014. tessellation: tessellation,
  25015. sideOrientation: sideOrientation,
  25016. updatable: updatable
  25017. };
  25018. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25019. };
  25020. /**
  25021. * Creates a plane mesh.
  25022. * Please consider using the same method from the MeshBuilder class instead.
  25023. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25027. */
  25028. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25029. var options = {
  25030. size: size,
  25031. width: size,
  25032. height: size,
  25033. sideOrientation: sideOrientation,
  25034. updatable: updatable
  25035. };
  25036. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25037. };
  25038. /**
  25039. * Creates a ground mesh.
  25040. * Please consider using the same method from the MeshBuilder class instead.
  25041. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25042. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25044. */
  25045. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25046. var options = {
  25047. width: width,
  25048. height: height,
  25049. subdivisions: subdivisions,
  25050. updatable: updatable
  25051. };
  25052. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25053. };
  25054. /**
  25055. * Creates a tiled ground mesh.
  25056. * Please consider using the same method from the MeshBuilder class instead.
  25057. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25058. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25059. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25060. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25061. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25062. * numbers of subdivisions on the ground width and height of each tile.
  25063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25064. */
  25065. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25066. var options = {
  25067. xmin: xmin,
  25068. zmin: zmin,
  25069. xmax: xmax,
  25070. zmax: zmax,
  25071. subdivisions: subdivisions,
  25072. precision: precision,
  25073. updatable: updatable
  25074. };
  25075. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25076. };
  25077. /**
  25078. * Creates a ground mesh from a height map.
  25079. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25080. * Please consider using the same method from the MeshBuilder class instead.
  25081. * The parameter `url` sets the URL of the height map image resource.
  25082. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25083. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25084. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25085. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25086. * 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).
  25087. * This function is passed the newly built mesh :
  25088. * ```javascript
  25089. * function(mesh) { // do things
  25090. * return; }
  25091. * ```
  25092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25093. */
  25094. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25095. var options = {
  25096. width: width,
  25097. height: height,
  25098. subdivisions: subdivisions,
  25099. minHeight: minHeight,
  25100. maxHeight: maxHeight,
  25101. updatable: updatable,
  25102. onReady: onReady
  25103. };
  25104. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25105. };
  25106. /**
  25107. * Creates a tube mesh.
  25108. * 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.
  25109. * Please consider using the same method from the MeshBuilder class instead.
  25110. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25111. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25112. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25113. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25114. * 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.
  25115. * It must return a radius value (positive float) :
  25116. * ```javascript
  25117. * var radiusFunction = function(i, distance) {
  25118. * // do things
  25119. * return radius; }
  25120. * ```
  25121. * 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
  25122. * 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
  25123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25126. */
  25127. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25128. var options = {
  25129. path: path,
  25130. radius: radius,
  25131. tessellation: tessellation,
  25132. radiusFunction: radiusFunction,
  25133. arc: 1,
  25134. cap: cap,
  25135. updatable: updatable,
  25136. sideOrientation: sideOrientation,
  25137. instance: instance
  25138. };
  25139. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25140. };
  25141. /**
  25142. * Creates a polyhedron mesh.
  25143. * Please consider using the same method from the MeshBuilder class instead.
  25144. * 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
  25145. * to choose the wanted type.
  25146. * The parameter `size` (positive float, default 1) sets the polygon size.
  25147. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25148. * 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`.
  25149. * 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
  25150. * 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)`).
  25151. * 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
  25152. * 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.
  25153. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25154. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25156. */
  25157. Mesh.CreatePolyhedron = function (name, options, scene) {
  25158. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25159. };
  25160. /**
  25161. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25162. * Please consider using the same method from the MeshBuilder class instead.
  25163. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25164. * 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`).
  25165. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25166. * 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.
  25167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25170. */
  25171. Mesh.CreateIcoSphere = function (name, options, scene) {
  25172. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25173. };
  25174. /**
  25175. * Creates a decal mesh.
  25176. * Please consider using the same method from the MeshBuilder class instead.
  25177. * 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.
  25178. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25179. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25180. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25181. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25182. */
  25183. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25184. var options = {
  25185. position: position,
  25186. normal: normal,
  25187. size: size,
  25188. angle: angle
  25189. };
  25190. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25191. };
  25192. // Skeletons
  25193. /**
  25194. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25195. */
  25196. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25197. var source;
  25198. if (!this._sourcePositions) {
  25199. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25200. this._sourcePositions = new Float32Array(source);
  25201. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25202. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25203. }
  25204. }
  25205. return this._sourcePositions;
  25206. };
  25207. /**
  25208. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25209. */
  25210. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25211. var source;
  25212. if (!this._sourceNormals) {
  25213. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25214. this._sourceNormals = new Float32Array(source);
  25215. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25216. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25217. }
  25218. }
  25219. return this._sourceNormals;
  25220. };
  25221. /**
  25222. * Updates the vertex buffer by applying transformation from the bones.
  25223. * Returns the Mesh.
  25224. *
  25225. * @param {skeleton} skeleton to apply
  25226. */
  25227. Mesh.prototype.applySkeleton = function (skeleton) {
  25228. if (!this.geometry) {
  25229. return this;
  25230. }
  25231. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25232. return this;
  25233. }
  25234. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25235. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25236. return this;
  25237. }
  25238. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25239. return this;
  25240. }
  25241. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25242. return this;
  25243. }
  25244. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25245. return this;
  25246. }
  25247. if (!this._sourcePositions) {
  25248. var submeshes = this.subMeshes.slice();
  25249. this.setPositionsForCPUSkinning();
  25250. this.subMeshes = submeshes;
  25251. }
  25252. if (!this._sourceNormals) {
  25253. this.setNormalsForCPUSkinning();
  25254. }
  25255. // positionsData checks for not being Float32Array will only pass at most once
  25256. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25257. if (!(positionsData instanceof Float32Array)) {
  25258. positionsData = new Float32Array(positionsData);
  25259. }
  25260. // normalsData checks for not being Float32Array will only pass at most once
  25261. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25262. if (!(normalsData instanceof Float32Array)) {
  25263. normalsData = new Float32Array(normalsData);
  25264. }
  25265. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25266. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25267. var needExtras = this.numBoneInfluencers > 4;
  25268. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25269. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25270. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25271. var tempVector3 = BABYLON.Vector3.Zero();
  25272. var finalMatrix = new BABYLON.Matrix();
  25273. var tempMatrix = new BABYLON.Matrix();
  25274. var matWeightIdx = 0;
  25275. var inf;
  25276. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25277. var weight;
  25278. for (inf = 0; inf < 4; inf++) {
  25279. weight = matricesWeightsData[matWeightIdx + inf];
  25280. if (weight > 0) {
  25281. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25282. finalMatrix.addToSelf(tempMatrix);
  25283. }
  25284. else
  25285. break;
  25286. }
  25287. if (needExtras) {
  25288. for (inf = 0; inf < 4; inf++) {
  25289. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25290. if (weight > 0) {
  25291. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25292. finalMatrix.addToSelf(tempMatrix);
  25293. }
  25294. else
  25295. break;
  25296. }
  25297. }
  25298. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25299. tempVector3.toArray(positionsData, index);
  25300. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25301. tempVector3.toArray(normalsData, index);
  25302. finalMatrix.reset();
  25303. }
  25304. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25305. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25306. return this;
  25307. };
  25308. // Tools
  25309. /**
  25310. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25311. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25312. */
  25313. Mesh.MinMax = function (meshes) {
  25314. var minVector = null;
  25315. var maxVector = null;
  25316. meshes.forEach(function (mesh, index, array) {
  25317. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25318. if (!minVector) {
  25319. minVector = boundingBox.minimumWorld;
  25320. maxVector = boundingBox.maximumWorld;
  25321. }
  25322. else {
  25323. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25324. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25325. }
  25326. });
  25327. return {
  25328. min: minVector,
  25329. max: maxVector
  25330. };
  25331. };
  25332. /**
  25333. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25334. */
  25335. Mesh.Center = function (meshesOrMinMaxVector) {
  25336. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25337. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25338. };
  25339. /**
  25340. * Merge the array of meshes into a single mesh for performance reasons.
  25341. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25342. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25343. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25344. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25345. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25346. */
  25347. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25348. if (disposeSource === void 0) { disposeSource = true; }
  25349. var index;
  25350. if (!allow32BitsIndices) {
  25351. var totalVertices = 0;
  25352. // Counting vertices
  25353. for (index = 0; index < meshes.length; index++) {
  25354. if (meshes[index]) {
  25355. totalVertices += meshes[index].getTotalVertices();
  25356. if (totalVertices > 65536) {
  25357. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25358. return null;
  25359. }
  25360. }
  25361. }
  25362. }
  25363. // Merge
  25364. var vertexData;
  25365. var otherVertexData;
  25366. var indiceArray = new Array();
  25367. var source;
  25368. for (index = 0; index < meshes.length; index++) {
  25369. if (meshes[index]) {
  25370. meshes[index].computeWorldMatrix(true);
  25371. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25372. otherVertexData.transform(meshes[index].getWorldMatrix());
  25373. if (vertexData) {
  25374. vertexData.merge(otherVertexData);
  25375. }
  25376. else {
  25377. vertexData = otherVertexData;
  25378. source = meshes[index];
  25379. }
  25380. if (subdivideWithSubMeshes) {
  25381. indiceArray.push(meshes[index].getTotalIndices());
  25382. }
  25383. }
  25384. }
  25385. if (!meshSubclass) {
  25386. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25387. }
  25388. vertexData.applyToMesh(meshSubclass);
  25389. // Setting properties
  25390. meshSubclass.material = source.material;
  25391. meshSubclass.checkCollisions = source.checkCollisions;
  25392. // Cleaning
  25393. if (disposeSource) {
  25394. for (index = 0; index < meshes.length; index++) {
  25395. if (meshes[index]) {
  25396. meshes[index].dispose();
  25397. }
  25398. }
  25399. }
  25400. // Subdivide
  25401. if (subdivideWithSubMeshes) {
  25402. //-- Suppresions du submesh global
  25403. meshSubclass.releaseSubMeshes();
  25404. index = 0;
  25405. var offset = 0;
  25406. //-- aplique la subdivision en fonction du tableau d'indices
  25407. while (index < indiceArray.length) {
  25408. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25409. offset += indiceArray[index];
  25410. index++;
  25411. }
  25412. }
  25413. return meshSubclass;
  25414. };
  25415. return Mesh;
  25416. }(BABYLON.AbstractMesh));
  25417. // Consts
  25418. Mesh._FRONTSIDE = 0;
  25419. Mesh._BACKSIDE = 1;
  25420. Mesh._DOUBLESIDE = 2;
  25421. Mesh._DEFAULTSIDE = 0;
  25422. Mesh._NO_CAP = 0;
  25423. Mesh._CAP_START = 1;
  25424. Mesh._CAP_END = 2;
  25425. Mesh._CAP_ALL = 3;
  25426. BABYLON.Mesh = Mesh;
  25427. })(BABYLON || (BABYLON = {}));
  25428. //# sourceMappingURL=babylon.mesh.js.map
  25429. var BABYLON;
  25430. (function (BABYLON) {
  25431. var SubMesh = (function () {
  25432. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25433. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25434. this.materialIndex = materialIndex;
  25435. this.verticesStart = verticesStart;
  25436. this.verticesCount = verticesCount;
  25437. this.indexStart = indexStart;
  25438. this.indexCount = indexCount;
  25439. this._renderId = 0;
  25440. this._mesh = mesh;
  25441. this._renderingMesh = renderingMesh || mesh;
  25442. mesh.subMeshes.push(this);
  25443. this._trianglePlanes = [];
  25444. this._id = mesh.subMeshes.length - 1;
  25445. if (createBoundingBox) {
  25446. this.refreshBoundingInfo();
  25447. mesh.computeWorldMatrix(true);
  25448. }
  25449. }
  25450. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25451. get: function () {
  25452. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25453. },
  25454. enumerable: true,
  25455. configurable: true
  25456. });
  25457. /**
  25458. * Returns the submesh BoudingInfo object.
  25459. */
  25460. SubMesh.prototype.getBoundingInfo = function () {
  25461. if (this.IsGlobal) {
  25462. return this._mesh.getBoundingInfo();
  25463. }
  25464. return this._boundingInfo;
  25465. };
  25466. /**
  25467. * Sets the submesh BoundingInfo.
  25468. * Return the SubMesh.
  25469. */
  25470. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25471. this._boundingInfo = boundingInfo;
  25472. return this;
  25473. };
  25474. /**
  25475. * Returns the mesh of the current submesh.
  25476. */
  25477. SubMesh.prototype.getMesh = function () {
  25478. return this._mesh;
  25479. };
  25480. /**
  25481. * Returns the rendering mesh of the submesh.
  25482. */
  25483. SubMesh.prototype.getRenderingMesh = function () {
  25484. return this._renderingMesh;
  25485. };
  25486. /**
  25487. * Returns the submesh material.
  25488. */
  25489. SubMesh.prototype.getMaterial = function () {
  25490. var rootMaterial = this._renderingMesh.material;
  25491. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25492. var multiMaterial = rootMaterial;
  25493. return multiMaterial.getSubMaterial(this.materialIndex);
  25494. }
  25495. if (!rootMaterial) {
  25496. return this._mesh.getScene().defaultMaterial;
  25497. }
  25498. return rootMaterial;
  25499. };
  25500. // Methods
  25501. /**
  25502. * Sets a new updated BoundingInfo object to the submesh.
  25503. * Returns the SubMesh.
  25504. */
  25505. SubMesh.prototype.refreshBoundingInfo = function () {
  25506. this._lastColliderWorldVertices = null;
  25507. if (this.IsGlobal) {
  25508. return;
  25509. }
  25510. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25511. if (!data) {
  25512. this._boundingInfo = this._mesh._boundingInfo;
  25513. return;
  25514. }
  25515. var indices = this._renderingMesh.getIndices();
  25516. var extend;
  25517. //is this the only submesh?
  25518. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25519. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25520. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  25521. }
  25522. else {
  25523. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25524. }
  25525. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25526. return this;
  25527. };
  25528. SubMesh.prototype._checkCollision = function (collider) {
  25529. return this.getBoundingInfo()._checkCollision(collider);
  25530. };
  25531. /**
  25532. * Updates the submesh BoundingInfo.
  25533. * Returns the Submesh.
  25534. */
  25535. SubMesh.prototype.updateBoundingInfo = function (world) {
  25536. if (!this.getBoundingInfo()) {
  25537. this.refreshBoundingInfo();
  25538. }
  25539. this.getBoundingInfo().update(world);
  25540. return this;
  25541. };
  25542. /**
  25543. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25544. * Boolean returned.
  25545. */
  25546. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25547. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  25548. };
  25549. /**
  25550. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25551. * Boolean returned.
  25552. */
  25553. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25554. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  25555. };
  25556. /**
  25557. * Renders the submesh.
  25558. * Returns it.
  25559. */
  25560. SubMesh.prototype.render = function (enableAlphaMode) {
  25561. this._renderingMesh.render(this, enableAlphaMode);
  25562. return this;
  25563. };
  25564. /**
  25565. * Returns a new Index Buffer.
  25566. * Type returned : WebGLBuffer.
  25567. */
  25568. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25569. if (!this._linesIndexBuffer) {
  25570. var linesIndices = [];
  25571. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25572. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25573. }
  25574. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25575. this.linesIndexCount = linesIndices.length;
  25576. }
  25577. return this._linesIndexBuffer;
  25578. };
  25579. /**
  25580. * True is the passed Ray intersects the submesh bounding box.
  25581. * Boolean returned.
  25582. */
  25583. SubMesh.prototype.canIntersects = function (ray) {
  25584. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  25585. };
  25586. /**
  25587. * Returns an object IntersectionInfo.
  25588. */
  25589. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25590. var intersectInfo = null;
  25591. // LineMesh first as it's also a Mesh...
  25592. if (this._mesh instanceof BABYLON.LinesMesh) {
  25593. var lineMesh = this._mesh;
  25594. // Line test
  25595. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25596. var p0 = positions[indices[index]];
  25597. var p1 = positions[indices[index + 1]];
  25598. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25599. if (length < 0) {
  25600. continue;
  25601. }
  25602. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25603. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25604. if (fastCheck) {
  25605. break;
  25606. }
  25607. }
  25608. }
  25609. }
  25610. else {
  25611. // Triangles test
  25612. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25613. var p0 = positions[indices[index]];
  25614. var p1 = positions[indices[index + 1]];
  25615. var p2 = positions[indices[index + 2]];
  25616. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25617. if (currentIntersectInfo) {
  25618. if (currentIntersectInfo.distance < 0) {
  25619. continue;
  25620. }
  25621. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25622. intersectInfo = currentIntersectInfo;
  25623. intersectInfo.faceId = index / 3;
  25624. if (fastCheck) {
  25625. break;
  25626. }
  25627. }
  25628. }
  25629. }
  25630. }
  25631. return intersectInfo;
  25632. };
  25633. // Clone
  25634. /**
  25635. * Creates a new Submesh from the passed Mesh.
  25636. */
  25637. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25638. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25639. if (!this.IsGlobal) {
  25640. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  25641. }
  25642. return result;
  25643. };
  25644. // Dispose
  25645. /**
  25646. * Disposes the Submesh.
  25647. * Returns nothing.
  25648. */
  25649. SubMesh.prototype.dispose = function () {
  25650. if (this._linesIndexBuffer) {
  25651. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25652. this._linesIndexBuffer = null;
  25653. }
  25654. // Remove from mesh
  25655. var index = this._mesh.subMeshes.indexOf(this);
  25656. this._mesh.subMeshes.splice(index, 1);
  25657. };
  25658. // Statics
  25659. /**
  25660. * Creates a new Submesh from the passed parameters :
  25661. * - materialIndex (integer) : the index of the main mesh material.
  25662. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25663. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25664. * - mesh (Mesh) : the main mesh to create the submesh from.
  25665. * - renderingMesh (optional Mesh) : rendering mesh.
  25666. */
  25667. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25668. var minVertexIndex = Number.MAX_VALUE;
  25669. var maxVertexIndex = -Number.MAX_VALUE;
  25670. renderingMesh = renderingMesh || mesh;
  25671. var indices = renderingMesh.getIndices();
  25672. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25673. var vertexIndex = indices[index];
  25674. if (vertexIndex < minVertexIndex)
  25675. minVertexIndex = vertexIndex;
  25676. if (vertexIndex > maxVertexIndex)
  25677. maxVertexIndex = vertexIndex;
  25678. }
  25679. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25680. };
  25681. return SubMesh;
  25682. }());
  25683. BABYLON.SubMesh = SubMesh;
  25684. })(BABYLON || (BABYLON = {}));
  25685. //# sourceMappingURL=babylon.subMesh.js.map
  25686. var BABYLON;
  25687. (function (BABYLON) {
  25688. var MeshBuilder = (function () {
  25689. function MeshBuilder() {
  25690. }
  25691. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25692. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25693. return BABYLON.Mesh.DOUBLESIDE;
  25694. }
  25695. if (orientation === undefined || orientation === null) {
  25696. return BABYLON.Mesh.FRONTSIDE;
  25697. }
  25698. return orientation;
  25699. };
  25700. /**
  25701. * Creates a box mesh.
  25702. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25703. * The parameter `size` sets the size (float) of each box side (default 1).
  25704. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25705. * 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).
  25706. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25710. */
  25711. MeshBuilder.CreateBox = function (name, options, scene) {
  25712. var box = new BABYLON.Mesh(name, scene);
  25713. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25714. box.sideOrientation = options.sideOrientation;
  25715. var vertexData = BABYLON.VertexData.CreateBox(options);
  25716. vertexData.applyToMesh(box, options.updatable);
  25717. return box;
  25718. };
  25719. /**
  25720. * Creates a sphere mesh.
  25721. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25722. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25723. * 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`).
  25724. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25725. * 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
  25726. * 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).
  25727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25730. */
  25731. MeshBuilder.CreateSphere = function (name, options, scene) {
  25732. var sphere = new BABYLON.Mesh(name, scene);
  25733. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25734. sphere.sideOrientation = options.sideOrientation;
  25735. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25736. vertexData.applyToMesh(sphere, options.updatable);
  25737. return sphere;
  25738. };
  25739. /**
  25740. * Creates a plane polygonal mesh. By default, this is a disc.
  25741. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25742. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25743. * 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.
  25744. * 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
  25745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25748. */
  25749. MeshBuilder.CreateDisc = function (name, options, scene) {
  25750. var disc = new BABYLON.Mesh(name, scene);
  25751. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25752. disc.sideOrientation = options.sideOrientation;
  25753. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25754. vertexData.applyToMesh(disc, options.updatable);
  25755. return disc;
  25756. };
  25757. /**
  25758. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25760. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25761. * 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`).
  25762. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25763. * 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.
  25764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25765. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25767. */
  25768. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25769. var sphere = new BABYLON.Mesh(name, scene);
  25770. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25771. sphere.sideOrientation = options.sideOrientation;
  25772. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25773. vertexData.applyToMesh(sphere, options.updatable);
  25774. return sphere;
  25775. };
  25776. ;
  25777. /**
  25778. * Creates a ribbon mesh.
  25779. * 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.
  25780. *
  25781. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25782. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25783. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25784. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25785. * 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.
  25786. * 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.
  25787. * 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
  25788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25789. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25790. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25791. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  25792. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  25793. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  25794. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  25795. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  25796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25797. */
  25798. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25799. var pathArray = options.pathArray;
  25800. var closeArray = options.closeArray;
  25801. var closePath = options.closePath;
  25802. var offset = options.offset;
  25803. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25804. var instance = options.instance;
  25805. var updatable = options.updatable;
  25806. if (instance) {
  25807. // positionFunction : ribbon case
  25808. // only pathArray and sideOrientation parameters are taken into account for positions update
  25809. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25810. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25811. var positionFunction = function (positions) {
  25812. var minlg = pathArray[0].length;
  25813. var i = 0;
  25814. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25815. for (var si = 1; si <= ns; si++) {
  25816. for (var p = 0; p < pathArray.length; p++) {
  25817. var path = pathArray[p];
  25818. var l = path.length;
  25819. minlg = (minlg < l) ? minlg : l;
  25820. var j = 0;
  25821. while (j < minlg) {
  25822. positions[i] = path[j].x;
  25823. positions[i + 1] = path[j].y;
  25824. positions[i + 2] = path[j].z;
  25825. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25826. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25827. }
  25828. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25829. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25830. }
  25831. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25832. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25833. }
  25834. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25835. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25836. }
  25837. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25838. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25839. }
  25840. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25841. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25842. }
  25843. j++;
  25844. i += 3;
  25845. }
  25846. if (instance._closePath) {
  25847. positions[i] = path[0].x;
  25848. positions[i + 1] = path[0].y;
  25849. positions[i + 2] = path[0].z;
  25850. i += 3;
  25851. }
  25852. }
  25853. }
  25854. };
  25855. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25856. positionFunction(positions);
  25857. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25858. instance._boundingInfo.update(instance._worldMatrix);
  25859. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25860. if (options.colors) {
  25861. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25862. for (var c = 0; c < options.colors.length; c++) {
  25863. colors[c * 4] = options.colors[c].r;
  25864. colors[c * 4 + 1] = options.colors[c].g;
  25865. colors[c * 4 + 2] = options.colors[c].b;
  25866. colors[c * 4 + 3] = options.colors[c].a;
  25867. }
  25868. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  25869. }
  25870. if (options.uvs) {
  25871. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25872. for (var i = 0; i < options.uvs.length; i++) {
  25873. uvs[i * 2] = options.uvs[i].x;
  25874. uvs[i * 2 + 1] = options.uvs[i].y;
  25875. }
  25876. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  25877. }
  25878. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25879. var indices = instance.getIndices();
  25880. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25881. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25882. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25883. if (instance._closePath) {
  25884. var indexFirst = 0;
  25885. var indexLast = 0;
  25886. for (var p = 0; p < pathArray.length; p++) {
  25887. indexFirst = instance._idx[p] * 3;
  25888. if (p + 1 < pathArray.length) {
  25889. indexLast = (instance._idx[p + 1] - 1) * 3;
  25890. }
  25891. else {
  25892. indexLast = normals.length - 3;
  25893. }
  25894. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25895. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25896. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25897. normals[indexLast] = normals[indexFirst];
  25898. normals[indexLast + 1] = normals[indexFirst + 1];
  25899. normals[indexLast + 2] = normals[indexFirst + 2];
  25900. }
  25901. }
  25902. if (!(instance.areNormalsFrozen)) {
  25903. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25904. }
  25905. }
  25906. return instance;
  25907. }
  25908. else {
  25909. var ribbon = new BABYLON.Mesh(name, scene);
  25910. ribbon.sideOrientation = sideOrientation;
  25911. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25912. if (closePath) {
  25913. ribbon._idx = vertexData._idx;
  25914. }
  25915. ribbon._closePath = closePath;
  25916. ribbon._closeArray = closeArray;
  25917. vertexData.applyToMesh(ribbon, updatable);
  25918. return ribbon;
  25919. }
  25920. };
  25921. /**
  25922. * Creates a cylinder or a cone mesh.
  25923. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25924. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25925. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25926. * 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.
  25927. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25928. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25929. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25930. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25931. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25932. * 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).
  25933. * 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
  25934. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25935. * 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
  25936. * 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.
  25937. * If `enclose` is false, a ring surface is one element.
  25938. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25939. * 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
  25940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25943. */
  25944. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25945. var cylinder = new BABYLON.Mesh(name, scene);
  25946. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25947. cylinder.sideOrientation = options.sideOrientation;
  25948. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25949. vertexData.applyToMesh(cylinder, options.updatable);
  25950. return cylinder;
  25951. };
  25952. /**
  25953. * Creates a torus mesh.
  25954. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25955. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25956. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25957. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25961. */
  25962. MeshBuilder.CreateTorus = function (name, options, scene) {
  25963. var torus = new BABYLON.Mesh(name, scene);
  25964. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25965. torus.sideOrientation = options.sideOrientation;
  25966. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25967. vertexData.applyToMesh(torus, options.updatable);
  25968. return torus;
  25969. };
  25970. /**
  25971. * Creates a torus knot mesh.
  25972. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25973. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25974. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25975. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25976. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25980. */
  25981. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25982. var torusKnot = new BABYLON.Mesh(name, scene);
  25983. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25984. torusKnot.sideOrientation = options.sideOrientation;
  25985. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25986. vertexData.applyToMesh(torusKnot, options.updatable);
  25987. return torusKnot;
  25988. };
  25989. /**
  25990. * Creates a line system mesh.
  25991. * A line system is a pool of many lines gathered in a single mesh.
  25992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25993. * 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.
  25994. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25995. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25996. * 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
  25997. * 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
  25998. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26000. */
  26001. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  26002. var instance = options.instance;
  26003. var lines = options.lines;
  26004. if (instance) {
  26005. var positionFunction = function (positions) {
  26006. var i = 0;
  26007. for (var l = 0; l < lines.length; l++) {
  26008. var points = lines[l];
  26009. for (var p = 0; p < points.length; p++) {
  26010. positions[i] = points[p].x;
  26011. positions[i + 1] = points[p].y;
  26012. positions[i + 2] = points[p].z;
  26013. i += 3;
  26014. }
  26015. }
  26016. };
  26017. instance.updateMeshPositions(positionFunction, false);
  26018. return instance;
  26019. }
  26020. // line system creation
  26021. var lineSystem = new BABYLON.LinesMesh(name, scene);
  26022. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  26023. vertexData.applyToMesh(lineSystem, options.updatable);
  26024. return lineSystem;
  26025. };
  26026. /**
  26027. * Creates a line mesh.
  26028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  26029. * 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.
  26030. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26031. * The parameter `points` is an array successive Vector3.
  26032. * 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
  26033. * When updating an instance, remember that only point positions can change, not the number of points.
  26034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26035. */
  26036. MeshBuilder.CreateLines = function (name, options, scene) {
  26037. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  26038. return lines;
  26039. };
  26040. /**
  26041. * Creates a dashed line mesh.
  26042. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  26043. * 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.
  26044. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26045. * The parameter `points` is an array successive Vector3.
  26046. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26047. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26048. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26049. * 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
  26050. * When updating an instance, remember that only point positions can change, not the number of points.
  26051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26052. */
  26053. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26054. var points = options.points;
  26055. var instance = options.instance;
  26056. var gapSize = options.gapSize;
  26057. var dashNb = options.dashNb;
  26058. var dashSize = options.dashSize;
  26059. if (instance) {
  26060. var positionFunction = function (positions) {
  26061. var curvect = BABYLON.Vector3.Zero();
  26062. var nbSeg = positions.length / 6;
  26063. var lg = 0;
  26064. var nb = 0;
  26065. var shft = 0;
  26066. var dashshft = 0;
  26067. var curshft = 0;
  26068. var p = 0;
  26069. var i = 0;
  26070. var j = 0;
  26071. for (i = 0; i < points.length - 1; i++) {
  26072. points[i + 1].subtractToRef(points[i], curvect);
  26073. lg += curvect.length();
  26074. }
  26075. shft = lg / nbSeg;
  26076. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26077. for (i = 0; i < points.length - 1; i++) {
  26078. points[i + 1].subtractToRef(points[i], curvect);
  26079. nb = Math.floor(curvect.length() / shft);
  26080. curvect.normalize();
  26081. j = 0;
  26082. while (j < nb && p < positions.length) {
  26083. curshft = shft * j;
  26084. positions[p] = points[i].x + curshft * curvect.x;
  26085. positions[p + 1] = points[i].y + curshft * curvect.y;
  26086. positions[p + 2] = points[i].z + curshft * curvect.z;
  26087. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26088. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26089. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26090. p += 6;
  26091. j++;
  26092. }
  26093. }
  26094. while (p < positions.length) {
  26095. positions[p] = points[i].x;
  26096. positions[p + 1] = points[i].y;
  26097. positions[p + 2] = points[i].z;
  26098. p += 3;
  26099. }
  26100. };
  26101. instance.updateMeshPositions(positionFunction, false);
  26102. return instance;
  26103. }
  26104. // dashed lines creation
  26105. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26106. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26107. vertexData.applyToMesh(dashedLines, options.updatable);
  26108. dashedLines.dashSize = dashSize;
  26109. dashedLines.gapSize = gapSize;
  26110. return dashedLines;
  26111. };
  26112. /**
  26113. * Creates an extruded shape mesh.
  26114. * 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.
  26115. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26116. *
  26117. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26118. * 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
  26119. * extruded along the Z axis.
  26120. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26121. * 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.
  26122. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26123. * 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
  26124. * 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
  26125. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26128. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26130. */
  26131. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26132. var path = options.path;
  26133. var shape = options.shape;
  26134. var scale = options.scale || 1;
  26135. var rotation = options.rotation || 0;
  26136. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26137. var updatable = options.updatable;
  26138. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26139. var instance = options.instance;
  26140. var invertUV = options.invertUV || false;
  26141. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26142. };
  26143. /**
  26144. * Creates an custom extruded shape mesh.
  26145. * 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.
  26146. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26147. *
  26148. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26149. * 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
  26150. * extruded along the Z axis.
  26151. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26152. * 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
  26153. * and the distance of this point from the begining of the path :
  26154. * ```javascript
  26155. * var rotationFunction = function(i, distance) {
  26156. * // do things
  26157. * return rotationValue; }
  26158. * ```
  26159. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26160. * 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
  26161. * and the distance of this point from the begining of the path :
  26162. * ```javascript
  26163. * var scaleFunction = function(i, distance) {
  26164. * // do things
  26165. * return scaleValue;}
  26166. * ```
  26167. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26168. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26169. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26170. * 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
  26171. * 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
  26172. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26175. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26177. */
  26178. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26179. var path = options.path;
  26180. var shape = options.shape;
  26181. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26182. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26183. var ribbonCloseArray = options.ribbonCloseArray || false;
  26184. var ribbonClosePath = options.ribbonClosePath || false;
  26185. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26186. var updatable = options.updatable;
  26187. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26188. var instance = options.instance;
  26189. var invertUV = options.invertUV || false;
  26190. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26191. };
  26192. /**
  26193. * Creates lathe mesh.
  26194. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26195. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26196. *
  26197. * 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
  26198. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26199. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26200. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26201. * 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.
  26202. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26203. * 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
  26204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26206. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26208. */
  26209. MeshBuilder.CreateLathe = function (name, options, scene) {
  26210. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26211. var closed = (options.closed === undefined) ? true : options.closed;
  26212. var shape = options.shape;
  26213. var radius = options.radius || 1;
  26214. var tessellation = options.tessellation || 64;
  26215. var updatable = options.updatable;
  26216. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26217. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26218. var pi2 = Math.PI * 2;
  26219. var paths = new Array();
  26220. var invertUV = options.invertUV || false;
  26221. var i = 0;
  26222. var p = 0;
  26223. var step = pi2 / tessellation * arc;
  26224. var rotated;
  26225. var path = new Array();
  26226. ;
  26227. for (i = 0; i <= tessellation; i++) {
  26228. var path = [];
  26229. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26230. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26231. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26232. }
  26233. for (p = 0; p < shape.length; p++) {
  26234. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26235. path.push(rotated);
  26236. }
  26237. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26238. 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));
  26239. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26240. }
  26241. paths.push(path);
  26242. }
  26243. // lathe ribbon
  26244. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26245. return lathe;
  26246. };
  26247. /**
  26248. * Creates a plane mesh.
  26249. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26250. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26251. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26252. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26256. */
  26257. MeshBuilder.CreatePlane = function (name, options, scene) {
  26258. var plane = new BABYLON.Mesh(name, scene);
  26259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26260. plane.sideOrientation = options.sideOrientation;
  26261. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26262. vertexData.applyToMesh(plane, options.updatable);
  26263. if (options.sourcePlane) {
  26264. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26265. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26266. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26267. plane.rotate(vectorProduct, product);
  26268. }
  26269. return plane;
  26270. };
  26271. /**
  26272. * Creates a ground mesh.
  26273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26274. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26275. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26277. */
  26278. MeshBuilder.CreateGround = function (name, options, scene) {
  26279. var ground = new BABYLON.GroundMesh(name, scene);
  26280. ground._setReady(false);
  26281. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26282. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26283. ground._width = options.width || 1;
  26284. ground._height = options.height || 1;
  26285. ground._maxX = ground._width / 2;
  26286. ground._maxZ = ground._height / 2;
  26287. ground._minX = -ground._maxX;
  26288. ground._minZ = -ground._maxZ;
  26289. var vertexData = BABYLON.VertexData.CreateGround(options);
  26290. vertexData.applyToMesh(ground, options.updatable);
  26291. ground._setReady(true);
  26292. return ground;
  26293. };
  26294. /**
  26295. * Creates a tiled ground mesh.
  26296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26297. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26298. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26299. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26300. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26301. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26302. * numbers of subdivisions on the ground width and height of each tile.
  26303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26304. */
  26305. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26306. var tiledGround = new BABYLON.Mesh(name, scene);
  26307. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26308. vertexData.applyToMesh(tiledGround, options.updatable);
  26309. return tiledGround;
  26310. };
  26311. /**
  26312. * Creates a ground mesh from a height map.
  26313. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26314. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26315. * The parameter `url` sets the URL of the height map image resource.
  26316. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26317. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26318. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26319. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26320. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  26321. * 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).
  26322. * This function is passed the newly built mesh :
  26323. * ```javascript
  26324. * function(mesh) { // do things
  26325. * return; }
  26326. * ```
  26327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26328. */
  26329. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26330. var width = options.width || 10.0;
  26331. var height = options.height || 10.0;
  26332. var subdivisions = options.subdivisions || 1 | 0;
  26333. var minHeight = options.minHeight || 0.0;
  26334. var maxHeight = options.maxHeight || 10.0;
  26335. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26336. var updatable = options.updatable;
  26337. var onReady = options.onReady;
  26338. var ground = new BABYLON.GroundMesh(name, scene);
  26339. ground._subdivisionsX = subdivisions;
  26340. ground._subdivisionsY = subdivisions;
  26341. ground._width = width;
  26342. ground._height = height;
  26343. ground._maxX = ground._width / 2.0;
  26344. ground._maxZ = ground._height / 2.0;
  26345. ground._minX = -ground._maxX;
  26346. ground._minZ = -ground._maxZ;
  26347. ground._setReady(false);
  26348. var onload = function (img) {
  26349. // Getting height map data
  26350. var canvas = document.createElement("canvas");
  26351. var context = canvas.getContext("2d");
  26352. var bufferWidth = img.width;
  26353. var bufferHeight = img.height;
  26354. canvas.width = bufferWidth;
  26355. canvas.height = bufferHeight;
  26356. context.drawImage(img, 0, 0);
  26357. // Create VertexData from map data
  26358. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26359. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26360. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26361. width: width, height: height,
  26362. subdivisions: subdivisions,
  26363. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26364. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26365. });
  26366. vertexData.applyToMesh(ground, updatable);
  26367. ground._setReady(true);
  26368. //execute ready callback, if set
  26369. if (onReady) {
  26370. onReady(ground);
  26371. }
  26372. };
  26373. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26374. return ground;
  26375. };
  26376. /**
  26377. * Creates a tube mesh.
  26378. * 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.
  26379. *
  26380. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26381. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26382. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26383. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26384. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26385. * 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.
  26386. * It must return a radius value (positive float) :
  26387. * ```javascript
  26388. * var radiusFunction = function(i, distance) {
  26389. * // do things
  26390. * return radius; }
  26391. * ```
  26392. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26393. * 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
  26394. * 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
  26395. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26396. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26397. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26398. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26399. */
  26400. MeshBuilder.CreateTube = function (name, options, scene) {
  26401. var path = options.path;
  26402. var radius = options.radius || 1.0;
  26403. var tessellation = options.tessellation || 64 | 0;
  26404. var radiusFunction = options.radiusFunction;
  26405. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26406. var invertUV = options.invertUV || false;
  26407. var updatable = options.updatable;
  26408. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26409. var instance = options.instance;
  26410. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26411. // tube geometry
  26412. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26413. var tangents = path3D.getTangents();
  26414. var normals = path3D.getNormals();
  26415. var distances = path3D.getDistances();
  26416. var pi2 = Math.PI * 2;
  26417. var step = pi2 / tessellation * arc;
  26418. var returnRadius = function () { return radius; };
  26419. var radiusFunctionFinal = radiusFunction || returnRadius;
  26420. var circlePath;
  26421. var rad;
  26422. var normal;
  26423. var rotated;
  26424. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26425. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26426. for (var i = 0; i < path.length; i++) {
  26427. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26428. circlePath = Array(); // current circle array
  26429. normal = normals[i]; // current normal
  26430. for (var t = 0; t < tessellation; t++) {
  26431. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26432. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26433. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26434. rotated.scaleInPlace(rad).addInPlace(path[i]);
  26435. circlePath[t] = rotated;
  26436. }
  26437. circlePaths[index] = circlePath;
  26438. index++;
  26439. }
  26440. // cap
  26441. var capPath = function (nbPoints, pathIndex) {
  26442. var pointCap = Array();
  26443. for (var i = 0; i < nbPoints; i++) {
  26444. pointCap.push(path[pathIndex]);
  26445. }
  26446. return pointCap;
  26447. };
  26448. switch (cap) {
  26449. case BABYLON.Mesh.NO_CAP:
  26450. break;
  26451. case BABYLON.Mesh.CAP_START:
  26452. circlePaths[0] = capPath(tessellation, 0);
  26453. circlePaths[1] = circlePaths[2].slice(0);
  26454. break;
  26455. case BABYLON.Mesh.CAP_END:
  26456. circlePaths[index] = circlePaths[index - 1].slice(0);
  26457. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26458. break;
  26459. case BABYLON.Mesh.CAP_ALL:
  26460. circlePaths[0] = capPath(tessellation, 0);
  26461. circlePaths[1] = circlePaths[2].slice(0);
  26462. circlePaths[index] = circlePaths[index - 1].slice(0);
  26463. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26464. break;
  26465. default:
  26466. break;
  26467. }
  26468. return circlePaths;
  26469. };
  26470. var path3D;
  26471. var pathArray;
  26472. if (instance) {
  26473. var arc = options.arc || instance.arc;
  26474. path3D = (instance.path3D).update(path);
  26475. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  26476. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  26477. instance.path3D = path3D;
  26478. instance.pathArray = pathArray;
  26479. instance.arc = arc;
  26480. return instance;
  26481. }
  26482. // tube creation
  26483. path3D = new BABYLON.Path3D(path);
  26484. var newPathArray = new Array();
  26485. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26486. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  26487. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  26488. tube.pathArray = pathArray;
  26489. tube.path3D = path3D;
  26490. tube.tessellation = tessellation;
  26491. tube.cap = cap;
  26492. tube.arc = options.arc;
  26493. return tube;
  26494. };
  26495. /**
  26496. * Creates a polyhedron mesh.
  26497. *
  26498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26499. * 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
  26500. * to choose the wanted type.
  26501. * The parameter `size` (positive float, default 1) sets the polygon size.
  26502. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26503. * 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`.
  26504. * 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
  26505. * 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)`).
  26506. * 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
  26507. * 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.
  26508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26511. */
  26512. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26513. var polyhedron = new BABYLON.Mesh(name, scene);
  26514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26515. polyhedron.sideOrientation = options.sideOrientation;
  26516. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26517. vertexData.applyToMesh(polyhedron, options.updatable);
  26518. return polyhedron;
  26519. };
  26520. /**
  26521. * Creates a decal mesh.
  26522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  26523. * 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.
  26524. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26525. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26526. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26527. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26528. */
  26529. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  26530. var indices = sourceMesh.getIndices();
  26531. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26532. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26533. var position = options.position || BABYLON.Vector3.Zero();
  26534. var normal = options.normal || BABYLON.Vector3.Up();
  26535. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  26536. var angle = options.angle || 0;
  26537. // Getting correct rotation
  26538. if (!normal) {
  26539. var target = new BABYLON.Vector3(0, 0, 1);
  26540. var camera = sourceMesh.getScene().activeCamera;
  26541. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  26542. normal = camera.globalPosition.subtract(cameraWorldTarget);
  26543. }
  26544. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  26545. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  26546. var pitch = Math.atan2(normal.y, len);
  26547. // Matrix
  26548. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  26549. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  26550. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  26551. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  26552. var vertexData = new BABYLON.VertexData();
  26553. vertexData.indices = [];
  26554. vertexData.positions = [];
  26555. vertexData.normals = [];
  26556. vertexData.uvs = [];
  26557. var currentVertexDataIndex = 0;
  26558. var extractDecalVector3 = function (indexId) {
  26559. var vertexId = indices[indexId];
  26560. var result = new BABYLON.PositionNormalVertex();
  26561. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  26562. // Send vector to decal local world
  26563. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  26564. // Get normal
  26565. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  26566. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  26567. return result;
  26568. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  26569. var clip = function (vertices, axis) {
  26570. if (vertices.length === 0) {
  26571. return vertices;
  26572. }
  26573. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  26574. var clipVertices = function (v0, v1) {
  26575. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  26576. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  26577. };
  26578. var result = new Array();
  26579. for (var index = 0; index < vertices.length; index += 3) {
  26580. var v1Out;
  26581. var v2Out;
  26582. var v3Out;
  26583. var total = 0;
  26584. var nV1, nV2, nV3, nV4;
  26585. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  26586. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  26587. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  26588. v1Out = d1 > 0;
  26589. v2Out = d2 > 0;
  26590. v3Out = d3 > 0;
  26591. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  26592. switch (total) {
  26593. case 0:
  26594. result.push(vertices[index]);
  26595. result.push(vertices[index + 1]);
  26596. result.push(vertices[index + 2]);
  26597. break;
  26598. case 1:
  26599. if (v1Out) {
  26600. nV1 = vertices[index + 1];
  26601. nV2 = vertices[index + 2];
  26602. nV3 = clipVertices(vertices[index], nV1);
  26603. nV4 = clipVertices(vertices[index], nV2);
  26604. }
  26605. if (v2Out) {
  26606. nV1 = vertices[index];
  26607. nV2 = vertices[index + 2];
  26608. nV3 = clipVertices(vertices[index + 1], nV1);
  26609. nV4 = clipVertices(vertices[index + 1], nV2);
  26610. result.push(nV3);
  26611. result.push(nV2.clone());
  26612. result.push(nV1.clone());
  26613. result.push(nV2.clone());
  26614. result.push(nV3.clone());
  26615. result.push(nV4);
  26616. break;
  26617. }
  26618. if (v3Out) {
  26619. nV1 = vertices[index];
  26620. nV2 = vertices[index + 1];
  26621. nV3 = clipVertices(vertices[index + 2], nV1);
  26622. nV4 = clipVertices(vertices[index + 2], nV2);
  26623. }
  26624. result.push(nV1.clone());
  26625. result.push(nV2.clone());
  26626. result.push(nV3);
  26627. result.push(nV4);
  26628. result.push(nV3.clone());
  26629. result.push(nV2.clone());
  26630. break;
  26631. case 2:
  26632. if (!v1Out) {
  26633. nV1 = vertices[index].clone();
  26634. nV2 = clipVertices(nV1, vertices[index + 1]);
  26635. nV3 = clipVertices(nV1, vertices[index + 2]);
  26636. result.push(nV1);
  26637. result.push(nV2);
  26638. result.push(nV3);
  26639. }
  26640. if (!v2Out) {
  26641. nV1 = vertices[index + 1].clone();
  26642. nV2 = clipVertices(nV1, vertices[index + 2]);
  26643. nV3 = clipVertices(nV1, vertices[index]);
  26644. result.push(nV1);
  26645. result.push(nV2);
  26646. result.push(nV3);
  26647. }
  26648. if (!v3Out) {
  26649. nV1 = vertices[index + 2].clone();
  26650. nV2 = clipVertices(nV1, vertices[index]);
  26651. nV3 = clipVertices(nV1, vertices[index + 1]);
  26652. result.push(nV1);
  26653. result.push(nV2);
  26654. result.push(nV3);
  26655. }
  26656. break;
  26657. case 3:
  26658. break;
  26659. }
  26660. }
  26661. return result;
  26662. };
  26663. for (var index = 0; index < indices.length; index += 3) {
  26664. var faceVertices = new Array();
  26665. faceVertices.push(extractDecalVector3(index));
  26666. faceVertices.push(extractDecalVector3(index + 1));
  26667. faceVertices.push(extractDecalVector3(index + 2));
  26668. // Clip
  26669. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26670. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26671. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26672. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26673. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26674. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26675. if (faceVertices.length === 0) {
  26676. continue;
  26677. }
  26678. // Add UVs and get back to world
  26679. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26680. var vertex = faceVertices[vIndex];
  26681. //TODO check for Int32Array | Uint32Array | Uint16Array
  26682. vertexData.indices.push(currentVertexDataIndex);
  26683. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26684. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26685. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26686. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26687. currentVertexDataIndex++;
  26688. }
  26689. }
  26690. // Return mesh
  26691. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26692. vertexData.applyToMesh(decal);
  26693. decal.position = position.clone();
  26694. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26695. return decal;
  26696. };
  26697. // Privates
  26698. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26699. // extrusion geometry
  26700. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26701. var tangents = path3D.getTangents();
  26702. var normals = path3D.getNormals();
  26703. var binormals = path3D.getBinormals();
  26704. var distances = path3D.getDistances();
  26705. var angle = 0;
  26706. var returnScale = function () { return scale; };
  26707. var returnRotation = function () { return rotation; };
  26708. var rotate = custom ? rotateFunction : returnRotation;
  26709. var scl = custom ? scaleFunction : returnScale;
  26710. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26711. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26712. for (var i = 0; i < curve.length; i++) {
  26713. var shapePath = new Array();
  26714. var angleStep = rotate(i, distances[i]);
  26715. var scaleRatio = scl(i, distances[i]);
  26716. for (var p = 0; p < shape.length; p++) {
  26717. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26718. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26719. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26720. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26721. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26722. shapePath[p] = rotated;
  26723. }
  26724. shapePaths[index] = shapePath;
  26725. angle += angleStep;
  26726. index++;
  26727. }
  26728. // cap
  26729. var capPath = function (shapePath) {
  26730. var pointCap = Array();
  26731. var barycenter = BABYLON.Vector3.Zero();
  26732. var i;
  26733. for (i = 0; i < shapePath.length; i++) {
  26734. barycenter.addInPlace(shapePath[i]);
  26735. }
  26736. barycenter.scaleInPlace(1.0 / shapePath.length);
  26737. for (i = 0; i < shapePath.length; i++) {
  26738. pointCap.push(barycenter);
  26739. }
  26740. return pointCap;
  26741. };
  26742. switch (cap) {
  26743. case BABYLON.Mesh.NO_CAP:
  26744. break;
  26745. case BABYLON.Mesh.CAP_START:
  26746. shapePaths[0] = capPath(shapePaths[2]);
  26747. shapePaths[1] = shapePaths[2];
  26748. break;
  26749. case BABYLON.Mesh.CAP_END:
  26750. shapePaths[index] = shapePaths[index - 1];
  26751. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26752. break;
  26753. case BABYLON.Mesh.CAP_ALL:
  26754. shapePaths[0] = capPath(shapePaths[2]);
  26755. shapePaths[1] = shapePaths[2];
  26756. shapePaths[index] = shapePaths[index - 1];
  26757. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26758. break;
  26759. default:
  26760. break;
  26761. }
  26762. return shapePaths;
  26763. };
  26764. var path3D;
  26765. var pathArray;
  26766. if (instance) {
  26767. path3D = (instance.path3D).update(curve);
  26768. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26769. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26770. return instance;
  26771. }
  26772. // extruded shape creation
  26773. path3D = new BABYLON.Path3D(curve);
  26774. var newShapePaths = new Array();
  26775. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26776. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26777. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26778. extrudedGeneric.pathArray = pathArray;
  26779. extrudedGeneric.path3D = path3D;
  26780. extrudedGeneric.cap = cap;
  26781. return extrudedGeneric;
  26782. };
  26783. return MeshBuilder;
  26784. }());
  26785. BABYLON.MeshBuilder = MeshBuilder;
  26786. })(BABYLON || (BABYLON = {}));
  26787. //# sourceMappingURL=babylon.meshBuilder.js.map
  26788. var BABYLON;
  26789. (function (BABYLON) {
  26790. var BaseTexture = (function () {
  26791. function BaseTexture(scene) {
  26792. this.hasAlpha = false;
  26793. this.getAlphaFromRGB = false;
  26794. this.level = 1;
  26795. this.coordinatesIndex = 0;
  26796. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26797. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26798. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26799. this.anisotropicFilteringLevel = 4;
  26800. this.isCube = false;
  26801. this.isRenderTarget = false;
  26802. this.animations = new Array();
  26803. /**
  26804. * An event triggered when the texture is disposed.
  26805. * @type {BABYLON.Observable}
  26806. */
  26807. this.onDisposeObservable = new BABYLON.Observable();
  26808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26809. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26810. this._scene.textures.push(this);
  26811. this._uid = null;
  26812. }
  26813. Object.defineProperty(BaseTexture.prototype, "uid", {
  26814. get: function () {
  26815. if (!this._uid) {
  26816. this._uid = BABYLON.Tools.RandomId();
  26817. }
  26818. return this._uid;
  26819. },
  26820. enumerable: true,
  26821. configurable: true
  26822. });
  26823. BaseTexture.prototype.toString = function () {
  26824. return this.name;
  26825. };
  26826. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26827. set: function (callback) {
  26828. if (this._onDisposeObserver) {
  26829. this.onDisposeObservable.remove(this._onDisposeObserver);
  26830. }
  26831. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26832. },
  26833. enumerable: true,
  26834. configurable: true
  26835. });
  26836. BaseTexture.prototype.getScene = function () {
  26837. return this._scene;
  26838. };
  26839. BaseTexture.prototype.getTextureMatrix = function () {
  26840. return null;
  26841. };
  26842. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26843. return null;
  26844. };
  26845. BaseTexture.prototype.getInternalTexture = function () {
  26846. return this._texture;
  26847. };
  26848. BaseTexture.prototype.isReady = function () {
  26849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26850. return true;
  26851. }
  26852. if (this._texture) {
  26853. return this._texture.isReady;
  26854. }
  26855. return false;
  26856. };
  26857. BaseTexture.prototype.getSize = function () {
  26858. if (this._texture._width) {
  26859. return new BABYLON.Size(this._texture._width, this._texture._height);
  26860. }
  26861. if (this._texture._size) {
  26862. return new BABYLON.Size(this._texture._size, this._texture._size);
  26863. }
  26864. return BABYLON.Size.Zero();
  26865. };
  26866. BaseTexture.prototype.getBaseSize = function () {
  26867. if (!this.isReady() || !this._texture)
  26868. return BABYLON.Size.Zero();
  26869. if (this._texture._size) {
  26870. return new BABYLON.Size(this._texture._size, this._texture._size);
  26871. }
  26872. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26873. };
  26874. BaseTexture.prototype.scale = function (ratio) {
  26875. };
  26876. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26877. get: function () {
  26878. return false;
  26879. },
  26880. enumerable: true,
  26881. configurable: true
  26882. });
  26883. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26884. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26885. for (var index = 0; index < texturesCache.length; index++) {
  26886. var texturesCacheEntry = texturesCache[index];
  26887. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26888. texturesCache.splice(index, 1);
  26889. return;
  26890. }
  26891. }
  26892. };
  26893. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26894. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26895. for (var index = 0; index < texturesCache.length; index++) {
  26896. var texturesCacheEntry = texturesCache[index];
  26897. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26898. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26899. texturesCacheEntry.references++;
  26900. return texturesCacheEntry;
  26901. }
  26902. }
  26903. }
  26904. return null;
  26905. };
  26906. BaseTexture.prototype.delayLoad = function () {
  26907. };
  26908. BaseTexture.prototype.clone = function () {
  26909. return null;
  26910. };
  26911. BaseTexture.prototype.releaseInternalTexture = function () {
  26912. if (this._texture) {
  26913. this._scene.getEngine().releaseInternalTexture(this._texture);
  26914. delete this._texture;
  26915. }
  26916. };
  26917. BaseTexture.prototype.dispose = function () {
  26918. // Animations
  26919. this.getScene().stopAnimation(this);
  26920. // Remove from scene
  26921. this._scene._removePendingData(this);
  26922. var index = this._scene.textures.indexOf(this);
  26923. if (index >= 0) {
  26924. this._scene.textures.splice(index, 1);
  26925. }
  26926. if (this._texture === undefined) {
  26927. return;
  26928. }
  26929. // Release
  26930. this.releaseInternalTexture();
  26931. // Callback
  26932. this.onDisposeObservable.notifyObservers(this);
  26933. this.onDisposeObservable.clear();
  26934. };
  26935. BaseTexture.prototype.serialize = function () {
  26936. if (!this.name) {
  26937. return null;
  26938. }
  26939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26940. // Animations
  26941. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26942. return serializationObject;
  26943. };
  26944. return BaseTexture;
  26945. }());
  26946. __decorate([
  26947. BABYLON.serialize()
  26948. ], BaseTexture.prototype, "name", void 0);
  26949. __decorate([
  26950. BABYLON.serialize()
  26951. ], BaseTexture.prototype, "hasAlpha", void 0);
  26952. __decorate([
  26953. BABYLON.serialize()
  26954. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26955. __decorate([
  26956. BABYLON.serialize()
  26957. ], BaseTexture.prototype, "level", void 0);
  26958. __decorate([
  26959. BABYLON.serialize()
  26960. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26961. __decorate([
  26962. BABYLON.serialize()
  26963. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26964. __decorate([
  26965. BABYLON.serialize()
  26966. ], BaseTexture.prototype, "wrapU", void 0);
  26967. __decorate([
  26968. BABYLON.serialize()
  26969. ], BaseTexture.prototype, "wrapV", void 0);
  26970. __decorate([
  26971. BABYLON.serialize()
  26972. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26973. __decorate([
  26974. BABYLON.serialize()
  26975. ], BaseTexture.prototype, "isCube", void 0);
  26976. __decorate([
  26977. BABYLON.serialize()
  26978. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26979. BABYLON.BaseTexture = BaseTexture;
  26980. })(BABYLON || (BABYLON = {}));
  26981. //# sourceMappingURL=babylon.baseTexture.js.map
  26982. var BABYLON;
  26983. (function (BABYLON) {
  26984. var Texture = (function (_super) {
  26985. __extends(Texture, _super);
  26986. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26987. if (noMipmap === void 0) { noMipmap = false; }
  26988. if (invertY === void 0) { invertY = true; }
  26989. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26990. if (onLoad === void 0) { onLoad = null; }
  26991. if (onError === void 0) { onError = null; }
  26992. if (buffer === void 0) { buffer = null; }
  26993. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26994. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26995. var _this = _super.call(this, scene) || this;
  26996. _this.uOffset = 0;
  26997. _this.vOffset = 0;
  26998. _this.uScale = 1.0;
  26999. _this.vScale = 1.0;
  27000. _this.uAng = 0;
  27001. _this.vAng = 0;
  27002. _this.wAng = 0;
  27003. _this.name = url;
  27004. _this.url = url;
  27005. _this._noMipmap = noMipmap;
  27006. _this._invertY = invertY;
  27007. _this._samplingMode = samplingMode;
  27008. _this._buffer = buffer;
  27009. _this._deleteBuffer = deleteBuffer;
  27010. _this._format = format;
  27011. if (!url) {
  27012. return _this;
  27013. }
  27014. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  27015. var load = function () {
  27016. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  27017. _this.onLoadObservable.notifyObservers(true);
  27018. }
  27019. if (onLoad) {
  27020. onLoad();
  27021. }
  27022. };
  27023. if (!_this._texture) {
  27024. if (!scene.useDelayedTextureLoading) {
  27025. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  27026. if (deleteBuffer) {
  27027. delete _this._buffer;
  27028. }
  27029. }
  27030. else {
  27031. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27032. _this._delayedOnLoad = load;
  27033. _this._delayedOnError = onError;
  27034. }
  27035. }
  27036. else {
  27037. if (_this._texture.isReady) {
  27038. BABYLON.Tools.SetImmediate(function () { return load(); });
  27039. }
  27040. else {
  27041. _this._texture.onLoadedCallbacks.push(load);
  27042. }
  27043. }
  27044. return _this;
  27045. }
  27046. Object.defineProperty(Texture.prototype, "noMipmap", {
  27047. get: function () {
  27048. return this._noMipmap;
  27049. },
  27050. enumerable: true,
  27051. configurable: true
  27052. });
  27053. Texture.prototype.delayLoad = function () {
  27054. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27055. return;
  27056. }
  27057. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27058. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27059. if (!this._texture) {
  27060. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27061. if (this._deleteBuffer) {
  27062. delete this._buffer;
  27063. }
  27064. }
  27065. };
  27066. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27067. if (!this._texture) {
  27068. return;
  27069. }
  27070. this._samplingMode = samplingMode;
  27071. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27072. };
  27073. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27074. x *= this.uScale;
  27075. y *= this.vScale;
  27076. x -= 0.5 * this.uScale;
  27077. y -= 0.5 * this.vScale;
  27078. z -= 0.5;
  27079. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27080. t.x += 0.5 * this.uScale + this.uOffset;
  27081. t.y += 0.5 * this.vScale + this.vOffset;
  27082. t.z += 0.5;
  27083. };
  27084. Texture.prototype.getTextureMatrix = function () {
  27085. if (this.uOffset === this._cachedUOffset &&
  27086. this.vOffset === this._cachedVOffset &&
  27087. this.uScale === this._cachedUScale &&
  27088. this.vScale === this._cachedVScale &&
  27089. this.uAng === this._cachedUAng &&
  27090. this.vAng === this._cachedVAng &&
  27091. this.wAng === this._cachedWAng) {
  27092. return this._cachedTextureMatrix;
  27093. }
  27094. this._cachedUOffset = this.uOffset;
  27095. this._cachedVOffset = this.vOffset;
  27096. this._cachedUScale = this.uScale;
  27097. this._cachedVScale = this.vScale;
  27098. this._cachedUAng = this.uAng;
  27099. this._cachedVAng = this.vAng;
  27100. this._cachedWAng = this.wAng;
  27101. if (!this._cachedTextureMatrix) {
  27102. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27103. this._rowGenerationMatrix = new BABYLON.Matrix();
  27104. this._t0 = BABYLON.Vector3.Zero();
  27105. this._t1 = BABYLON.Vector3.Zero();
  27106. this._t2 = BABYLON.Vector3.Zero();
  27107. }
  27108. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27109. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27110. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27111. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27112. this._t1.subtractInPlace(this._t0);
  27113. this._t2.subtractInPlace(this._t0);
  27114. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27115. this._cachedTextureMatrix.m[0] = this._t1.x;
  27116. this._cachedTextureMatrix.m[1] = this._t1.y;
  27117. this._cachedTextureMatrix.m[2] = this._t1.z;
  27118. this._cachedTextureMatrix.m[4] = this._t2.x;
  27119. this._cachedTextureMatrix.m[5] = this._t2.y;
  27120. this._cachedTextureMatrix.m[6] = this._t2.z;
  27121. this._cachedTextureMatrix.m[8] = this._t0.x;
  27122. this._cachedTextureMatrix.m[9] = this._t0.y;
  27123. this._cachedTextureMatrix.m[10] = this._t0.z;
  27124. return this._cachedTextureMatrix;
  27125. };
  27126. Texture.prototype.getReflectionTextureMatrix = function () {
  27127. if (this.uOffset === this._cachedUOffset &&
  27128. this.vOffset === this._cachedVOffset &&
  27129. this.uScale === this._cachedUScale &&
  27130. this.vScale === this._cachedVScale &&
  27131. this.coordinatesMode === this._cachedCoordinatesMode) {
  27132. return this._cachedTextureMatrix;
  27133. }
  27134. if (!this._cachedTextureMatrix) {
  27135. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27136. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27137. }
  27138. this._cachedCoordinatesMode = this.coordinatesMode;
  27139. switch (this.coordinatesMode) {
  27140. case Texture.PLANAR_MODE:
  27141. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27142. this._cachedTextureMatrix[0] = this.uScale;
  27143. this._cachedTextureMatrix[5] = this.vScale;
  27144. this._cachedTextureMatrix[12] = this.uOffset;
  27145. this._cachedTextureMatrix[13] = this.vOffset;
  27146. break;
  27147. case Texture.PROJECTION_MODE:
  27148. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27149. this._projectionModeMatrix.m[0] = 0.5;
  27150. this._projectionModeMatrix.m[5] = -0.5;
  27151. this._projectionModeMatrix.m[10] = 0.0;
  27152. this._projectionModeMatrix.m[12] = 0.5;
  27153. this._projectionModeMatrix.m[13] = 0.5;
  27154. this._projectionModeMatrix.m[14] = 1.0;
  27155. this._projectionModeMatrix.m[15] = 1.0;
  27156. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27157. break;
  27158. default:
  27159. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27160. break;
  27161. }
  27162. return this._cachedTextureMatrix;
  27163. };
  27164. Texture.prototype.clone = function () {
  27165. var _this = this;
  27166. return BABYLON.SerializationHelper.Clone(function () {
  27167. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27168. }, this);
  27169. };
  27170. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27171. get: function () {
  27172. if (!this._onLoadObservarble) {
  27173. this._onLoadObservarble = new BABYLON.Observable();
  27174. }
  27175. return this._onLoadObservarble;
  27176. },
  27177. enumerable: true,
  27178. configurable: true
  27179. });
  27180. // Statics
  27181. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27182. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27183. if (onLoad === void 0) { onLoad = null; }
  27184. if (onError === void 0) { onError = null; }
  27185. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27186. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27187. };
  27188. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27189. if (parsedTexture.customType) {
  27190. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27191. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27192. }
  27193. if (parsedTexture.isCube) {
  27194. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27195. }
  27196. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27197. return null;
  27198. }
  27199. var texture = BABYLON.SerializationHelper.Parse(function () {
  27200. if (parsedTexture.mirrorPlane) {
  27201. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27202. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27203. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27204. return mirrorTexture;
  27205. }
  27206. else if (parsedTexture.isRenderTarget) {
  27207. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27208. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27209. return renderTargetTexture;
  27210. }
  27211. else {
  27212. var texture;
  27213. if (parsedTexture.base64String) {
  27214. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27215. }
  27216. else {
  27217. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27218. }
  27219. return texture;
  27220. }
  27221. }, parsedTexture, scene);
  27222. // Animations
  27223. if (parsedTexture.animations) {
  27224. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27225. var parsedAnimation = parsedTexture.animations[animationIndex];
  27226. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27227. }
  27228. }
  27229. return texture;
  27230. };
  27231. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27232. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27233. if (noMipmap === void 0) { noMipmap = false; }
  27234. if (invertY === void 0) { invertY = true; }
  27235. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27236. if (onLoad === void 0) { onLoad = null; }
  27237. if (onError === void 0) { onError = null; }
  27238. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27239. if (name.substr(0, 5) !== "data:") {
  27240. name = "data:" + name;
  27241. }
  27242. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27243. };
  27244. return Texture;
  27245. }(BABYLON.BaseTexture));
  27246. // Constants
  27247. Texture.NEAREST_SAMPLINGMODE = 1;
  27248. Texture.BILINEAR_SAMPLINGMODE = 2;
  27249. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27250. Texture.EXPLICIT_MODE = 0;
  27251. Texture.SPHERICAL_MODE = 1;
  27252. Texture.PLANAR_MODE = 2;
  27253. Texture.CUBIC_MODE = 3;
  27254. Texture.PROJECTION_MODE = 4;
  27255. Texture.SKYBOX_MODE = 5;
  27256. Texture.INVCUBIC_MODE = 6;
  27257. Texture.EQUIRECTANGULAR_MODE = 7;
  27258. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27259. Texture.CLAMP_ADDRESSMODE = 0;
  27260. Texture.WRAP_ADDRESSMODE = 1;
  27261. Texture.MIRROR_ADDRESSMODE = 2;
  27262. __decorate([
  27263. BABYLON.serialize()
  27264. ], Texture.prototype, "url", void 0);
  27265. __decorate([
  27266. BABYLON.serialize()
  27267. ], Texture.prototype, "uOffset", void 0);
  27268. __decorate([
  27269. BABYLON.serialize()
  27270. ], Texture.prototype, "vOffset", void 0);
  27271. __decorate([
  27272. BABYLON.serialize()
  27273. ], Texture.prototype, "uScale", void 0);
  27274. __decorate([
  27275. BABYLON.serialize()
  27276. ], Texture.prototype, "vScale", void 0);
  27277. __decorate([
  27278. BABYLON.serialize()
  27279. ], Texture.prototype, "uAng", void 0);
  27280. __decorate([
  27281. BABYLON.serialize()
  27282. ], Texture.prototype, "vAng", void 0);
  27283. __decorate([
  27284. BABYLON.serialize()
  27285. ], Texture.prototype, "wAng", void 0);
  27286. BABYLON.Texture = Texture;
  27287. })(BABYLON || (BABYLON = {}));
  27288. //# sourceMappingURL=babylon.texture.js.map
  27289. var BABYLON;
  27290. (function (BABYLON) {
  27291. var CubeTexture = (function (_super) {
  27292. __extends(CubeTexture, _super);
  27293. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27294. if (onLoad === void 0) { onLoad = null; }
  27295. if (onError === void 0) { onError = null; }
  27296. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27297. var _this = _super.call(this, scene) || this;
  27298. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27299. _this.name = rootUrl;
  27300. _this.url = rootUrl;
  27301. _this._noMipmap = noMipmap;
  27302. _this.hasAlpha = false;
  27303. _this._format = format;
  27304. if (!rootUrl && !files) {
  27305. return _this;
  27306. }
  27307. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27308. if (!files) {
  27309. if (!extensions) {
  27310. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27311. }
  27312. files = [];
  27313. for (var index = 0; index < extensions.length; index++) {
  27314. files.push(rootUrl + extensions[index]);
  27315. }
  27316. _this._extensions = extensions;
  27317. }
  27318. _this._files = files;
  27319. if (!_this._texture) {
  27320. if (!scene.useDelayedTextureLoading) {
  27321. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27322. }
  27323. else {
  27324. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27325. }
  27326. }
  27327. else if (onLoad) {
  27328. if (_this._texture.isReady) {
  27329. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27330. }
  27331. else {
  27332. _this._texture.onLoadedCallbacks.push(onLoad);
  27333. }
  27334. }
  27335. _this.isCube = true;
  27336. _this._textureMatrix = BABYLON.Matrix.Identity();
  27337. return _this;
  27338. }
  27339. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27340. return new CubeTexture("", scene, null, noMipmap, files);
  27341. };
  27342. // Methods
  27343. CubeTexture.prototype.delayLoad = function () {
  27344. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27345. return;
  27346. }
  27347. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27348. this._texture = this._getFromCache(this.url, this._noMipmap);
  27349. if (!this._texture) {
  27350. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27351. }
  27352. };
  27353. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27354. return this._textureMatrix;
  27355. };
  27356. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27357. var texture = BABYLON.SerializationHelper.Parse(function () {
  27358. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27359. }, parsedTexture, scene);
  27360. // Animations
  27361. if (parsedTexture.animations) {
  27362. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27363. var parsedAnimation = parsedTexture.animations[animationIndex];
  27364. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27365. }
  27366. }
  27367. return texture;
  27368. };
  27369. CubeTexture.prototype.clone = function () {
  27370. var _this = this;
  27371. return BABYLON.SerializationHelper.Clone(function () {
  27372. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27373. }, this);
  27374. };
  27375. return CubeTexture;
  27376. }(BABYLON.BaseTexture));
  27377. BABYLON.CubeTexture = CubeTexture;
  27378. })(BABYLON || (BABYLON = {}));
  27379. //# sourceMappingURL=babylon.cubeTexture.js.map
  27380. var BABYLON;
  27381. (function (BABYLON) {
  27382. var RenderTargetTexture = (function (_super) {
  27383. __extends(RenderTargetTexture, _super);
  27384. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27385. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27386. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27387. if (isCube === void 0) { isCube = false; }
  27388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27389. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27390. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27391. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27392. _this.isCube = isCube;
  27393. /**
  27394. * Use this list to define the list of mesh you want to render.
  27395. */
  27396. _this.renderList = new Array();
  27397. _this.renderParticles = true;
  27398. _this.renderSprites = false;
  27399. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27400. // Events
  27401. /**
  27402. * An event triggered when the texture is unbind.
  27403. * @type {BABYLON.Observable}
  27404. */
  27405. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27406. /**
  27407. * An event triggered before rendering the texture
  27408. * @type {BABYLON.Observable}
  27409. */
  27410. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27411. /**
  27412. * An event triggered after rendering the texture
  27413. * @type {BABYLON.Observable}
  27414. */
  27415. _this.onAfterRenderObservable = new BABYLON.Observable();
  27416. /**
  27417. * An event triggered after the texture clear
  27418. * @type {BABYLON.Observable}
  27419. */
  27420. _this.onClearObservable = new BABYLON.Observable();
  27421. _this._currentRefreshId = -1;
  27422. _this._refreshRate = 1;
  27423. _this._samples = 1;
  27424. _this.name = name;
  27425. _this.isRenderTarget = true;
  27426. _this._size = size;
  27427. _this._generateMipMaps = generateMipMaps;
  27428. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  27429. _this._renderTargetOptions = {
  27430. generateMipMaps: generateMipMaps,
  27431. type: type,
  27432. samplingMode: samplingMode,
  27433. generateDepthBuffer: generateDepthBuffer,
  27434. generateStencilBuffer: generateStencilBuffer
  27435. };
  27436. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27437. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27438. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27439. }
  27440. if (isCube) {
  27441. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  27442. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  27443. _this._textureMatrix = BABYLON.Matrix.Identity();
  27444. }
  27445. else {
  27446. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  27447. }
  27448. // Rendering groups
  27449. _this._renderingManager = new BABYLON.RenderingManager(scene);
  27450. return _this;
  27451. }
  27452. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  27453. get: function () {
  27454. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  27455. },
  27456. enumerable: true,
  27457. configurable: true
  27458. });
  27459. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  27460. get: function () {
  27461. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  27462. },
  27463. enumerable: true,
  27464. configurable: true
  27465. });
  27466. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  27467. get: function () {
  27468. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  27469. },
  27470. enumerable: true,
  27471. configurable: true
  27472. });
  27473. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  27474. set: function (callback) {
  27475. if (this._onAfterUnbindObserver) {
  27476. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  27477. }
  27478. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  27479. },
  27480. enumerable: true,
  27481. configurable: true
  27482. });
  27483. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  27484. set: function (callback) {
  27485. if (this._onBeforeRenderObserver) {
  27486. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27487. }
  27488. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27489. },
  27490. enumerable: true,
  27491. configurable: true
  27492. });
  27493. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  27494. set: function (callback) {
  27495. if (this._onAfterRenderObserver) {
  27496. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27497. }
  27498. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27499. },
  27500. enumerable: true,
  27501. configurable: true
  27502. });
  27503. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  27504. set: function (callback) {
  27505. if (this._onClearObserver) {
  27506. this.onClearObservable.remove(this._onClearObserver);
  27507. }
  27508. this._onClearObserver = this.onClearObservable.add(callback);
  27509. },
  27510. enumerable: true,
  27511. configurable: true
  27512. });
  27513. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  27514. get: function () {
  27515. return this._samples;
  27516. },
  27517. set: function (value) {
  27518. if (this._samples === value) {
  27519. return;
  27520. }
  27521. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  27522. },
  27523. enumerable: true,
  27524. configurable: true
  27525. });
  27526. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  27527. this._currentRefreshId = -1;
  27528. };
  27529. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  27530. get: function () {
  27531. return this._refreshRate;
  27532. },
  27533. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27534. set: function (value) {
  27535. this._refreshRate = value;
  27536. this.resetRefreshCounter();
  27537. },
  27538. enumerable: true,
  27539. configurable: true
  27540. });
  27541. RenderTargetTexture.prototype._shouldRender = function () {
  27542. if (this._currentRefreshId === -1) {
  27543. this._currentRefreshId = 1;
  27544. return true;
  27545. }
  27546. if (this.refreshRate === this._currentRefreshId) {
  27547. this._currentRefreshId = 1;
  27548. return true;
  27549. }
  27550. this._currentRefreshId++;
  27551. return false;
  27552. };
  27553. RenderTargetTexture.prototype.isReady = function () {
  27554. if (!this.getScene().renderTargetsEnabled) {
  27555. return false;
  27556. }
  27557. return _super.prototype.isReady.call(this);
  27558. };
  27559. RenderTargetTexture.prototype.getRenderSize = function () {
  27560. return this._size;
  27561. };
  27562. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  27563. get: function () {
  27564. return true;
  27565. },
  27566. enumerable: true,
  27567. configurable: true
  27568. });
  27569. RenderTargetTexture.prototype.scale = function (ratio) {
  27570. var newSize = this._size * ratio;
  27571. this.resize(newSize);
  27572. };
  27573. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  27574. if (this.isCube) {
  27575. return this._textureMatrix;
  27576. }
  27577. return _super.prototype.getReflectionTextureMatrix.call(this);
  27578. };
  27579. RenderTargetTexture.prototype.resize = function (size) {
  27580. this.releaseInternalTexture();
  27581. if (this.isCube) {
  27582. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  27583. }
  27584. else {
  27585. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  27586. }
  27587. };
  27588. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  27589. var scene = this.getScene();
  27590. var engine = scene.getEngine();
  27591. if (this.useCameraPostProcesses !== undefined) {
  27592. useCameraPostProcess = this.useCameraPostProcesses;
  27593. }
  27594. if (this._waitingRenderList) {
  27595. this.renderList = [];
  27596. for (var index = 0; index < this._waitingRenderList.length; index++) {
  27597. var id = this._waitingRenderList[index];
  27598. this.renderList.push(scene.getMeshByID(id));
  27599. }
  27600. delete this._waitingRenderList;
  27601. }
  27602. // Is predicate defined?
  27603. if (this.renderListPredicate) {
  27604. this.renderList.splice(0); // Clear previous renderList
  27605. var sceneMeshes = this.getScene().meshes;
  27606. for (var index = 0; index < sceneMeshes.length; index++) {
  27607. var mesh = sceneMeshes[index];
  27608. if (this.renderListPredicate(mesh)) {
  27609. this.renderList.push(mesh);
  27610. }
  27611. }
  27612. }
  27613. if (this.renderList && this.renderList.length === 0) {
  27614. return;
  27615. }
  27616. // Set custom projection.
  27617. // Needs to be before binding to prevent changing the aspect ratio.
  27618. if (this.activeCamera) {
  27619. engine.setViewport(this.activeCamera.viewport);
  27620. if (this.activeCamera !== scene.activeCamera) {
  27621. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  27622. }
  27623. }
  27624. else {
  27625. engine.setViewport(scene.activeCamera.viewport);
  27626. }
  27627. // Prepare renderingManager
  27628. this._renderingManager.reset();
  27629. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  27630. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  27631. var sceneRenderId = scene.getRenderId();
  27632. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  27633. var mesh = currentRenderList[meshIndex];
  27634. if (mesh) {
  27635. if (!mesh.isReady()) {
  27636. // Reset _currentRefreshId
  27637. this.resetRefreshCounter();
  27638. continue;
  27639. }
  27640. mesh._preActivateForIntermediateRendering(sceneRenderId);
  27641. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  27642. mesh._activate(sceneRenderId);
  27643. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27644. var subMesh = mesh.subMeshes[subIndex];
  27645. scene._activeIndices.addCount(subMesh.indexCount, false);
  27646. this._renderingManager.dispatch(subMesh);
  27647. }
  27648. }
  27649. }
  27650. }
  27651. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  27652. var particleSystem = scene.particleSystems[particleIndex];
  27653. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  27654. continue;
  27655. }
  27656. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  27657. this._renderingManager.dispatchParticles(particleSystem);
  27658. }
  27659. }
  27660. if (this.isCube) {
  27661. for (var face = 0; face < 6; face++) {
  27662. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27663. scene.incrementRenderId();
  27664. scene.resetCachedMaterial();
  27665. }
  27666. }
  27667. else {
  27668. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27669. }
  27670. this.onAfterUnbindObservable.notifyObservers(this);
  27671. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  27672. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  27673. }
  27674. engine.setViewport(scene.activeCamera.viewport);
  27675. scene.resetCachedMaterial();
  27676. };
  27677. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  27678. var _this = this;
  27679. var scene = this.getScene();
  27680. var engine = scene.getEngine();
  27681. // Bind
  27682. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  27683. if (this.isCube) {
  27684. engine.bindFramebuffer(this._texture, faceIndex);
  27685. }
  27686. else {
  27687. engine.bindFramebuffer(this._texture);
  27688. }
  27689. }
  27690. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27691. // Clear
  27692. if (this.onClearObservable.hasObservers()) {
  27693. this.onClearObservable.notifyObservers(engine);
  27694. }
  27695. else {
  27696. engine.clear(scene.clearColor, true, true, true);
  27697. }
  27698. if (!this._doNotChangeAspectRatio) {
  27699. scene.updateTransformMatrix(true);
  27700. }
  27701. // Render
  27702. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27703. if (useCameraPostProcess) {
  27704. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27705. }
  27706. if (!this._doNotChangeAspectRatio) {
  27707. scene.updateTransformMatrix(true);
  27708. }
  27709. // Dump ?
  27710. if (dumpForDebug) {
  27711. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27712. }
  27713. // Unbind
  27714. if (!this.isCube || faceIndex === 5) {
  27715. if (this.isCube) {
  27716. if (faceIndex === 5) {
  27717. engine.generateMipMapsForCubemap(this._texture);
  27718. }
  27719. }
  27720. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  27721. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  27722. });
  27723. }
  27724. else {
  27725. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27726. }
  27727. };
  27728. /**
  27729. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27730. * This allowed control for front to back rendering or reversly depending of the special needs.
  27731. *
  27732. * @param renderingGroupId The rendering group id corresponding to its index
  27733. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27734. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27735. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27736. */
  27737. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27738. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27739. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27740. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27741. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27742. };
  27743. /**
  27744. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27745. *
  27746. * @param renderingGroupId The rendering group id corresponding to its index
  27747. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27748. */
  27749. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27750. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27751. };
  27752. RenderTargetTexture.prototype.clone = function () {
  27753. var textureSize = this.getSize();
  27754. 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);
  27755. // Base texture
  27756. newTexture.hasAlpha = this.hasAlpha;
  27757. newTexture.level = this.level;
  27758. // RenderTarget Texture
  27759. newTexture.coordinatesMode = this.coordinatesMode;
  27760. newTexture.renderList = this.renderList.slice(0);
  27761. return newTexture;
  27762. };
  27763. RenderTargetTexture.prototype.serialize = function () {
  27764. if (!this.name) {
  27765. return null;
  27766. }
  27767. var serializationObject = _super.prototype.serialize.call(this);
  27768. serializationObject.renderTargetSize = this.getRenderSize();
  27769. serializationObject.renderList = [];
  27770. for (var index = 0; index < this.renderList.length; index++) {
  27771. serializationObject.renderList.push(this.renderList[index].id);
  27772. }
  27773. return serializationObject;
  27774. };
  27775. return RenderTargetTexture;
  27776. }(BABYLON.Texture));
  27777. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27778. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27779. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27780. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27781. })(BABYLON || (BABYLON = {}));
  27782. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27783. var BABYLON;
  27784. (function (BABYLON) {
  27785. var ProceduralTexture = (function (_super) {
  27786. __extends(ProceduralTexture, _super);
  27787. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27788. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27789. if (isCube === void 0) { isCube = false; }
  27790. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27791. _this.isCube = isCube;
  27792. _this.isEnabled = true;
  27793. _this._currentRefreshId = -1;
  27794. _this._refreshRate = 1;
  27795. _this._vertexBuffers = {};
  27796. _this._uniforms = new Array();
  27797. _this._samplers = new Array();
  27798. _this._textures = new Array();
  27799. _this._floats = new Array();
  27800. _this._floatsArrays = {};
  27801. _this._colors3 = new Array();
  27802. _this._colors4 = new Array();
  27803. _this._vectors2 = new Array();
  27804. _this._vectors3 = new Array();
  27805. _this._matrices = new Array();
  27806. _this._fallbackTextureUsed = false;
  27807. scene._proceduralTextures.push(_this);
  27808. _this.name = name;
  27809. _this.isRenderTarget = true;
  27810. _this._size = size;
  27811. _this._generateMipMaps = generateMipMaps;
  27812. _this.setFragment(fragment);
  27813. _this._fallbackTexture = fallbackTexture;
  27814. var engine = scene.getEngine();
  27815. if (isCube) {
  27816. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27817. _this.setFloat("face", 0);
  27818. }
  27819. else {
  27820. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27821. }
  27822. // VBO
  27823. var vertices = [];
  27824. vertices.push(1, 1);
  27825. vertices.push(-1, 1);
  27826. vertices.push(-1, -1);
  27827. vertices.push(1, -1);
  27828. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27829. // Indices
  27830. var indices = [];
  27831. indices.push(0);
  27832. indices.push(1);
  27833. indices.push(2);
  27834. indices.push(0);
  27835. indices.push(2);
  27836. indices.push(3);
  27837. _this._indexBuffer = engine.createIndexBuffer(indices);
  27838. return _this;
  27839. }
  27840. ProceduralTexture.prototype.reset = function () {
  27841. if (this._effect === undefined) {
  27842. return;
  27843. }
  27844. var engine = this.getScene().getEngine();
  27845. engine._releaseEffect(this._effect);
  27846. };
  27847. ProceduralTexture.prototype.isReady = function () {
  27848. var _this = this;
  27849. var engine = this.getScene().getEngine();
  27850. var shaders;
  27851. if (!this._fragment) {
  27852. return false;
  27853. }
  27854. if (this._fallbackTextureUsed) {
  27855. return true;
  27856. }
  27857. if (this._fragment.fragmentElement !== undefined) {
  27858. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27859. }
  27860. else {
  27861. shaders = { vertex: "procedural", fragment: this._fragment };
  27862. }
  27863. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27864. _this.releaseInternalTexture();
  27865. if (_this._fallbackTexture) {
  27866. _this._texture = _this._fallbackTexture._texture;
  27867. _this._texture.references++;
  27868. }
  27869. _this._fallbackTextureUsed = true;
  27870. });
  27871. return this._effect.isReady();
  27872. };
  27873. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27874. this._currentRefreshId = -1;
  27875. };
  27876. ProceduralTexture.prototype.setFragment = function (fragment) {
  27877. this._fragment = fragment;
  27878. };
  27879. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27880. get: function () {
  27881. return this._refreshRate;
  27882. },
  27883. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27884. set: function (value) {
  27885. this._refreshRate = value;
  27886. this.resetRefreshCounter();
  27887. },
  27888. enumerable: true,
  27889. configurable: true
  27890. });
  27891. ProceduralTexture.prototype._shouldRender = function () {
  27892. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27893. return false;
  27894. }
  27895. if (this._fallbackTextureUsed) {
  27896. return false;
  27897. }
  27898. if (this._currentRefreshId === -1) {
  27899. this._currentRefreshId = 1;
  27900. return true;
  27901. }
  27902. if (this.refreshRate === this._currentRefreshId) {
  27903. this._currentRefreshId = 1;
  27904. return true;
  27905. }
  27906. this._currentRefreshId++;
  27907. return false;
  27908. };
  27909. ProceduralTexture.prototype.getRenderSize = function () {
  27910. return this._size;
  27911. };
  27912. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27913. if (this._fallbackTextureUsed) {
  27914. return;
  27915. }
  27916. this.releaseInternalTexture();
  27917. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27918. };
  27919. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27920. if (this._uniforms.indexOf(uniformName) === -1) {
  27921. this._uniforms.push(uniformName);
  27922. }
  27923. };
  27924. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27925. if (this._samplers.indexOf(name) === -1) {
  27926. this._samplers.push(name);
  27927. }
  27928. this._textures[name] = texture;
  27929. return this;
  27930. };
  27931. ProceduralTexture.prototype.setFloat = function (name, value) {
  27932. this._checkUniform(name);
  27933. this._floats[name] = value;
  27934. return this;
  27935. };
  27936. ProceduralTexture.prototype.setFloats = function (name, value) {
  27937. this._checkUniform(name);
  27938. this._floatsArrays[name] = value;
  27939. return this;
  27940. };
  27941. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27942. this._checkUniform(name);
  27943. this._colors3[name] = value;
  27944. return this;
  27945. };
  27946. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27947. this._checkUniform(name);
  27948. this._colors4[name] = value;
  27949. return this;
  27950. };
  27951. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27952. this._checkUniform(name);
  27953. this._vectors2[name] = value;
  27954. return this;
  27955. };
  27956. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27957. this._checkUniform(name);
  27958. this._vectors3[name] = value;
  27959. return this;
  27960. };
  27961. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27962. this._checkUniform(name);
  27963. this._matrices[name] = value;
  27964. return this;
  27965. };
  27966. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27967. var scene = this.getScene();
  27968. var engine = scene.getEngine();
  27969. // Render
  27970. engine.enableEffect(this._effect);
  27971. engine.setState(false);
  27972. // Texture
  27973. for (var name in this._textures) {
  27974. this._effect.setTexture(name, this._textures[name]);
  27975. }
  27976. // Float
  27977. for (name in this._floats) {
  27978. this._effect.setFloat(name, this._floats[name]);
  27979. }
  27980. // Floats
  27981. for (name in this._floatsArrays) {
  27982. this._effect.setArray(name, this._floatsArrays[name]);
  27983. }
  27984. // Color3
  27985. for (name in this._colors3) {
  27986. this._effect.setColor3(name, this._colors3[name]);
  27987. }
  27988. // Color4
  27989. for (name in this._colors4) {
  27990. var color = this._colors4[name];
  27991. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27992. }
  27993. // Vector2
  27994. for (name in this._vectors2) {
  27995. this._effect.setVector2(name, this._vectors2[name]);
  27996. }
  27997. // Vector3
  27998. for (name in this._vectors3) {
  27999. this._effect.setVector3(name, this._vectors3[name]);
  28000. }
  28001. // Matrix
  28002. for (name in this._matrices) {
  28003. this._effect.setMatrix(name, this._matrices[name]);
  28004. }
  28005. if (this.isCube) {
  28006. for (var face = 0; face < 6; face++) {
  28007. engine.bindFramebuffer(this._texture, face);
  28008. // VBOs
  28009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28010. this._effect.setFloat("face", face);
  28011. // Clear
  28012. engine.clear(scene.clearColor, true, true, true);
  28013. // Draw order
  28014. engine.draw(true, 0, 6);
  28015. // Mipmaps
  28016. if (face === 5) {
  28017. engine.generateMipMapsForCubemap(this._texture);
  28018. }
  28019. }
  28020. }
  28021. else {
  28022. engine.bindFramebuffer(this._texture);
  28023. // VBOs
  28024. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28025. // Clear
  28026. engine.clear(scene.clearColor, true, true, true);
  28027. // Draw order
  28028. engine.draw(true, 0, 6);
  28029. }
  28030. // Unbind
  28031. engine.unBindFramebuffer(this._texture, this.isCube);
  28032. if (this.onGenerated) {
  28033. this.onGenerated();
  28034. }
  28035. };
  28036. ProceduralTexture.prototype.clone = function () {
  28037. var textureSize = this.getSize();
  28038. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  28039. // Base texture
  28040. newTexture.hasAlpha = this.hasAlpha;
  28041. newTexture.level = this.level;
  28042. // RenderTarget Texture
  28043. newTexture.coordinatesMode = this.coordinatesMode;
  28044. return newTexture;
  28045. };
  28046. ProceduralTexture.prototype.dispose = function () {
  28047. var index = this.getScene()._proceduralTextures.indexOf(this);
  28048. if (index >= 0) {
  28049. this.getScene()._proceduralTextures.splice(index, 1);
  28050. }
  28051. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28052. if (vertexBuffer) {
  28053. vertexBuffer.dispose();
  28054. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28055. }
  28056. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28057. this._indexBuffer = null;
  28058. }
  28059. _super.prototype.dispose.call(this);
  28060. };
  28061. return ProceduralTexture;
  28062. }(BABYLON.Texture));
  28063. BABYLON.ProceduralTexture = ProceduralTexture;
  28064. })(BABYLON || (BABYLON = {}));
  28065. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28066. /// <reference path="babylon.renderTargetTexture.ts" />
  28067. var BABYLON;
  28068. (function (BABYLON) {
  28069. var MirrorTexture = (function (_super) {
  28070. __extends(MirrorTexture, _super);
  28071. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28072. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28074. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28075. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28076. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28077. _this._transformMatrix = BABYLON.Matrix.Zero();
  28078. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28079. _this.onBeforeRenderObservable.add(function () {
  28080. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28081. _this._savedViewMatrix = scene.getViewMatrix();
  28082. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28083. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28084. scene.clipPlane = _this.mirrorPlane;
  28085. scene.getEngine().cullBackFaces = false;
  28086. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28087. });
  28088. _this.onAfterRenderObservable.add(function () {
  28089. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28090. scene.getEngine().cullBackFaces = true;
  28091. scene._mirroredCameraPosition = null;
  28092. delete scene.clipPlane;
  28093. });
  28094. return _this;
  28095. }
  28096. MirrorTexture.prototype.clone = function () {
  28097. var textureSize = this.getSize();
  28098. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28099. // Base texture
  28100. newTexture.hasAlpha = this.hasAlpha;
  28101. newTexture.level = this.level;
  28102. // Mirror Texture
  28103. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28104. newTexture.renderList = this.renderList.slice(0);
  28105. return newTexture;
  28106. };
  28107. MirrorTexture.prototype.serialize = function () {
  28108. if (!this.name) {
  28109. return null;
  28110. }
  28111. var serializationObject = _super.prototype.serialize.call(this);
  28112. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28113. return serializationObject;
  28114. };
  28115. return MirrorTexture;
  28116. }(BABYLON.RenderTargetTexture));
  28117. BABYLON.MirrorTexture = MirrorTexture;
  28118. })(BABYLON || (BABYLON = {}));
  28119. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28120. /// <reference path="babylon.renderTargetTexture.ts" />
  28121. var BABYLON;
  28122. (function (BABYLON) {
  28123. /**
  28124. * Creates a refraction texture used by refraction channel of the standard material.
  28125. * @param name the texture name
  28126. * @param size size of the underlying texture
  28127. * @param scene root scene
  28128. */
  28129. var RefractionTexture = (function (_super) {
  28130. __extends(RefractionTexture, _super);
  28131. function RefractionTexture(name, size, scene, generateMipMaps) {
  28132. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28133. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28134. _this.depth = 2.0;
  28135. _this.onBeforeRenderObservable.add(function () {
  28136. scene.clipPlane = _this.refractionPlane;
  28137. });
  28138. _this.onAfterRenderObservable.add(function () {
  28139. delete scene.clipPlane;
  28140. });
  28141. return _this;
  28142. }
  28143. RefractionTexture.prototype.clone = function () {
  28144. var textureSize = this.getSize();
  28145. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28146. // Base texture
  28147. newTexture.hasAlpha = this.hasAlpha;
  28148. newTexture.level = this.level;
  28149. // Refraction Texture
  28150. newTexture.refractionPlane = this.refractionPlane.clone();
  28151. newTexture.renderList = this.renderList.slice(0);
  28152. newTexture.depth = this.depth;
  28153. return newTexture;
  28154. };
  28155. RefractionTexture.prototype.serialize = function () {
  28156. if (!this.name) {
  28157. return null;
  28158. }
  28159. var serializationObject = _super.prototype.serialize.call(this);
  28160. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28161. serializationObject.depth = this.depth;
  28162. return serializationObject;
  28163. };
  28164. return RefractionTexture;
  28165. }(BABYLON.RenderTargetTexture));
  28166. BABYLON.RefractionTexture = RefractionTexture;
  28167. })(BABYLON || (BABYLON = {}));
  28168. //# sourceMappingURL=babylon.refractionTexture.js.map
  28169. /// <reference path="babylon.texture.ts" />
  28170. var BABYLON;
  28171. (function (BABYLON) {
  28172. var DynamicTexture = (function (_super) {
  28173. __extends(DynamicTexture, _super);
  28174. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28176. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28177. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28178. _this.name = name;
  28179. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28180. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28181. _this._generateMipMaps = generateMipMaps;
  28182. if (options.getContext) {
  28183. _this._canvas = options;
  28184. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28185. }
  28186. else {
  28187. _this._canvas = document.createElement("canvas");
  28188. if (options.width) {
  28189. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28190. }
  28191. else {
  28192. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28193. }
  28194. }
  28195. var textureSize = _this.getSize();
  28196. _this._canvas.width = textureSize.width;
  28197. _this._canvas.height = textureSize.height;
  28198. _this._context = _this._canvas.getContext("2d");
  28199. return _this;
  28200. }
  28201. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28202. get: function () {
  28203. return true;
  28204. },
  28205. enumerable: true,
  28206. configurable: true
  28207. });
  28208. DynamicTexture.prototype.scale = function (ratio) {
  28209. var textureSize = this.getSize();
  28210. textureSize.width *= ratio;
  28211. textureSize.height *= ratio;
  28212. this._canvas.width = textureSize.width;
  28213. this._canvas.height = textureSize.height;
  28214. this.releaseInternalTexture();
  28215. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28216. };
  28217. DynamicTexture.prototype.getContext = function () {
  28218. return this._context;
  28219. };
  28220. DynamicTexture.prototype.clear = function () {
  28221. var size = this.getSize();
  28222. this._context.fillRect(0, 0, size.width, size.height);
  28223. };
  28224. DynamicTexture.prototype.update = function (invertY) {
  28225. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28226. };
  28227. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28228. if (update === void 0) { update = true; }
  28229. var size = this.getSize();
  28230. if (clearColor) {
  28231. this._context.fillStyle = clearColor;
  28232. this._context.fillRect(0, 0, size.width, size.height);
  28233. }
  28234. this._context.font = font;
  28235. if (x === null || x === undefined) {
  28236. var textSize = this._context.measureText(text);
  28237. x = (size.width - textSize.width) / 2;
  28238. }
  28239. if (y === null || y === undefined) {
  28240. var fontSize = parseInt((font.replace(/\D/g, '')));
  28241. ;
  28242. y = (size.height / 2) + (fontSize / 3.65);
  28243. }
  28244. this._context.fillStyle = color;
  28245. this._context.fillText(text, x, y);
  28246. if (update) {
  28247. this.update(invertY);
  28248. }
  28249. };
  28250. DynamicTexture.prototype.clone = function () {
  28251. var textureSize = this.getSize();
  28252. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28253. // Base texture
  28254. newTexture.hasAlpha = this.hasAlpha;
  28255. newTexture.level = this.level;
  28256. // Dynamic Texture
  28257. newTexture.wrapU = this.wrapU;
  28258. newTexture.wrapV = this.wrapV;
  28259. return newTexture;
  28260. };
  28261. return DynamicTexture;
  28262. }(BABYLON.Texture));
  28263. BABYLON.DynamicTexture = DynamicTexture;
  28264. })(BABYLON || (BABYLON = {}));
  28265. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28266. var BABYLON;
  28267. (function (BABYLON) {
  28268. var VideoTexture = (function (_super) {
  28269. __extends(VideoTexture, _super);
  28270. /**
  28271. * Creates a video texture.
  28272. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28273. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28274. * @param {BABYLON.Scene} scene is obviously the current scene.
  28275. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28276. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28277. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28278. */
  28279. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28280. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28281. if (invertY === void 0) { invertY = false; }
  28282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28283. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28284. _this._autoLaunch = true;
  28285. var urls;
  28286. _this.name = name;
  28287. if (urlsOrVideo instanceof HTMLVideoElement) {
  28288. _this.video = urlsOrVideo;
  28289. }
  28290. else {
  28291. urls = urlsOrVideo;
  28292. _this.video = document.createElement("video");
  28293. _this.video.autoplay = false;
  28294. _this.video.loop = true;
  28295. }
  28296. _this._generateMipMaps = generateMipMaps;
  28297. _this._samplingMode = samplingMode;
  28298. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28299. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28300. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28301. }
  28302. else {
  28303. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28304. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28305. _this._generateMipMaps = false;
  28306. }
  28307. if (urls) {
  28308. _this.video.addEventListener("canplaythrough", function () {
  28309. _this._createTexture();
  28310. });
  28311. urls.forEach(function (url) {
  28312. var source = document.createElement("source");
  28313. source.src = url;
  28314. _this.video.appendChild(source);
  28315. });
  28316. }
  28317. else {
  28318. _this._createTexture();
  28319. }
  28320. _this._lastUpdate = BABYLON.Tools.Now;
  28321. return _this;
  28322. }
  28323. VideoTexture.prototype._createTexture = function () {
  28324. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28325. this._texture.isReady = true;
  28326. };
  28327. VideoTexture.prototype.update = function () {
  28328. if (this._autoLaunch) {
  28329. this._autoLaunch = false;
  28330. this.video.play();
  28331. }
  28332. var now = BABYLON.Tools.Now;
  28333. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28334. return false;
  28335. }
  28336. this._lastUpdate = now;
  28337. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28338. return true;
  28339. };
  28340. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28341. var video = document.createElement("video");
  28342. var constraintsDeviceId;
  28343. if (constraints && constraints.deviceId) {
  28344. constraintsDeviceId = {
  28345. exact: constraints.deviceId
  28346. };
  28347. }
  28348. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28349. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28350. if (navigator.getUserMedia) {
  28351. navigator.getUserMedia({
  28352. video: {
  28353. deviceId: constraintsDeviceId,
  28354. width: {
  28355. min: (constraints && constraints.minWidth) || 256,
  28356. max: (constraints && constraints.maxWidth) || 640
  28357. },
  28358. height: {
  28359. min: (constraints && constraints.minHeight) || 256,
  28360. max: (constraints && constraints.maxHeight) || 480
  28361. }
  28362. }
  28363. }, function (stream) {
  28364. if (video.mozSrcObject !== undefined) {
  28365. video.mozSrcObject = stream;
  28366. }
  28367. else {
  28368. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28369. }
  28370. video.play();
  28371. if (onReady) {
  28372. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28373. }
  28374. }, function (e) {
  28375. BABYLON.Tools.Error(e.name);
  28376. });
  28377. }
  28378. };
  28379. return VideoTexture;
  28380. }(BABYLON.Texture));
  28381. BABYLON.VideoTexture = VideoTexture;
  28382. })(BABYLON || (BABYLON = {}));
  28383. //# sourceMappingURL=babylon.videoTexture.js.map
  28384. /// <reference path="babylon.proceduralTexture.ts" />
  28385. var BABYLON;
  28386. (function (BABYLON) {
  28387. var CustomProceduralTexture = (function (_super) {
  28388. __extends(CustomProceduralTexture, _super);
  28389. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28390. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28391. _this._animate = true;
  28392. _this._time = 0;
  28393. _this._texturePath = texturePath;
  28394. //Try to load json
  28395. _this.loadJson(texturePath);
  28396. _this.refreshRate = 1;
  28397. return _this;
  28398. }
  28399. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28400. var _this = this;
  28401. var that = this;
  28402. function noConfigFile() {
  28403. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  28404. try {
  28405. that.setFragment(that._texturePath);
  28406. }
  28407. catch (ex) {
  28408. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  28409. }
  28410. }
  28411. var configFileUrl = jsonUrl + "/config.json";
  28412. var xhr = new XMLHttpRequest();
  28413. xhr.open("GET", configFileUrl, true);
  28414. xhr.addEventListener("load", function () {
  28415. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  28416. try {
  28417. _this._config = JSON.parse(xhr.response);
  28418. _this.updateShaderUniforms();
  28419. _this.updateTextures();
  28420. _this.setFragment(_this._texturePath + "/custom");
  28421. _this._animate = _this._config.animate;
  28422. _this.refreshRate = _this._config.refreshrate;
  28423. }
  28424. catch (ex) {
  28425. noConfigFile();
  28426. }
  28427. }
  28428. else {
  28429. noConfigFile();
  28430. }
  28431. }, false);
  28432. xhr.addEventListener("error", function () {
  28433. noConfigFile();
  28434. }, false);
  28435. try {
  28436. xhr.send();
  28437. }
  28438. catch (ex) {
  28439. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  28440. }
  28441. };
  28442. CustomProceduralTexture.prototype.isReady = function () {
  28443. if (!_super.prototype.isReady.call(this)) {
  28444. return false;
  28445. }
  28446. for (var name in this._textures) {
  28447. var texture = this._textures[name];
  28448. if (!texture.isReady()) {
  28449. return false;
  28450. }
  28451. }
  28452. return true;
  28453. };
  28454. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28455. if (this._animate) {
  28456. this._time += this.getScene().getAnimationRatio() * 0.03;
  28457. this.updateShaderUniforms();
  28458. }
  28459. _super.prototype.render.call(this, useCameraPostProcess);
  28460. };
  28461. CustomProceduralTexture.prototype.updateTextures = function () {
  28462. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  28463. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  28464. }
  28465. };
  28466. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  28467. if (this._config) {
  28468. for (var j = 0; j < this._config.uniforms.length; j++) {
  28469. var uniform = this._config.uniforms[j];
  28470. switch (uniform.type) {
  28471. case "float":
  28472. this.setFloat(uniform.name, uniform.value);
  28473. break;
  28474. case "color3":
  28475. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  28476. break;
  28477. case "color4":
  28478. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  28479. break;
  28480. case "vector2":
  28481. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  28482. break;
  28483. case "vector3":
  28484. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  28485. break;
  28486. }
  28487. }
  28488. }
  28489. this.setFloat("time", this._time);
  28490. };
  28491. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  28492. get: function () {
  28493. return this._animate;
  28494. },
  28495. set: function (value) {
  28496. this._animate = value;
  28497. },
  28498. enumerable: true,
  28499. configurable: true
  28500. });
  28501. return CustomProceduralTexture;
  28502. }(BABYLON.ProceduralTexture));
  28503. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  28504. })(BABYLON || (BABYLON = {}));
  28505. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  28506. var BABYLON;
  28507. (function (BABYLON) {
  28508. var EffectFallbacks = (function () {
  28509. function EffectFallbacks() {
  28510. this._defines = {};
  28511. this._currentRank = 32;
  28512. this._maxRank = -1;
  28513. }
  28514. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28515. if (!this._defines[rank]) {
  28516. if (rank < this._currentRank) {
  28517. this._currentRank = rank;
  28518. }
  28519. if (rank > this._maxRank) {
  28520. this._maxRank = rank;
  28521. }
  28522. this._defines[rank] = new Array();
  28523. }
  28524. this._defines[rank].push(define);
  28525. };
  28526. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  28527. this._meshRank = rank;
  28528. this._mesh = mesh;
  28529. if (rank < this._currentRank) {
  28530. this._currentRank = rank;
  28531. }
  28532. if (rank > this._maxRank) {
  28533. this._maxRank = rank;
  28534. }
  28535. };
  28536. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  28537. get: function () {
  28538. return this._currentRank <= this._maxRank;
  28539. },
  28540. enumerable: true,
  28541. configurable: true
  28542. });
  28543. EffectFallbacks.prototype.reduce = function (currentDefines) {
  28544. // First we try to switch to CPU skinning
  28545. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  28546. this._mesh.computeBonesUsingShaders = false;
  28547. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  28548. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  28549. var scene = this._mesh.getScene();
  28550. for (var index = 0; index < scene.meshes.length; index++) {
  28551. var otherMesh = scene.meshes[index];
  28552. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  28553. otherMesh.computeBonesUsingShaders = false;
  28554. }
  28555. }
  28556. }
  28557. else {
  28558. var currentFallbacks = this._defines[this._currentRank];
  28559. if (currentFallbacks) {
  28560. for (var index = 0; index < currentFallbacks.length; index++) {
  28561. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  28562. }
  28563. }
  28564. this._currentRank++;
  28565. }
  28566. return currentDefines;
  28567. };
  28568. return EffectFallbacks;
  28569. }());
  28570. BABYLON.EffectFallbacks = EffectFallbacks;
  28571. var Effect = (function () {
  28572. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  28573. var _this = this;
  28574. this.uniqueId = 0;
  28575. this._isReady = false;
  28576. this._compilationError = "";
  28577. this._valueCache = {};
  28578. this._engine = engine;
  28579. this.name = baseName;
  28580. this.defines = defines;
  28581. this._uniformsNames = uniformsNames.concat(samplers);
  28582. this._samplers = samplers;
  28583. this._attributesNames = attributesNames;
  28584. this.onError = onError;
  28585. this.onCompiled = onCompiled;
  28586. this._indexParameters = indexParameters;
  28587. this.uniqueId = Effect._uniqueIdSeed++;
  28588. var vertexSource;
  28589. var fragmentSource;
  28590. if (baseName.vertexElement) {
  28591. vertexSource = document.getElementById(baseName.vertexElement);
  28592. if (!vertexSource) {
  28593. vertexSource = baseName.vertexElement;
  28594. }
  28595. }
  28596. else {
  28597. vertexSource = baseName.vertex || baseName;
  28598. }
  28599. if (baseName.fragmentElement) {
  28600. fragmentSource = document.getElementById(baseName.fragmentElement);
  28601. if (!fragmentSource) {
  28602. fragmentSource = baseName.fragmentElement;
  28603. }
  28604. }
  28605. else {
  28606. fragmentSource = baseName.fragment || baseName;
  28607. }
  28608. this._loadVertexShader(vertexSource, function (vertexCode) {
  28609. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  28610. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  28611. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  28612. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  28613. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  28614. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  28615. });
  28616. });
  28617. });
  28618. });
  28619. });
  28620. });
  28621. }
  28622. Object.defineProperty(Effect.prototype, "key", {
  28623. get: function () {
  28624. return this._key;
  28625. },
  28626. enumerable: true,
  28627. configurable: true
  28628. });
  28629. // Properties
  28630. Effect.prototype.isReady = function () {
  28631. return this._isReady;
  28632. };
  28633. Effect.prototype.getProgram = function () {
  28634. return this._program;
  28635. };
  28636. Effect.prototype.getAttributesNames = function () {
  28637. return this._attributesNames;
  28638. };
  28639. Effect.prototype.getAttributeLocation = function (index) {
  28640. return this._attributes[index];
  28641. };
  28642. Effect.prototype.getAttributeLocationByName = function (name) {
  28643. var index = this._attributesNames.indexOf(name);
  28644. return this._attributes[index];
  28645. };
  28646. Effect.prototype.getAttributesCount = function () {
  28647. return this._attributes.length;
  28648. };
  28649. Effect.prototype.getUniformIndex = function (uniformName) {
  28650. return this._uniformsNames.indexOf(uniformName);
  28651. };
  28652. Effect.prototype.getUniform = function (uniformName) {
  28653. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  28654. };
  28655. Effect.prototype.getSamplers = function () {
  28656. return this._samplers;
  28657. };
  28658. Effect.prototype.getCompilationError = function () {
  28659. return this._compilationError;
  28660. };
  28661. Effect.prototype.getVertexShaderSource = function () {
  28662. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  28663. };
  28664. Effect.prototype.getFragmentShaderSource = function () {
  28665. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  28666. };
  28667. // Methods
  28668. Effect.prototype._loadVertexShader = function (vertex, callback) {
  28669. // DOM element ?
  28670. if (vertex instanceof HTMLElement) {
  28671. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  28672. callback(vertexCode);
  28673. return;
  28674. }
  28675. // Base64 encoded ?
  28676. if (vertex.substr(0, 7) === "base64:") {
  28677. var vertexBinary = window.atob(vertex.substr(7));
  28678. callback(vertexBinary);
  28679. return;
  28680. }
  28681. // Is in local store ?
  28682. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  28683. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  28684. return;
  28685. }
  28686. var vertexShaderUrl;
  28687. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  28688. vertexShaderUrl = vertex;
  28689. }
  28690. else {
  28691. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  28692. }
  28693. // Vertex shader
  28694. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  28695. };
  28696. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  28697. // DOM element ?
  28698. if (fragment instanceof HTMLElement) {
  28699. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  28700. callback(fragmentCode);
  28701. return;
  28702. }
  28703. // Base64 encoded ?
  28704. if (fragment.substr(0, 7) === "base64:") {
  28705. var fragmentBinary = window.atob(fragment.substr(7));
  28706. callback(fragmentBinary);
  28707. return;
  28708. }
  28709. // Is in local store ?
  28710. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  28711. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  28712. return;
  28713. }
  28714. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  28715. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28716. return;
  28717. }
  28718. var fragmentShaderUrl;
  28719. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28720. fragmentShaderUrl = fragment;
  28721. }
  28722. else {
  28723. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28724. }
  28725. // Fragment shader
  28726. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28727. };
  28728. Effect.prototype._dumpShadersName = function () {
  28729. if (this.name.vertexElement) {
  28730. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28731. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28732. }
  28733. else if (this.name.vertex) {
  28734. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28735. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28736. }
  28737. else {
  28738. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28739. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28740. }
  28741. };
  28742. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28743. var preparedSourceCode = this._processPrecision(sourceCode);
  28744. if (this._engine.webGLVersion == 1) {
  28745. callback(preparedSourceCode);
  28746. return;
  28747. }
  28748. // Already converted
  28749. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28750. callback(preparedSourceCode);
  28751. return;
  28752. }
  28753. // Remove extensions
  28754. // #extension GL_OES_standard_derivatives : enable
  28755. // #extension GL_EXT_shader_texture_lod : enable
  28756. // #extension GL_EXT_frag_depth : enable
  28757. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28758. var result = preparedSourceCode.replace(regex, "");
  28759. // Migrate to GLSL v300
  28760. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28761. result = result.replace(/attribute[ \t]/g, "in ");
  28762. result = result.replace(/[ \t]attribute/g, " in");
  28763. if (isFragment) {
  28764. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  28765. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28766. result = result.replace(/texture2D\(/g, "texture(");
  28767. result = result.replace(/textureCube\(/g, "texture(");
  28768. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28769. result = result.replace(/gl_FragColor/g, "glFragColor");
  28770. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28771. }
  28772. callback(result);
  28773. };
  28774. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28775. var _this = this;
  28776. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28777. var match = regex.exec(sourceCode);
  28778. var returnValue = new String(sourceCode);
  28779. while (match != null) {
  28780. var includeFile = match[1];
  28781. if (Effect.IncludesShadersStore[includeFile]) {
  28782. // Substitution
  28783. var includeContent = Effect.IncludesShadersStore[includeFile];
  28784. if (match[2]) {
  28785. var splits = match[3].split(",");
  28786. for (var index = 0; index < splits.length; index += 2) {
  28787. var source = new RegExp(splits[index], "g");
  28788. var dest = splits[index + 1];
  28789. includeContent = includeContent.replace(source, dest);
  28790. }
  28791. }
  28792. if (match[4]) {
  28793. var indexString = match[5];
  28794. if (indexString.indexOf("..") !== -1) {
  28795. var indexSplits = indexString.split("..");
  28796. var minIndex = parseInt(indexSplits[0]);
  28797. var maxIndex = parseInt(indexSplits[1]);
  28798. var sourceIncludeContent = includeContent.slice(0);
  28799. includeContent = "";
  28800. if (isNaN(maxIndex)) {
  28801. maxIndex = this._indexParameters[indexSplits[1]];
  28802. }
  28803. for (var i = minIndex; i <= maxIndex; i++) {
  28804. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28805. }
  28806. }
  28807. else {
  28808. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28809. }
  28810. }
  28811. // Replace
  28812. returnValue = returnValue.replace(match[0], includeContent);
  28813. }
  28814. else {
  28815. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28816. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28817. Effect.IncludesShadersStore[includeFile] = fileContent;
  28818. _this._processIncludes(returnValue, callback);
  28819. });
  28820. return;
  28821. }
  28822. match = regex.exec(sourceCode);
  28823. }
  28824. callback(returnValue);
  28825. };
  28826. Effect.prototype._processPrecision = function (source) {
  28827. if (source.indexOf("precision highp float") === -1) {
  28828. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28829. source = "precision mediump float;\n" + source;
  28830. }
  28831. else {
  28832. source = "precision highp float;\n" + source;
  28833. }
  28834. }
  28835. else {
  28836. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28837. source = source.replace("precision highp float", "precision mediump float");
  28838. }
  28839. }
  28840. return source;
  28841. };
  28842. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28843. try {
  28844. var engine = this._engine;
  28845. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28846. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28847. this._attributes = engine.getAttributes(this._program, attributesNames);
  28848. var index;
  28849. for (index = 0; index < this._samplers.length; index++) {
  28850. var sampler = this.getUniform(this._samplers[index]);
  28851. if (sampler == null) {
  28852. this._samplers.splice(index, 1);
  28853. index--;
  28854. }
  28855. }
  28856. engine.bindSamplers(this);
  28857. this._compilationError = "";
  28858. this._isReady = true;
  28859. if (this.onCompiled) {
  28860. this.onCompiled(this);
  28861. }
  28862. }
  28863. catch (e) {
  28864. this._compilationError = e.message;
  28865. // Let's go through fallbacks then
  28866. BABYLON.Tools.Error("Unable to compile effect: ");
  28867. BABYLON.Tools.Error("Defines: " + defines);
  28868. BABYLON.Tools.Error("Error: " + this._compilationError);
  28869. this._dumpShadersName();
  28870. if (fallbacks && fallbacks.isMoreFallbacks) {
  28871. BABYLON.Tools.Error("Trying next fallback.");
  28872. defines = fallbacks.reduce(defines);
  28873. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28874. }
  28875. else {
  28876. if (this.onError) {
  28877. this.onError(this, this._compilationError);
  28878. }
  28879. }
  28880. }
  28881. };
  28882. Object.defineProperty(Effect.prototype, "isSupported", {
  28883. get: function () {
  28884. return this._compilationError === "";
  28885. },
  28886. enumerable: true,
  28887. configurable: true
  28888. });
  28889. Effect.prototype._bindTexture = function (channel, texture) {
  28890. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28891. };
  28892. Effect.prototype.setTexture = function (channel, texture) {
  28893. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28894. };
  28895. Effect.prototype.setTextureArray = function (channel, textures) {
  28896. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28897. var initialPos = this._samplers.indexOf(channel);
  28898. for (var index = 1; index < textures.length; index++) {
  28899. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28900. }
  28901. }
  28902. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28903. };
  28904. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28905. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28906. };
  28907. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28908. var changed = false;
  28909. var cache = this._valueCache[uniformName];
  28910. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28911. changed = true;
  28912. cache = new BABYLON.Matrix();
  28913. }
  28914. var tm = cache.m;
  28915. var om = matrix.m;
  28916. for (var index = 0; index < 16; index++) {
  28917. if (tm[index] !== om[index]) {
  28918. tm[index] = om[index];
  28919. changed = true;
  28920. }
  28921. }
  28922. this._valueCache[uniformName] = cache;
  28923. return changed;
  28924. };
  28925. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28926. var cache = this._valueCache[uniformName];
  28927. if (!cache) {
  28928. cache = [x, y];
  28929. this._valueCache[uniformName] = cache;
  28930. return true;
  28931. }
  28932. var changed = false;
  28933. if (cache[0] !== x) {
  28934. cache[0] = x;
  28935. changed = true;
  28936. }
  28937. if (cache[1] !== y) {
  28938. cache[1] = y;
  28939. changed = true;
  28940. }
  28941. return changed;
  28942. };
  28943. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28944. var cache = this._valueCache[uniformName];
  28945. if (!cache) {
  28946. cache = [x, y, z];
  28947. this._valueCache[uniformName] = cache;
  28948. return true;
  28949. }
  28950. var changed = false;
  28951. if (cache[0] !== x) {
  28952. cache[0] = x;
  28953. changed = true;
  28954. }
  28955. if (cache[1] !== y) {
  28956. cache[1] = y;
  28957. changed = true;
  28958. }
  28959. if (cache[2] !== z) {
  28960. cache[2] = z;
  28961. changed = true;
  28962. }
  28963. return changed;
  28964. };
  28965. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28966. var cache = this._valueCache[uniformName];
  28967. if (!cache) {
  28968. cache = [x, y, z, w];
  28969. this._valueCache[uniformName] = cache;
  28970. return true;
  28971. }
  28972. var changed = false;
  28973. if (cache[0] !== x) {
  28974. cache[0] = x;
  28975. changed = true;
  28976. }
  28977. if (cache[1] !== y) {
  28978. cache[1] = y;
  28979. changed = true;
  28980. }
  28981. if (cache[2] !== z) {
  28982. cache[2] = z;
  28983. changed = true;
  28984. }
  28985. if (cache[3] !== w) {
  28986. cache[3] = w;
  28987. changed = true;
  28988. }
  28989. return changed;
  28990. };
  28991. Effect.prototype.setIntArray = function (uniformName, array) {
  28992. this._valueCache[uniformName] = null;
  28993. this._engine.setIntArray(this.getUniform(uniformName), array);
  28994. return this;
  28995. };
  28996. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28997. this._valueCache[uniformName] = null;
  28998. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28999. return this;
  29000. };
  29001. Effect.prototype.setIntArray3 = function (uniformName, array) {
  29002. this._valueCache[uniformName] = null;
  29003. this._engine.setIntArray3(this.getUniform(uniformName), array);
  29004. return this;
  29005. };
  29006. Effect.prototype.setIntArray4 = function (uniformName, array) {
  29007. this._valueCache[uniformName] = null;
  29008. this._engine.setIntArray4(this.getUniform(uniformName), array);
  29009. return this;
  29010. };
  29011. Effect.prototype.setFloatArray = function (uniformName, array) {
  29012. this._valueCache[uniformName] = null;
  29013. this._engine.setFloatArray(this.getUniform(uniformName), array);
  29014. return this;
  29015. };
  29016. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  29017. this._valueCache[uniformName] = null;
  29018. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  29019. return this;
  29020. };
  29021. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  29022. this._valueCache[uniformName] = null;
  29023. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  29024. return this;
  29025. };
  29026. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  29027. this._valueCache[uniformName] = null;
  29028. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  29029. return this;
  29030. };
  29031. Effect.prototype.setArray = function (uniformName, array) {
  29032. this._valueCache[uniformName] = null;
  29033. this._engine.setArray(this.getUniform(uniformName), array);
  29034. return this;
  29035. };
  29036. Effect.prototype.setArray2 = function (uniformName, array) {
  29037. this._valueCache[uniformName] = null;
  29038. this._engine.setArray2(this.getUniform(uniformName), array);
  29039. return this;
  29040. };
  29041. Effect.prototype.setArray3 = function (uniformName, array) {
  29042. this._valueCache[uniformName] = null;
  29043. this._engine.setArray3(this.getUniform(uniformName), array);
  29044. return this;
  29045. };
  29046. Effect.prototype.setArray4 = function (uniformName, array) {
  29047. this._valueCache[uniformName] = null;
  29048. this._engine.setArray4(this.getUniform(uniformName), array);
  29049. return this;
  29050. };
  29051. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29052. this._valueCache[uniformName] = null;
  29053. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29054. return this;
  29055. };
  29056. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29057. if (this._cacheMatrix(uniformName, matrix)) {
  29058. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29059. }
  29060. return this;
  29061. };
  29062. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29063. this._valueCache[uniformName] = null;
  29064. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29065. return this;
  29066. };
  29067. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29068. this._valueCache[uniformName] = null;
  29069. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29070. return this;
  29071. };
  29072. Effect.prototype.setFloat = function (uniformName, value) {
  29073. var cache = this._valueCache[uniformName];
  29074. if (cache !== undefined && cache === value)
  29075. return this;
  29076. this._valueCache[uniformName] = value;
  29077. this._engine.setFloat(this.getUniform(uniformName), value);
  29078. return this;
  29079. };
  29080. Effect.prototype.setBool = function (uniformName, bool) {
  29081. var cache = this._valueCache[uniformName];
  29082. if (cache !== undefined && cache === bool)
  29083. return this;
  29084. this._valueCache[uniformName] = bool;
  29085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29086. return this;
  29087. };
  29088. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29089. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29090. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29091. }
  29092. return this;
  29093. };
  29094. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29095. if (this._cacheFloat2(uniformName, x, y)) {
  29096. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29097. }
  29098. return this;
  29099. };
  29100. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29101. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29102. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29103. }
  29104. return this;
  29105. };
  29106. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29107. if (this._cacheFloat3(uniformName, x, y, z)) {
  29108. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29109. }
  29110. return this;
  29111. };
  29112. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29113. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29114. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29115. }
  29116. return this;
  29117. };
  29118. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29119. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29120. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29121. }
  29122. return this;
  29123. };
  29124. Effect.prototype.setColor3 = function (uniformName, color3) {
  29125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29126. this._engine.setColor3(this.getUniform(uniformName), color3);
  29127. }
  29128. return this;
  29129. };
  29130. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29131. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29132. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29133. }
  29134. return this;
  29135. };
  29136. Effect.prototype._recombineShader = function (node) {
  29137. if (node.define) {
  29138. if (node.condition) {
  29139. var defineIndex = this.defines.indexOf("#define " + node.define);
  29140. if (defineIndex === -1) {
  29141. return null;
  29142. }
  29143. var nextComma = this.defines.indexOf("\n", defineIndex);
  29144. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29145. var condition = defineValue + node.condition;
  29146. if (!eval(condition)) {
  29147. return null;
  29148. }
  29149. }
  29150. else if (node.ndef) {
  29151. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29152. return null;
  29153. }
  29154. }
  29155. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29156. return null;
  29157. }
  29158. }
  29159. var result = "";
  29160. for (var index = 0; index < node.children.length; index++) {
  29161. var line = node.children[index];
  29162. if (line.children) {
  29163. var combined = this._recombineShader(line);
  29164. if (combined !== null) {
  29165. result += combined + "\r\n";
  29166. }
  29167. continue;
  29168. }
  29169. if (line.length > 0) {
  29170. result += line + "\r\n";
  29171. }
  29172. }
  29173. return result;
  29174. };
  29175. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29176. var root = {
  29177. children: []
  29178. };
  29179. var currentNode = root;
  29180. var lines = shaderString.split("\n");
  29181. for (var index = 0; index < lines.length; index++) {
  29182. var line = lines[index].trim();
  29183. // #ifdef
  29184. var pos = line.indexOf("#ifdef ");
  29185. if (pos !== -1) {
  29186. var define = line.substr(pos + 7);
  29187. var newNode = {
  29188. condition: null,
  29189. ndef: false,
  29190. define: define,
  29191. children: [],
  29192. parent: currentNode
  29193. };
  29194. currentNode.children.push(newNode);
  29195. currentNode = newNode;
  29196. continue;
  29197. }
  29198. // #ifndef
  29199. var pos = line.indexOf("#ifndef ");
  29200. if (pos !== -1) {
  29201. var define = line.substr(pos + 8);
  29202. newNode = {
  29203. condition: null,
  29204. define: define,
  29205. ndef: true,
  29206. children: [],
  29207. parent: currentNode
  29208. };
  29209. currentNode.children.push(newNode);
  29210. currentNode = newNode;
  29211. continue;
  29212. }
  29213. // #if
  29214. var pos = line.indexOf("#if ");
  29215. if (pos !== -1) {
  29216. var define = line.substr(pos + 4).trim();
  29217. var conditionPos = define.indexOf(" ");
  29218. newNode = {
  29219. condition: define.substr(conditionPos + 1),
  29220. define: define.substr(0, conditionPos),
  29221. ndef: false,
  29222. children: [],
  29223. parent: currentNode
  29224. };
  29225. currentNode.children.push(newNode);
  29226. currentNode = newNode;
  29227. continue;
  29228. }
  29229. // #endif
  29230. pos = line.indexOf("#endif");
  29231. if (pos !== -1) {
  29232. currentNode = currentNode.parent;
  29233. continue;
  29234. }
  29235. currentNode.children.push(line);
  29236. }
  29237. // Recombine
  29238. return this._recombineShader(root);
  29239. };
  29240. return Effect;
  29241. }());
  29242. Effect._uniqueIdSeed = 0;
  29243. // Statics
  29244. Effect.ShadersStore = {};
  29245. Effect.IncludesShadersStore = {};
  29246. BABYLON.Effect = Effect;
  29247. })(BABYLON || (BABYLON = {}));
  29248. //# sourceMappingURL=babylon.effect.js.map
  29249. var BABYLON;
  29250. (function (BABYLON) {
  29251. var MaterialHelper = (function () {
  29252. function MaterialHelper() {
  29253. }
  29254. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  29255. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29256. var lightIndex = 0;
  29257. var needNormals = false;
  29258. var needRebuild = false;
  29259. var needShadows = false;
  29260. var lightmapMode = false;
  29261. for (var index = 0; index < scene.lights.length; index++) {
  29262. var light = scene.lights[index];
  29263. if (!light.isEnabled()) {
  29264. continue;
  29265. }
  29266. // Excluded check
  29267. if (light._excludedMeshesIds.length > 0) {
  29268. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  29269. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  29270. if (excludedMesh) {
  29271. light.excludedMeshes.push(excludedMesh);
  29272. }
  29273. }
  29274. light._excludedMeshesIds = [];
  29275. }
  29276. // Included check
  29277. if (light._includedOnlyMeshesIds.length > 0) {
  29278. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  29279. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  29280. if (includedOnlyMesh) {
  29281. light.includedOnlyMeshes.push(includedOnlyMesh);
  29282. }
  29283. }
  29284. light._includedOnlyMeshesIds = [];
  29285. }
  29286. if (!light.canAffectMesh(mesh)) {
  29287. continue;
  29288. }
  29289. needNormals = true;
  29290. if (defines["LIGHT" + lightIndex] === undefined) {
  29291. needRebuild = true;
  29292. }
  29293. defines["LIGHT" + lightIndex] = true;
  29294. var type;
  29295. if (light instanceof BABYLON.SpotLight) {
  29296. type = "SPOTLIGHT" + lightIndex;
  29297. }
  29298. else if (light instanceof BABYLON.HemisphericLight) {
  29299. type = "HEMILIGHT" + lightIndex;
  29300. }
  29301. else if (light instanceof BABYLON.PointLight) {
  29302. type = "POINTLIGHT" + lightIndex;
  29303. }
  29304. else {
  29305. type = "DIRLIGHT" + lightIndex;
  29306. }
  29307. if (defines[type] === undefined) {
  29308. needRebuild = true;
  29309. }
  29310. defines[type] = true;
  29311. // Specular
  29312. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  29313. defines["SPECULARTERM"] = true;
  29314. }
  29315. // Shadows
  29316. if (scene.shadowsEnabled) {
  29317. var shadowGenerator = light.getShadowGenerator();
  29318. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29319. if (defines["SHADOW" + lightIndex] === undefined) {
  29320. needRebuild = true;
  29321. }
  29322. defines["SHADOW" + lightIndex] = true;
  29323. defines["SHADOWS"] = true;
  29324. if (shadowGenerator.usePoissonSampling) {
  29325. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  29326. needRebuild = true;
  29327. }
  29328. defines["SHADOWPCF" + lightIndex] = true;
  29329. }
  29330. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  29331. if (defines["SHADOWESM" + lightIndex] === undefined) {
  29332. needRebuild = true;
  29333. }
  29334. defines["SHADOWESM" + lightIndex] = true;
  29335. }
  29336. needShadows = true;
  29337. }
  29338. }
  29339. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29340. lightmapMode = true;
  29341. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  29342. needRebuild = true;
  29343. }
  29344. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  29345. needRebuild = true;
  29346. }
  29347. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29348. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  29349. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  29350. }
  29351. }
  29352. lightIndex++;
  29353. if (lightIndex === maxSimultaneousLights)
  29354. break;
  29355. }
  29356. var caps = scene.getEngine().getCaps();
  29357. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  29358. if (defines["SHADOWFULLFLOAT"] === undefined) {
  29359. needRebuild = true;
  29360. }
  29361. defines["SHADOWFULLFLOAT"] = true;
  29362. }
  29363. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  29364. needRebuild = true;
  29365. }
  29366. if (lightmapMode) {
  29367. defines["LIGHTMAPEXCLUDED"] = true;
  29368. }
  29369. if (needRebuild) {
  29370. defines.rebuild();
  29371. }
  29372. return needNormals;
  29373. };
  29374. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29375. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29376. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29377. if (!defines["LIGHT" + lightIndex]) {
  29378. break;
  29379. }
  29380. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29381. samplersList.push("shadowSampler" + lightIndex);
  29382. }
  29383. };
  29384. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29385. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29386. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29387. if (!defines["LIGHT" + lightIndex]) {
  29388. break;
  29389. }
  29390. if (lightIndex > 0) {
  29391. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29392. }
  29393. if (defines["SHADOW" + lightIndex]) {
  29394. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29395. }
  29396. if (defines["SHADOWPCF" + lightIndex]) {
  29397. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29398. }
  29399. if (defines["SHADOWESM" + lightIndex]) {
  29400. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29401. }
  29402. }
  29403. };
  29404. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29405. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29406. fallbacks.addCPUSkinningFallback(0, mesh);
  29407. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29408. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29409. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  29410. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29411. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  29412. }
  29413. }
  29414. };
  29415. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  29416. if (defines["INSTANCES"]) {
  29417. attribs.push("world0");
  29418. attribs.push("world1");
  29419. attribs.push("world2");
  29420. attribs.push("world3");
  29421. }
  29422. };
  29423. // Bindings
  29424. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  29425. var shadowGenerator = light.getShadowGenerator();
  29426. if (mesh.receiveShadows && shadowGenerator) {
  29427. if (!light.needCube()) {
  29428. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  29429. }
  29430. else {
  29431. if (!depthValuesAlreadySet) {
  29432. depthValuesAlreadySet = true;
  29433. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  29434. }
  29435. }
  29436. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  29437. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  29438. }
  29439. return depthValuesAlreadySet;
  29440. };
  29441. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  29442. if (light instanceof BABYLON.PointLight) {
  29443. // Point Light
  29444. light.transferToEffect(effect, "vLightData" + lightIndex);
  29445. }
  29446. else if (light instanceof BABYLON.DirectionalLight) {
  29447. // Directional Light
  29448. light.transferToEffect(effect, "vLightData" + lightIndex);
  29449. }
  29450. else if (light instanceof BABYLON.SpotLight) {
  29451. // Spot Light
  29452. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  29453. }
  29454. else if (light instanceof BABYLON.HemisphericLight) {
  29455. // Hemispheric Light
  29456. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  29457. }
  29458. };
  29459. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  29460. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29461. var lightIndex = 0;
  29462. var depthValuesAlreadySet = false;
  29463. for (var index = 0; index < scene.lights.length; index++) {
  29464. var light = scene.lights[index];
  29465. if (!light.isEnabled()) {
  29466. continue;
  29467. }
  29468. if (!light.canAffectMesh(mesh)) {
  29469. continue;
  29470. }
  29471. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29472. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  29473. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  29474. if (defines["SPECULARTERM"]) {
  29475. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  29476. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  29477. }
  29478. // Shadows
  29479. if (scene.shadowsEnabled) {
  29480. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  29481. }
  29482. lightIndex++;
  29483. if (lightIndex === maxSimultaneousLights)
  29484. break;
  29485. }
  29486. };
  29487. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  29488. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  29489. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  29490. effect.setColor3("vFogColor", scene.fogColor);
  29491. }
  29492. };
  29493. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  29494. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29495. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  29496. if (matrices) {
  29497. effect.setMatrices("mBones", matrices);
  29498. }
  29499. }
  29500. };
  29501. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  29502. if (defines["LOGARITHMICDEPTH"]) {
  29503. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  29504. }
  29505. };
  29506. MaterialHelper.BindClipPlane = function (effect, scene) {
  29507. if (scene.clipPlane) {
  29508. var clipPlane = scene.clipPlane;
  29509. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29510. }
  29511. };
  29512. return MaterialHelper;
  29513. }());
  29514. BABYLON.MaterialHelper = MaterialHelper;
  29515. })(BABYLON || (BABYLON = {}));
  29516. //# sourceMappingURL=babylon.materialHelper.js.map
  29517. var BABYLON;
  29518. (function (BABYLON) {
  29519. var FresnelParameters = (function () {
  29520. function FresnelParameters() {
  29521. this.isEnabled = true;
  29522. this.leftColor = BABYLON.Color3.White();
  29523. this.rightColor = BABYLON.Color3.Black();
  29524. this.bias = 0;
  29525. this.power = 1;
  29526. }
  29527. FresnelParameters.prototype.clone = function () {
  29528. var newFresnelParameters = new FresnelParameters();
  29529. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  29530. return newFresnelParameters;
  29531. };
  29532. FresnelParameters.prototype.serialize = function () {
  29533. var serializationObject = {};
  29534. serializationObject.isEnabled = this.isEnabled;
  29535. serializationObject.leftColor = this.leftColor;
  29536. serializationObject.rightColor = this.rightColor;
  29537. serializationObject.bias = this.bias;
  29538. serializationObject.power = this.power;
  29539. return serializationObject;
  29540. };
  29541. FresnelParameters.Parse = function (parsedFresnelParameters) {
  29542. var fresnelParameters = new FresnelParameters();
  29543. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  29544. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  29545. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  29546. fresnelParameters.bias = parsedFresnelParameters.bias;
  29547. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  29548. return fresnelParameters;
  29549. };
  29550. return FresnelParameters;
  29551. }());
  29552. BABYLON.FresnelParameters = FresnelParameters;
  29553. })(BABYLON || (BABYLON = {}));
  29554. //# sourceMappingURL=babylon.fresnelParameters.js.map
  29555. var BABYLON;
  29556. (function (BABYLON) {
  29557. var MaterialDefines = (function () {
  29558. function MaterialDefines() {
  29559. }
  29560. MaterialDefines.prototype.rebuild = function () {
  29561. if (this._keys) {
  29562. delete this._keys;
  29563. }
  29564. this._keys = Object.keys(this);
  29565. };
  29566. MaterialDefines.prototype.isEqual = function (other) {
  29567. if (this._keys.length !== other._keys.length) {
  29568. return false;
  29569. }
  29570. for (var index = 0; index < this._keys.length; index++) {
  29571. var prop = this._keys[index];
  29572. if (this[prop] !== other[prop]) {
  29573. return false;
  29574. }
  29575. }
  29576. return true;
  29577. };
  29578. MaterialDefines.prototype.cloneTo = function (other) {
  29579. if (this._keys.length !== other._keys.length) {
  29580. other._keys = this._keys.slice(0);
  29581. }
  29582. for (var index = 0; index < this._keys.length; index++) {
  29583. var prop = this._keys[index];
  29584. other[prop] = this[prop];
  29585. }
  29586. };
  29587. MaterialDefines.prototype.reset = function () {
  29588. for (var index = 0; index < this._keys.length; index++) {
  29589. var prop = this._keys[index];
  29590. if (typeof (this[prop]) === "number") {
  29591. this[prop] = 0;
  29592. }
  29593. else {
  29594. this[prop] = false;
  29595. }
  29596. }
  29597. };
  29598. MaterialDefines.prototype.toString = function () {
  29599. var result = "";
  29600. for (var index = 0; index < this._keys.length; index++) {
  29601. var prop = this._keys[index];
  29602. if (typeof (this[prop]) === "number") {
  29603. result += "#define " + prop + " " + this[prop] + "\n";
  29604. }
  29605. else if (this[prop]) {
  29606. result += "#define " + prop + "\n";
  29607. }
  29608. }
  29609. return result;
  29610. };
  29611. return MaterialDefines;
  29612. }());
  29613. BABYLON.MaterialDefines = MaterialDefines;
  29614. var Material = (function () {
  29615. function Material(name, scene, doNotAdd) {
  29616. this.checkReadyOnEveryCall = false;
  29617. this.checkReadyOnlyOnce = false;
  29618. this.state = "";
  29619. this.alpha = 1.0;
  29620. this.backFaceCulling = true;
  29621. this.doNotSerialize = false;
  29622. /**
  29623. * An event triggered when the material is disposed.
  29624. * @type {BABYLON.Observable}
  29625. */
  29626. this.onDisposeObservable = new BABYLON.Observable();
  29627. /**
  29628. * An event triggered when the material is bound.
  29629. * @type {BABYLON.Observable}
  29630. */
  29631. this.onBindObservable = new BABYLON.Observable();
  29632. /**
  29633. * An event triggered when the material is unbound.
  29634. * @type {BABYLON.Observable}
  29635. */
  29636. this.onUnBindObservable = new BABYLON.Observable();
  29637. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29638. this.disableDepthWrite = false;
  29639. this.fogEnabled = true;
  29640. this.pointSize = 1.0;
  29641. this.zOffset = 0;
  29642. this._wasPreviouslyReady = false;
  29643. this._fillMode = Material.TriangleFillMode;
  29644. this.name = name;
  29645. this.id = name;
  29646. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29647. if (this._scene.useRightHandedSystem) {
  29648. this.sideOrientation = Material.ClockWiseSideOrientation;
  29649. }
  29650. else {
  29651. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29652. }
  29653. if (!doNotAdd) {
  29654. this._scene.materials.push(this);
  29655. }
  29656. }
  29657. Object.defineProperty(Material, "TriangleFillMode", {
  29658. get: function () {
  29659. return Material._TriangleFillMode;
  29660. },
  29661. enumerable: true,
  29662. configurable: true
  29663. });
  29664. Object.defineProperty(Material, "WireFrameFillMode", {
  29665. get: function () {
  29666. return Material._WireFrameFillMode;
  29667. },
  29668. enumerable: true,
  29669. configurable: true
  29670. });
  29671. Object.defineProperty(Material, "PointFillMode", {
  29672. get: function () {
  29673. return Material._PointFillMode;
  29674. },
  29675. enumerable: true,
  29676. configurable: true
  29677. });
  29678. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29679. get: function () {
  29680. return Material._ClockWiseSideOrientation;
  29681. },
  29682. enumerable: true,
  29683. configurable: true
  29684. });
  29685. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29686. get: function () {
  29687. return Material._CounterClockWiseSideOrientation;
  29688. },
  29689. enumerable: true,
  29690. configurable: true
  29691. });
  29692. Object.defineProperty(Material.prototype, "onDispose", {
  29693. set: function (callback) {
  29694. if (this._onDisposeObserver) {
  29695. this.onDisposeObservable.remove(this._onDisposeObserver);
  29696. }
  29697. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29698. },
  29699. enumerable: true,
  29700. configurable: true
  29701. });
  29702. Object.defineProperty(Material.prototype, "onBind", {
  29703. set: function (callback) {
  29704. if (this._onBindObserver) {
  29705. this.onBindObservable.remove(this._onBindObserver);
  29706. }
  29707. this._onBindObserver = this.onBindObservable.add(callback);
  29708. },
  29709. enumerable: true,
  29710. configurable: true
  29711. });
  29712. Object.defineProperty(Material.prototype, "wireframe", {
  29713. get: function () {
  29714. return this._fillMode === Material.WireFrameFillMode;
  29715. },
  29716. set: function (value) {
  29717. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29718. },
  29719. enumerable: true,
  29720. configurable: true
  29721. });
  29722. Object.defineProperty(Material.prototype, "pointsCloud", {
  29723. get: function () {
  29724. return this._fillMode === Material.PointFillMode;
  29725. },
  29726. set: function (value) {
  29727. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29728. },
  29729. enumerable: true,
  29730. configurable: true
  29731. });
  29732. Object.defineProperty(Material.prototype, "fillMode", {
  29733. get: function () {
  29734. return this._fillMode;
  29735. },
  29736. set: function (value) {
  29737. this._fillMode = value;
  29738. },
  29739. enumerable: true,
  29740. configurable: true
  29741. });
  29742. /**
  29743. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29744. * subclasses should override adding information pertainent to themselves
  29745. */
  29746. Material.prototype.toString = function (fullDetails) {
  29747. var ret = "Name: " + this.name;
  29748. if (fullDetails) {
  29749. }
  29750. return ret;
  29751. };
  29752. Material.prototype.getClassName = function () {
  29753. return "Material";
  29754. };
  29755. Object.defineProperty(Material.prototype, "isFrozen", {
  29756. get: function () {
  29757. return this.checkReadyOnlyOnce;
  29758. },
  29759. enumerable: true,
  29760. configurable: true
  29761. });
  29762. Material.prototype.freeze = function () {
  29763. this.checkReadyOnlyOnce = true;
  29764. };
  29765. Material.prototype.unfreeze = function () {
  29766. this.checkReadyOnlyOnce = false;
  29767. };
  29768. Material.prototype.isReady = function (mesh, useInstances) {
  29769. return true;
  29770. };
  29771. Material.prototype.getEffect = function () {
  29772. return this._effect;
  29773. };
  29774. Material.prototype.getScene = function () {
  29775. return this._scene;
  29776. };
  29777. Material.prototype.needAlphaBlending = function () {
  29778. return (this.alpha < 1.0);
  29779. };
  29780. Material.prototype.needAlphaTesting = function () {
  29781. return false;
  29782. };
  29783. Material.prototype.getAlphaTestTexture = function () {
  29784. return null;
  29785. };
  29786. Material.prototype.markDirty = function () {
  29787. this._wasPreviouslyReady = false;
  29788. };
  29789. Material.prototype._preBind = function () {
  29790. var engine = this._scene.getEngine();
  29791. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29792. engine.enableEffect(this._effect);
  29793. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29794. };
  29795. Material.prototype.bind = function (world, mesh) {
  29796. this._scene._cachedMaterial = this;
  29797. this.onBindObservable.notifyObservers(mesh);
  29798. if (this.disableDepthWrite) {
  29799. var engine = this._scene.getEngine();
  29800. this._cachedDepthWriteState = engine.getDepthWrite();
  29801. engine.setDepthWrite(false);
  29802. }
  29803. };
  29804. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29805. };
  29806. Material.prototype.unbind = function () {
  29807. this.onUnBindObservable.notifyObservers(this);
  29808. if (this.disableDepthWrite) {
  29809. var engine = this._scene.getEngine();
  29810. engine.setDepthWrite(this._cachedDepthWriteState);
  29811. }
  29812. };
  29813. Material.prototype.clone = function (name) {
  29814. return null;
  29815. };
  29816. Material.prototype.getBindedMeshes = function () {
  29817. var result = new Array();
  29818. for (var index = 0; index < this._scene.meshes.length; index++) {
  29819. var mesh = this._scene.meshes[index];
  29820. if (mesh.material === this) {
  29821. result.push(mesh);
  29822. }
  29823. }
  29824. return result;
  29825. };
  29826. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29827. // Animations
  29828. this.getScene().stopAnimation(this);
  29829. // Remove from scene
  29830. var index = this._scene.materials.indexOf(this);
  29831. if (index >= 0) {
  29832. this._scene.materials.splice(index, 1);
  29833. }
  29834. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29835. if (forceDisposeEffect && this._effect) {
  29836. this._scene.getEngine()._releaseEffect(this._effect);
  29837. this._effect = null;
  29838. }
  29839. // Remove from meshes
  29840. for (index = 0; index < this._scene.meshes.length; index++) {
  29841. var mesh = this._scene.meshes[index];
  29842. if (mesh.material === this) {
  29843. mesh.material = null;
  29844. }
  29845. }
  29846. // Callback
  29847. this.onDisposeObservable.notifyObservers(this);
  29848. this.onDisposeObservable.clear();
  29849. this.onBindObservable.clear();
  29850. this.onUnBindObservable.clear();
  29851. };
  29852. Material.prototype.serialize = function () {
  29853. return BABYLON.SerializationHelper.Serialize(this);
  29854. };
  29855. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29856. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29857. multiMaterial.id = parsedMultiMaterial.id;
  29858. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29859. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29860. var subMatId = parsedMultiMaterial.materials[matIndex];
  29861. if (subMatId) {
  29862. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29863. }
  29864. else {
  29865. multiMaterial.subMaterials.push(null);
  29866. }
  29867. }
  29868. return multiMaterial;
  29869. };
  29870. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29871. if (!parsedMaterial.customType) {
  29872. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29873. }
  29874. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29875. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29876. ;
  29877. };
  29878. return Material;
  29879. }());
  29880. Material._TriangleFillMode = 0;
  29881. Material._WireFrameFillMode = 1;
  29882. Material._PointFillMode = 2;
  29883. Material._ClockWiseSideOrientation = 0;
  29884. Material._CounterClockWiseSideOrientation = 1;
  29885. __decorate([
  29886. BABYLON.serialize()
  29887. ], Material.prototype, "id", void 0);
  29888. __decorate([
  29889. BABYLON.serialize()
  29890. ], Material.prototype, "name", void 0);
  29891. __decorate([
  29892. BABYLON.serialize()
  29893. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29894. __decorate([
  29895. BABYLON.serialize()
  29896. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29897. __decorate([
  29898. BABYLON.serialize()
  29899. ], Material.prototype, "state", void 0);
  29900. __decorate([
  29901. BABYLON.serialize()
  29902. ], Material.prototype, "alpha", void 0);
  29903. __decorate([
  29904. BABYLON.serialize()
  29905. ], Material.prototype, "backFaceCulling", void 0);
  29906. __decorate([
  29907. BABYLON.serialize()
  29908. ], Material.prototype, "sideOrientation", void 0);
  29909. __decorate([
  29910. BABYLON.serialize()
  29911. ], Material.prototype, "alphaMode", void 0);
  29912. __decorate([
  29913. BABYLON.serialize()
  29914. ], Material.prototype, "disableDepthWrite", void 0);
  29915. __decorate([
  29916. BABYLON.serialize()
  29917. ], Material.prototype, "fogEnabled", void 0);
  29918. __decorate([
  29919. BABYLON.serialize()
  29920. ], Material.prototype, "pointSize", void 0);
  29921. __decorate([
  29922. BABYLON.serialize()
  29923. ], Material.prototype, "zOffset", void 0);
  29924. __decorate([
  29925. BABYLON.serialize()
  29926. ], Material.prototype, "wireframe", null);
  29927. __decorate([
  29928. BABYLON.serialize()
  29929. ], Material.prototype, "pointsCloud", null);
  29930. __decorate([
  29931. BABYLON.serialize()
  29932. ], Material.prototype, "fillMode", null);
  29933. BABYLON.Material = Material;
  29934. })(BABYLON || (BABYLON = {}));
  29935. //# sourceMappingURL=babylon.material.js.map
  29936. var BABYLON;
  29937. (function (BABYLON) {
  29938. var StandardMaterialDefines = (function (_super) {
  29939. __extends(StandardMaterialDefines, _super);
  29940. function StandardMaterialDefines() {
  29941. var _this = _super.call(this) || this;
  29942. _this.DIFFUSE = false;
  29943. _this.AMBIENT = false;
  29944. _this.OPACITY = false;
  29945. _this.OPACITYRGB = false;
  29946. _this.REFLECTION = false;
  29947. _this.EMISSIVE = false;
  29948. _this.SPECULAR = false;
  29949. _this.BUMP = false;
  29950. _this.PARALLAX = false;
  29951. _this.PARALLAXOCCLUSION = false;
  29952. _this.SPECULAROVERALPHA = false;
  29953. _this.CLIPPLANE = false;
  29954. _this.ALPHATEST = false;
  29955. _this.ALPHAFROMDIFFUSE = false;
  29956. _this.POINTSIZE = false;
  29957. _this.FOG = false;
  29958. _this.SPECULARTERM = false;
  29959. _this.DIFFUSEFRESNEL = false;
  29960. _this.OPACITYFRESNEL = false;
  29961. _this.REFLECTIONFRESNEL = false;
  29962. _this.REFRACTIONFRESNEL = false;
  29963. _this.EMISSIVEFRESNEL = false;
  29964. _this.FRESNEL = false;
  29965. _this.NORMAL = false;
  29966. _this.UV1 = false;
  29967. _this.UV2 = false;
  29968. _this.VERTEXCOLOR = false;
  29969. _this.VERTEXALPHA = false;
  29970. _this.NUM_BONE_INFLUENCERS = 0;
  29971. _this.BonesPerMesh = 0;
  29972. _this.INSTANCES = false;
  29973. _this.GLOSSINESS = false;
  29974. _this.ROUGHNESS = false;
  29975. _this.EMISSIVEASILLUMINATION = false;
  29976. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29977. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29978. _this.LIGHTMAP = false;
  29979. _this.USELIGHTMAPASSHADOWMAP = false;
  29980. _this.REFLECTIONMAP_3D = false;
  29981. _this.REFLECTIONMAP_SPHERICAL = false;
  29982. _this.REFLECTIONMAP_PLANAR = false;
  29983. _this.REFLECTIONMAP_CUBIC = false;
  29984. _this.REFLECTIONMAP_PROJECTION = false;
  29985. _this.REFLECTIONMAP_SKYBOX = false;
  29986. _this.REFLECTIONMAP_EXPLICIT = false;
  29987. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29988. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29989. _this.INVERTCUBICMAP = false;
  29990. _this.LOGARITHMICDEPTH = false;
  29991. _this.REFRACTION = false;
  29992. _this.REFRACTIONMAP_3D = false;
  29993. _this.REFLECTIONOVERALPHA = false;
  29994. _this.INVERTNORMALMAPX = false;
  29995. _this.INVERTNORMALMAPY = false;
  29996. _this.TWOSIDEDLIGHTING = false;
  29997. _this.SHADOWFULLFLOAT = false;
  29998. _this.CAMERACOLORGRADING = false;
  29999. _this.CAMERACOLORCURVES = false;
  30000. _this.rebuild();
  30001. return _this;
  30002. }
  30003. return StandardMaterialDefines;
  30004. }(BABYLON.MaterialDefines));
  30005. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30006. var StandardMaterial = (function (_super) {
  30007. __extends(StandardMaterial, _super);
  30008. function StandardMaterial(name, scene) {
  30009. var _this = _super.call(this, name, scene) || this;
  30010. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30011. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30012. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30013. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30014. _this.specularPower = 64;
  30015. _this.useAlphaFromDiffuseTexture = false;
  30016. _this.useEmissiveAsIllumination = false;
  30017. _this.linkEmissiveWithDiffuse = false;
  30018. _this.useReflectionFresnelFromSpecular = false;
  30019. _this.useSpecularOverAlpha = false;
  30020. _this.useReflectionOverAlpha = false;
  30021. _this.disableLighting = false;
  30022. _this.useParallax = false;
  30023. _this.useParallaxOcclusion = false;
  30024. _this.parallaxScaleBias = 0.05;
  30025. _this.roughness = 0;
  30026. _this.indexOfRefraction = 0.98;
  30027. _this.invertRefractionY = true;
  30028. _this.useLightmapAsShadowmap = false;
  30029. _this.useGlossinessFromSpecularMapAlpha = false;
  30030. _this.maxSimultaneousLights = 4;
  30031. /**
  30032. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30033. */
  30034. _this.invertNormalMapX = false;
  30035. /**
  30036. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30037. */
  30038. _this.invertNormalMapY = false;
  30039. /**
  30040. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30041. */
  30042. _this.twoSidedLighting = false;
  30043. /**
  30044. * Color Grading 2D Lookup Texture.
  30045. * This allows special effects like sepia, black and white to sixties rendering style.
  30046. */
  30047. _this.cameraColorGradingTexture = null;
  30048. /**
  30049. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30050. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30051. * 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;
  30052. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30053. */
  30054. _this.cameraColorCurves = null;
  30055. _this._renderTargets = new BABYLON.SmartArray(16);
  30056. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30057. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30058. _this._defines = new StandardMaterialDefines();
  30059. _this._cachedDefines = new StandardMaterialDefines();
  30060. _this._cachedDefines.BonesPerMesh = -1;
  30061. _this.getRenderTargetTextures = function () {
  30062. _this._renderTargets.reset();
  30063. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  30064. _this._renderTargets.push(_this.reflectionTexture);
  30065. }
  30066. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  30067. _this._renderTargets.push(_this.refractionTexture);
  30068. }
  30069. return _this._renderTargets;
  30070. };
  30071. return _this;
  30072. }
  30073. StandardMaterial.prototype.getClassName = function () {
  30074. return "StandardMaterial";
  30075. };
  30076. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30077. get: function () {
  30078. return this._useLogarithmicDepth;
  30079. },
  30080. set: function (value) {
  30081. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30082. },
  30083. enumerable: true,
  30084. configurable: true
  30085. });
  30086. StandardMaterial.prototype.needAlphaBlending = function () {
  30087. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  30088. };
  30089. StandardMaterial.prototype.needAlphaTesting = function () {
  30090. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  30091. };
  30092. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30093. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  30094. };
  30095. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30096. return this.diffuseTexture;
  30097. };
  30098. // Methods
  30099. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  30100. if (!mesh) {
  30101. return true;
  30102. }
  30103. if (this._defines.INSTANCES !== useInstances) {
  30104. return false;
  30105. }
  30106. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  30107. return true;
  30108. }
  30109. return false;
  30110. };
  30111. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  30112. if (this.isFrozen) {
  30113. if (this._wasPreviouslyReady) {
  30114. return true;
  30115. }
  30116. }
  30117. var scene = this.getScene();
  30118. var engine = scene.getEngine();
  30119. var needUVs = false;
  30120. var needNormals = false;
  30121. this._defines.reset();
  30122. // Lights
  30123. if (scene.lightsEnabled && !this.disableLighting) {
  30124. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  30125. }
  30126. if (!this.checkReadyOnEveryCall) {
  30127. if (this._renderId === scene.getRenderId()) {
  30128. if (this._checkCache(scene, mesh, useInstances)) {
  30129. return true;
  30130. }
  30131. }
  30132. }
  30133. // Textures
  30134. if (scene.texturesEnabled) {
  30135. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30136. if (!this.diffuseTexture.isReady()) {
  30137. return false;
  30138. }
  30139. else {
  30140. needUVs = true;
  30141. this._defines.DIFFUSE = true;
  30142. }
  30143. }
  30144. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30145. if (!this.ambientTexture.isReady()) {
  30146. return false;
  30147. }
  30148. else {
  30149. needUVs = true;
  30150. this._defines.AMBIENT = true;
  30151. }
  30152. }
  30153. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30154. if (!this.opacityTexture.isReady()) {
  30155. return false;
  30156. }
  30157. else {
  30158. needUVs = true;
  30159. this._defines.OPACITY = true;
  30160. if (this.opacityTexture.getAlphaFromRGB) {
  30161. this._defines.OPACITYRGB = true;
  30162. }
  30163. }
  30164. }
  30165. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30166. if (!this.reflectionTexture.isReady()) {
  30167. return false;
  30168. }
  30169. else {
  30170. needNormals = true;
  30171. this._defines.REFLECTION = true;
  30172. if (this.roughness > 0) {
  30173. this._defines.ROUGHNESS = true;
  30174. }
  30175. if (this.useReflectionOverAlpha) {
  30176. this._defines.REFLECTIONOVERALPHA = true;
  30177. }
  30178. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30179. this._defines.INVERTCUBICMAP = true;
  30180. }
  30181. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  30182. switch (this.reflectionTexture.coordinatesMode) {
  30183. case BABYLON.Texture.CUBIC_MODE:
  30184. case BABYLON.Texture.INVCUBIC_MODE:
  30185. this._defines.REFLECTIONMAP_CUBIC = true;
  30186. break;
  30187. case BABYLON.Texture.EXPLICIT_MODE:
  30188. this._defines.REFLECTIONMAP_EXPLICIT = true;
  30189. break;
  30190. case BABYLON.Texture.PLANAR_MODE:
  30191. this._defines.REFLECTIONMAP_PLANAR = true;
  30192. break;
  30193. case BABYLON.Texture.PROJECTION_MODE:
  30194. this._defines.REFLECTIONMAP_PROJECTION = true;
  30195. break;
  30196. case BABYLON.Texture.SKYBOX_MODE:
  30197. this._defines.REFLECTIONMAP_SKYBOX = true;
  30198. break;
  30199. case BABYLON.Texture.SPHERICAL_MODE:
  30200. this._defines.REFLECTIONMAP_SPHERICAL = true;
  30201. break;
  30202. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30203. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30204. break;
  30205. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30206. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30207. break;
  30208. }
  30209. }
  30210. }
  30211. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30212. if (!this.emissiveTexture.isReady()) {
  30213. return false;
  30214. }
  30215. else {
  30216. needUVs = true;
  30217. this._defines.EMISSIVE = true;
  30218. }
  30219. }
  30220. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30221. if (!this.lightmapTexture.isReady()) {
  30222. return false;
  30223. }
  30224. else {
  30225. needUVs = true;
  30226. this._defines.LIGHTMAP = true;
  30227. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  30228. }
  30229. }
  30230. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30231. if (!this.specularTexture.isReady()) {
  30232. return false;
  30233. }
  30234. else {
  30235. needUVs = true;
  30236. this._defines.SPECULAR = true;
  30237. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  30238. }
  30239. }
  30240. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30241. if (!this.bumpTexture.isReady()) {
  30242. return false;
  30243. }
  30244. else {
  30245. needUVs = true;
  30246. this._defines.BUMP = true;
  30247. if (this.useParallax) {
  30248. this._defines.PARALLAX = true;
  30249. if (this.useParallaxOcclusion) {
  30250. this._defines.PARALLAXOCCLUSION = true;
  30251. }
  30252. }
  30253. if (this.invertNormalMapX) {
  30254. this._defines.INVERTNORMALMAPX = true;
  30255. }
  30256. if (this.invertNormalMapY) {
  30257. this._defines.INVERTNORMALMAPY = true;
  30258. }
  30259. if (scene._mirroredCameraPosition) {
  30260. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  30261. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  30262. }
  30263. }
  30264. }
  30265. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30266. if (!this.refractionTexture.isReady()) {
  30267. return false;
  30268. }
  30269. else {
  30270. needUVs = true;
  30271. this._defines.REFRACTION = true;
  30272. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  30273. }
  30274. }
  30275. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30276. if (!this.cameraColorGradingTexture.isReady()) {
  30277. return false;
  30278. }
  30279. else {
  30280. this._defines.CAMERACOLORGRADING = true;
  30281. }
  30282. }
  30283. if (!this.backFaceCulling && this.twoSidedLighting) {
  30284. this._defines.TWOSIDEDLIGHTING = true;
  30285. }
  30286. }
  30287. // Effect
  30288. if (scene.clipPlane) {
  30289. this._defines.CLIPPLANE = true;
  30290. }
  30291. if (engine.getAlphaTesting()) {
  30292. this._defines.ALPHATEST = true;
  30293. }
  30294. if (this._shouldUseAlphaFromDiffuseTexture()) {
  30295. this._defines.ALPHAFROMDIFFUSE = true;
  30296. }
  30297. if (this.useEmissiveAsIllumination) {
  30298. this._defines.EMISSIVEASILLUMINATION = true;
  30299. }
  30300. if (this.linkEmissiveWithDiffuse) {
  30301. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  30302. }
  30303. if (this.useLogarithmicDepth) {
  30304. this._defines.LOGARITHMICDEPTH = true;
  30305. }
  30306. if (this.cameraColorCurves) {
  30307. this._defines.CAMERACOLORCURVES = true;
  30308. }
  30309. // Point size
  30310. if (this.pointsCloud || scene.forcePointsCloud) {
  30311. this._defines.POINTSIZE = true;
  30312. }
  30313. // Fog
  30314. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30315. this._defines.FOG = true;
  30316. }
  30317. if (StandardMaterial.FresnelEnabled) {
  30318. // Fresnel
  30319. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  30320. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  30321. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  30322. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  30323. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30324. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30325. this._defines.DIFFUSEFRESNEL = true;
  30326. }
  30327. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30328. this._defines.OPACITYFRESNEL = true;
  30329. }
  30330. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30331. this._defines.REFLECTIONFRESNEL = true;
  30332. if (this.useReflectionFresnelFromSpecular) {
  30333. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  30334. }
  30335. }
  30336. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30337. this._defines.REFRACTIONFRESNEL = true;
  30338. }
  30339. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30340. this._defines.EMISSIVEFRESNEL = true;
  30341. }
  30342. needNormals = true;
  30343. this._defines.FRESNEL = true;
  30344. }
  30345. }
  30346. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  30347. this._defines.SPECULAROVERALPHA = true;
  30348. }
  30349. // Attribs
  30350. if (mesh) {
  30351. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30352. this._defines.NORMAL = true;
  30353. }
  30354. if (needUVs) {
  30355. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30356. this._defines.UV1 = true;
  30357. }
  30358. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30359. this._defines.UV2 = true;
  30360. }
  30361. }
  30362. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30363. this._defines.VERTEXCOLOR = true;
  30364. if (mesh.hasVertexAlpha) {
  30365. this._defines.VERTEXALPHA = true;
  30366. }
  30367. }
  30368. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30369. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30370. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30371. }
  30372. // Instances
  30373. if (useInstances) {
  30374. this._defines.INSTANCES = true;
  30375. }
  30376. }
  30377. // Get correct effect
  30378. if (!this._defines.isEqual(this._cachedDefines)) {
  30379. this._defines.cloneTo(this._cachedDefines);
  30380. scene.resetCachedMaterial();
  30381. // Fallbacks
  30382. var fallbacks = new BABYLON.EffectFallbacks();
  30383. if (this._defines.REFLECTION) {
  30384. fallbacks.addFallback(0, "REFLECTION");
  30385. }
  30386. if (this._defines.SPECULAR) {
  30387. fallbacks.addFallback(0, "SPECULAR");
  30388. }
  30389. if (this._defines.BUMP) {
  30390. fallbacks.addFallback(0, "BUMP");
  30391. }
  30392. if (this._defines.PARALLAX) {
  30393. fallbacks.addFallback(1, "PARALLAX");
  30394. }
  30395. if (this._defines.PARALLAXOCCLUSION) {
  30396. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30397. }
  30398. if (this._defines.SPECULAROVERALPHA) {
  30399. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30400. }
  30401. if (this._defines.FOG) {
  30402. fallbacks.addFallback(1, "FOG");
  30403. }
  30404. if (this._defines.POINTSIZE) {
  30405. fallbacks.addFallback(0, "POINTSIZE");
  30406. }
  30407. if (this._defines.LOGARITHMICDEPTH) {
  30408. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30409. }
  30410. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  30411. if (this._defines.SPECULARTERM) {
  30412. fallbacks.addFallback(0, "SPECULARTERM");
  30413. }
  30414. if (this._defines.DIFFUSEFRESNEL) {
  30415. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30416. }
  30417. if (this._defines.OPACITYFRESNEL) {
  30418. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30419. }
  30420. if (this._defines.REFLECTIONFRESNEL) {
  30421. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30422. }
  30423. if (this._defines.EMISSIVEFRESNEL) {
  30424. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30425. }
  30426. if (this._defines.FRESNEL) {
  30427. fallbacks.addFallback(4, "FRESNEL");
  30428. }
  30429. //Attributes
  30430. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30431. if (this._defines.NORMAL) {
  30432. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30433. }
  30434. if (this._defines.UV1) {
  30435. attribs.push(BABYLON.VertexBuffer.UVKind);
  30436. }
  30437. if (this._defines.UV2) {
  30438. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30439. }
  30440. if (this._defines.VERTEXCOLOR) {
  30441. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30442. }
  30443. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30444. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30445. var shaderName = "default";
  30446. var join = this._defines.toString();
  30447. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30448. "vFogInfos", "vFogColor", "pointSize",
  30449. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30450. "mBones",
  30451. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30452. "depthValues",
  30453. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30454. "logarithmicDepthConstant"
  30455. ];
  30456. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30457. if (this._defines.CAMERACOLORCURVES) {
  30458. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30459. }
  30460. if (this._defines.CAMERACOLORGRADING) {
  30461. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30462. }
  30463. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  30464. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  30465. }
  30466. if (!this._effect.isReady()) {
  30467. return false;
  30468. }
  30469. this._renderId = scene.getRenderId();
  30470. this._wasPreviouslyReady = true;
  30471. if (mesh) {
  30472. if (!mesh._materialDefines) {
  30473. mesh._materialDefines = new StandardMaterialDefines();
  30474. }
  30475. this._defines.cloneTo(mesh._materialDefines);
  30476. }
  30477. return true;
  30478. };
  30479. StandardMaterial.prototype.unbind = function () {
  30480. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  30481. this._effect.setTexture("reflection2DSampler", null);
  30482. }
  30483. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  30484. this._effect.setTexture("refraction2DSampler", null);
  30485. }
  30486. _super.prototype.unbind.call(this);
  30487. };
  30488. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30489. this._effect.setMatrix("world", world);
  30490. };
  30491. StandardMaterial.prototype.bind = function (world, mesh) {
  30492. var scene = this.getScene();
  30493. // Matrices
  30494. this.bindOnlyWorldMatrix(world);
  30495. // Bones
  30496. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30497. if (scene.getCachedMaterial() !== this) {
  30498. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30499. if (StandardMaterial.FresnelEnabled) {
  30500. // Fresnel
  30501. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30502. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30503. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30504. }
  30505. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30506. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30507. }
  30508. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30509. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30510. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30511. }
  30512. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30513. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30514. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30515. }
  30516. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30517. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30518. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30519. }
  30520. }
  30521. // Textures
  30522. if (scene.texturesEnabled) {
  30523. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30524. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  30525. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  30526. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  30527. }
  30528. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30529. this._effect.setTexture("ambientSampler", this.ambientTexture);
  30530. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  30531. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  30532. }
  30533. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30534. this._effect.setTexture("opacitySampler", this.opacityTexture);
  30535. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  30536. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  30537. }
  30538. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30539. if (this.reflectionTexture.isCube) {
  30540. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  30541. }
  30542. else {
  30543. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  30544. }
  30545. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  30546. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  30547. }
  30548. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30549. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  30550. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  30551. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  30552. }
  30553. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30554. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  30555. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  30556. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  30557. }
  30558. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30559. this._effect.setTexture("specularSampler", this.specularTexture);
  30560. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  30561. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  30562. }
  30563. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30564. this._effect.setTexture("bumpSampler", this.bumpTexture);
  30565. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  30566. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  30567. }
  30568. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30569. var depth = 1.0;
  30570. if (this.refractionTexture.isCube) {
  30571. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  30572. }
  30573. else {
  30574. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  30575. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  30576. if (this.refractionTexture.depth) {
  30577. depth = this.refractionTexture.depth;
  30578. }
  30579. }
  30580. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30581. }
  30582. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30583. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  30584. }
  30585. }
  30586. // Clip plane
  30587. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  30588. // Point size
  30589. if (this.pointsCloud) {
  30590. this._effect.setFloat("pointSize", this.pointSize);
  30591. }
  30592. // Colors
  30593. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30594. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30595. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30596. if (this._defines.SPECULARTERM) {
  30597. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  30598. }
  30599. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  30600. }
  30601. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  30602. // Diffuse
  30603. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30604. // Lights
  30605. if (scene.lightsEnabled && !this.disableLighting) {
  30606. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  30607. }
  30608. // View
  30609. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  30610. this._effect.setMatrix("view", scene.getViewMatrix());
  30611. }
  30612. // Fog
  30613. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  30614. // Log. depth
  30615. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  30616. // Color Curves
  30617. if (this.cameraColorCurves) {
  30618. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  30619. }
  30620. }
  30621. _super.prototype.bind.call(this, world, mesh);
  30622. };
  30623. StandardMaterial.prototype.getAnimatables = function () {
  30624. var results = [];
  30625. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  30626. results.push(this.diffuseTexture);
  30627. }
  30628. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  30629. results.push(this.ambientTexture);
  30630. }
  30631. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  30632. results.push(this.opacityTexture);
  30633. }
  30634. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  30635. results.push(this.reflectionTexture);
  30636. }
  30637. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  30638. results.push(this.emissiveTexture);
  30639. }
  30640. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  30641. results.push(this.specularTexture);
  30642. }
  30643. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  30644. results.push(this.bumpTexture);
  30645. }
  30646. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  30647. results.push(this.lightmapTexture);
  30648. }
  30649. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  30650. results.push(this.refractionTexture);
  30651. }
  30652. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  30653. results.push(this.cameraColorGradingTexture);
  30654. }
  30655. return results;
  30656. };
  30657. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30658. if (forceDisposeTextures) {
  30659. if (this.diffuseTexture) {
  30660. this.diffuseTexture.dispose();
  30661. }
  30662. if (this.ambientTexture) {
  30663. this.ambientTexture.dispose();
  30664. }
  30665. if (this.opacityTexture) {
  30666. this.opacityTexture.dispose();
  30667. }
  30668. if (this.reflectionTexture) {
  30669. this.reflectionTexture.dispose();
  30670. }
  30671. if (this.emissiveTexture) {
  30672. this.emissiveTexture.dispose();
  30673. }
  30674. if (this.specularTexture) {
  30675. this.specularTexture.dispose();
  30676. }
  30677. if (this.bumpTexture) {
  30678. this.bumpTexture.dispose();
  30679. }
  30680. if (this.lightmapTexture) {
  30681. this.lightmapTexture.dispose();
  30682. }
  30683. if (this.refractionTexture) {
  30684. this.refractionTexture.dispose();
  30685. }
  30686. if (this.cameraColorGradingTexture) {
  30687. this.cameraColorGradingTexture.dispose();
  30688. }
  30689. }
  30690. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30691. };
  30692. StandardMaterial.prototype.clone = function (name) {
  30693. var _this = this;
  30694. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30695. };
  30696. StandardMaterial.prototype.serialize = function () {
  30697. return BABYLON.SerializationHelper.Serialize(this);
  30698. };
  30699. // Statics
  30700. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30701. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30702. };
  30703. return StandardMaterial;
  30704. }(BABYLON.Material));
  30705. // Flags used to enable or disable a type of texture for all Standard Materials
  30706. StandardMaterial.DiffuseTextureEnabled = true;
  30707. StandardMaterial.AmbientTextureEnabled = true;
  30708. StandardMaterial.OpacityTextureEnabled = true;
  30709. StandardMaterial.ReflectionTextureEnabled = true;
  30710. StandardMaterial.EmissiveTextureEnabled = true;
  30711. StandardMaterial.SpecularTextureEnabled = true;
  30712. StandardMaterial.BumpTextureEnabled = true;
  30713. StandardMaterial.FresnelEnabled = true;
  30714. StandardMaterial.LightmapTextureEnabled = true;
  30715. StandardMaterial.RefractionTextureEnabled = true;
  30716. StandardMaterial.ColorGradingTextureEnabled = true;
  30717. __decorate([
  30718. BABYLON.serializeAsTexture()
  30719. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30720. __decorate([
  30721. BABYLON.serializeAsTexture()
  30722. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30723. __decorate([
  30724. BABYLON.serializeAsTexture()
  30725. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30726. __decorate([
  30727. BABYLON.serializeAsTexture()
  30728. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30729. __decorate([
  30730. BABYLON.serializeAsTexture()
  30731. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30732. __decorate([
  30733. BABYLON.serializeAsTexture()
  30734. ], StandardMaterial.prototype, "specularTexture", void 0);
  30735. __decorate([
  30736. BABYLON.serializeAsTexture()
  30737. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30738. __decorate([
  30739. BABYLON.serializeAsTexture()
  30740. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30741. __decorate([
  30742. BABYLON.serializeAsTexture()
  30743. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30744. __decorate([
  30745. BABYLON.serializeAsColor3("ambient")
  30746. ], StandardMaterial.prototype, "ambientColor", void 0);
  30747. __decorate([
  30748. BABYLON.serializeAsColor3("diffuse")
  30749. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30750. __decorate([
  30751. BABYLON.serializeAsColor3("specular")
  30752. ], StandardMaterial.prototype, "specularColor", void 0);
  30753. __decorate([
  30754. BABYLON.serializeAsColor3("emissive")
  30755. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30756. __decorate([
  30757. BABYLON.serialize()
  30758. ], StandardMaterial.prototype, "specularPower", void 0);
  30759. __decorate([
  30760. BABYLON.serialize()
  30761. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], StandardMaterial.prototype, "disableLighting", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], StandardMaterial.prototype, "useParallax", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], StandardMaterial.prototype, "roughness", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30801. __decorate([
  30802. BABYLON.serializeAsFresnelParameters()
  30803. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30804. __decorate([
  30805. BABYLON.serializeAsFresnelParameters()
  30806. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30807. __decorate([
  30808. BABYLON.serializeAsFresnelParameters()
  30809. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30810. __decorate([
  30811. BABYLON.serializeAsFresnelParameters()
  30812. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30813. __decorate([
  30814. BABYLON.serializeAsFresnelParameters()
  30815. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30816. __decorate([
  30817. BABYLON.serialize()
  30818. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30819. __decorate([
  30820. BABYLON.serialize()
  30821. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30822. __decorate([
  30823. BABYLON.serialize()
  30824. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30825. __decorate([
  30826. BABYLON.serialize()
  30827. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30828. __decorate([
  30829. BABYLON.serialize()
  30830. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  30831. __decorate([
  30832. BABYLON.serializeAsTexture()
  30833. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30834. __decorate([
  30835. BABYLON.serializeAsColorCurves()
  30836. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30837. __decorate([
  30838. BABYLON.serialize()
  30839. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30840. BABYLON.StandardMaterial = StandardMaterial;
  30841. })(BABYLON || (BABYLON = {}));
  30842. //# sourceMappingURL=babylon.standardMaterial.js.map
  30843. var BABYLON;
  30844. (function (BABYLON) {
  30845. var MultiMaterial = (function (_super) {
  30846. __extends(MultiMaterial, _super);
  30847. function MultiMaterial(name, scene) {
  30848. var _this = _super.call(this, name, scene, true) || this;
  30849. _this.subMaterials = new Array();
  30850. scene.multiMaterials.push(_this);
  30851. return _this;
  30852. }
  30853. // Properties
  30854. MultiMaterial.prototype.getSubMaterial = function (index) {
  30855. if (index < 0 || index >= this.subMaterials.length) {
  30856. return this.getScene().defaultMaterial;
  30857. }
  30858. return this.subMaterials[index];
  30859. };
  30860. // Methods
  30861. MultiMaterial.prototype.getClassName = function () {
  30862. return "MultiMaterial";
  30863. };
  30864. MultiMaterial.prototype.isReady = function (mesh) {
  30865. for (var index = 0; index < this.subMaterials.length; index++) {
  30866. var subMaterial = this.subMaterials[index];
  30867. if (subMaterial) {
  30868. if (!this.subMaterials[index].isReady(mesh)) {
  30869. return false;
  30870. }
  30871. }
  30872. }
  30873. return true;
  30874. };
  30875. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30876. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30877. for (var index = 0; index < this.subMaterials.length; index++) {
  30878. var subMaterial = null;
  30879. if (cloneChildren) {
  30880. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30881. }
  30882. else {
  30883. subMaterial = this.subMaterials[index];
  30884. }
  30885. newMultiMaterial.subMaterials.push(subMaterial);
  30886. }
  30887. return newMultiMaterial;
  30888. };
  30889. MultiMaterial.prototype.serialize = function () {
  30890. var serializationObject = {};
  30891. serializationObject.name = this.name;
  30892. serializationObject.id = this.id;
  30893. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30894. serializationObject.materials = [];
  30895. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30896. var subMat = this.subMaterials[matIndex];
  30897. if (subMat) {
  30898. serializationObject.materials.push(subMat.id);
  30899. }
  30900. else {
  30901. serializationObject.materials.push(null);
  30902. }
  30903. }
  30904. return serializationObject;
  30905. };
  30906. return MultiMaterial;
  30907. }(BABYLON.Material));
  30908. BABYLON.MultiMaterial = MultiMaterial;
  30909. })(BABYLON || (BABYLON = {}));
  30910. //# sourceMappingURL=babylon.multiMaterial.js.map
  30911. var BABYLON;
  30912. (function (BABYLON) {
  30913. var SceneLoader = (function () {
  30914. function SceneLoader() {
  30915. }
  30916. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30917. get: function () {
  30918. return 0;
  30919. },
  30920. enumerable: true,
  30921. configurable: true
  30922. });
  30923. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30924. get: function () {
  30925. return 1;
  30926. },
  30927. enumerable: true,
  30928. configurable: true
  30929. });
  30930. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30931. get: function () {
  30932. return 2;
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30938. get: function () {
  30939. return 3;
  30940. },
  30941. enumerable: true,
  30942. configurable: true
  30943. });
  30944. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30945. get: function () {
  30946. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30947. },
  30948. set: function (value) {
  30949. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30950. },
  30951. enumerable: true,
  30952. configurable: true
  30953. });
  30954. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30955. get: function () {
  30956. return SceneLoader._ShowLoadingScreen;
  30957. },
  30958. set: function (value) {
  30959. SceneLoader._ShowLoadingScreen = value;
  30960. },
  30961. enumerable: true,
  30962. configurable: true
  30963. });
  30964. Object.defineProperty(SceneLoader, "loggingLevel", {
  30965. get: function () {
  30966. return SceneLoader._loggingLevel;
  30967. },
  30968. set: function (value) {
  30969. SceneLoader._loggingLevel = value;
  30970. },
  30971. enumerable: true,
  30972. configurable: true
  30973. });
  30974. SceneLoader._getDefaultPlugin = function () {
  30975. return SceneLoader._registeredPlugins[".babylon"];
  30976. };
  30977. SceneLoader._getPluginForExtension = function (extension) {
  30978. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30979. if (registeredPlugin) {
  30980. return registeredPlugin;
  30981. }
  30982. return SceneLoader._getDefaultPlugin();
  30983. };
  30984. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30985. if (sceneFilename.name) {
  30986. sceneFilename = sceneFilename.name;
  30987. }
  30988. var dotPosition = sceneFilename.lastIndexOf(".");
  30989. var queryStringPosition = sceneFilename.indexOf("?");
  30990. if (queryStringPosition === -1) {
  30991. queryStringPosition = sceneFilename.length;
  30992. }
  30993. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30994. return SceneLoader._getPluginForExtension(extension);
  30995. };
  30996. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30997. SceneLoader._getDirectLoad = function (sceneFilename) {
  30998. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30999. return sceneFilename.substr(5);
  31000. }
  31001. return null;
  31002. };
  31003. // Public functions
  31004. SceneLoader.GetPluginForExtension = function (extension) {
  31005. return SceneLoader._getPluginForExtension(extension).plugin;
  31006. };
  31007. SceneLoader.RegisterPlugin = function (plugin) {
  31008. if (typeof plugin.extensions === "string") {
  31009. var extension = plugin.extensions;
  31010. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  31011. plugin: plugin,
  31012. isBinary: false
  31013. };
  31014. }
  31015. else {
  31016. var extensions = plugin.extensions;
  31017. Object.keys(extensions).forEach(function (extension) {
  31018. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  31019. plugin: plugin,
  31020. isBinary: extensions[extension].isBinary
  31021. };
  31022. });
  31023. }
  31024. };
  31025. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31026. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31027. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31028. return;
  31029. }
  31030. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31031. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31032. return;
  31033. }
  31034. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31035. var loadingToken = {};
  31036. scene._addPendingData(loadingToken);
  31037. var manifestChecked = function (success) {
  31038. scene.database = database;
  31039. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31040. var plugin = registeredPlugin.plugin;
  31041. var useArrayBuffer = registeredPlugin.isBinary;
  31042. var importMeshFromData = function (data) {
  31043. var meshes = [];
  31044. var particleSystems = [];
  31045. var skeletons = [];
  31046. if (scene.isDisposed) {
  31047. if (onerror) {
  31048. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  31049. }
  31050. return;
  31051. }
  31052. try {
  31053. if (plugin.importMesh) {
  31054. var syncedPlugin = plugin;
  31055. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  31056. if (onerror) {
  31057. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31058. }
  31059. scene._removePendingData(loadingToken);
  31060. return;
  31061. }
  31062. if (onsuccess) {
  31063. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31064. onsuccess(meshes, particleSystems, skeletons);
  31065. scene._removePendingData(loadingToken);
  31066. }
  31067. }
  31068. else {
  31069. var asyncedPlugin = plugin;
  31070. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  31071. if (onsuccess) {
  31072. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31073. onsuccess(meshes, particleSystems, skeletons);
  31074. scene._removePendingData(loadingToken);
  31075. }
  31076. }, function () {
  31077. if (onerror) {
  31078. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31079. }
  31080. scene._removePendingData(loadingToken);
  31081. });
  31082. }
  31083. }
  31084. catch (e) {
  31085. if (onerror) {
  31086. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  31087. }
  31088. scene._removePendingData(loadingToken);
  31089. }
  31090. };
  31091. if (directLoad) {
  31092. importMeshFromData(directLoad);
  31093. return;
  31094. }
  31095. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  31096. importMeshFromData(data);
  31097. }, progressCallBack, database, useArrayBuffer, function () {
  31098. if (onerror) {
  31099. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  31100. }
  31101. });
  31102. };
  31103. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  31104. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31105. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31106. }
  31107. else {
  31108. // If the scene is a data stream or offline support is not enabled, it's a direct load
  31109. manifestChecked(true);
  31110. }
  31111. };
  31112. /**
  31113. * Load a scene
  31114. * @param rootUrl a string that defines the root url for scene and resources
  31115. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31116. * @param engine is the instance of BABYLON.Engine to use to create the scene
  31117. */
  31118. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  31119. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  31120. };
  31121. /**
  31122. * Append a scene
  31123. * @param rootUrl a string that defines the root url for scene and resources
  31124. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31125. * @param scene is the instance of BABYLON.Scene to append to
  31126. */
  31127. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31128. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31129. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31130. return;
  31131. }
  31132. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31133. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31134. var plugin = registeredPlugin.plugin;
  31135. var useArrayBuffer = registeredPlugin.isBinary;
  31136. var database;
  31137. var loadingToken = {};
  31138. scene._addPendingData(loadingToken);
  31139. if (SceneLoader.ShowLoadingScreen) {
  31140. scene.getEngine().displayLoadingUI();
  31141. }
  31142. var loadSceneFromData = function (data) {
  31143. scene.database = database;
  31144. if (plugin.load) {
  31145. var syncedPlugin = plugin;
  31146. if (!syncedPlugin.load(scene, data, rootUrl)) {
  31147. if (onerror) {
  31148. onerror(scene);
  31149. }
  31150. scene._removePendingData(loadingToken);
  31151. scene.getEngine().hideLoadingUI();
  31152. return;
  31153. }
  31154. if (onsuccess) {
  31155. onsuccess(scene);
  31156. }
  31157. scene._removePendingData(loadingToken);
  31158. }
  31159. else {
  31160. var asyncedPlugin = plugin;
  31161. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  31162. if (onsuccess) {
  31163. onsuccess(scene);
  31164. }
  31165. scene._removePendingData(loadingToken);
  31166. }, function () {
  31167. if (onerror) {
  31168. onerror(scene);
  31169. }
  31170. scene._removePendingData(loadingToken);
  31171. scene.getEngine().hideLoadingUI();
  31172. });
  31173. }
  31174. if (SceneLoader.ShowLoadingScreen) {
  31175. scene.executeWhenReady(function () {
  31176. scene.getEngine().hideLoadingUI();
  31177. });
  31178. }
  31179. };
  31180. var manifestChecked = function (success) {
  31181. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  31182. };
  31183. if (directLoad) {
  31184. loadSceneFromData(directLoad);
  31185. return;
  31186. }
  31187. if (rootUrl.indexOf("file:") === -1) {
  31188. if (scene.getEngine().enableOfflineSupport) {
  31189. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31190. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31191. }
  31192. else {
  31193. manifestChecked(true);
  31194. }
  31195. }
  31196. else {
  31197. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  31198. }
  31199. };
  31200. return SceneLoader;
  31201. }());
  31202. // Flags
  31203. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  31204. SceneLoader._ShowLoadingScreen = true;
  31205. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  31206. // Members
  31207. SceneLoader._registeredPlugins = {};
  31208. BABYLON.SceneLoader = SceneLoader;
  31209. ;
  31210. })(BABYLON || (BABYLON = {}));
  31211. //# sourceMappingURL=babylon.sceneLoader.js.map
  31212. var BABYLON;
  31213. (function (BABYLON) {
  31214. var Internals;
  31215. (function (Internals) {
  31216. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  31217. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31218. var parsedMaterial = parsedData.materials[index];
  31219. if (parsedMaterial.id === id) {
  31220. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31221. }
  31222. }
  31223. return null;
  31224. };
  31225. var isDescendantOf = function (mesh, names, hierarchyIds) {
  31226. names = (names instanceof Array) ? names : [names];
  31227. for (var i in names) {
  31228. if (mesh.name === names[i]) {
  31229. hierarchyIds.push(mesh.id);
  31230. return true;
  31231. }
  31232. }
  31233. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  31234. hierarchyIds.push(mesh.id);
  31235. return true;
  31236. }
  31237. return false;
  31238. };
  31239. var logOperation = function (operation, producer) {
  31240. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  31241. };
  31242. BABYLON.SceneLoader.RegisterPlugin({
  31243. extensions: ".babylon",
  31244. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  31245. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31246. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31247. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31248. // and avoid problems with multiple concurrent .babylon loads.
  31249. var log = "importMesh has failed JSON parse";
  31250. try {
  31251. var parsedData = JSON.parse(data);
  31252. log = "";
  31253. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31254. var loadedSkeletonsIds = [];
  31255. var loadedMaterialsIds = [];
  31256. var hierarchyIds = [];
  31257. var index;
  31258. var cache;
  31259. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31260. var parsedMesh = parsedData.meshes[index];
  31261. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  31262. if (meshesNames instanceof Array) {
  31263. // Remove found mesh name from list.
  31264. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  31265. }
  31266. //Geometry?
  31267. if (parsedMesh.geometryId) {
  31268. //does the file contain geometries?
  31269. if (parsedData.geometries) {
  31270. //find the correct geometry and add it to the scene
  31271. var found = false;
  31272. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  31273. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  31274. return;
  31275. }
  31276. else {
  31277. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  31278. if (parsedGeometryData.id === parsedMesh.geometryId) {
  31279. switch (geometryType) {
  31280. case "boxes":
  31281. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  31282. break;
  31283. case "spheres":
  31284. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  31285. break;
  31286. case "cylinders":
  31287. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  31288. break;
  31289. case "toruses":
  31290. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  31291. break;
  31292. case "grounds":
  31293. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  31294. break;
  31295. case "planes":
  31296. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  31297. break;
  31298. case "torusKnots":
  31299. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  31300. break;
  31301. case "vertexData":
  31302. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  31303. break;
  31304. }
  31305. found = true;
  31306. }
  31307. });
  31308. }
  31309. });
  31310. if (!found) {
  31311. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  31312. }
  31313. }
  31314. }
  31315. // Material ?
  31316. if (parsedMesh.materialId) {
  31317. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  31318. if (!materialFound && parsedData.multiMaterials) {
  31319. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  31320. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  31321. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  31322. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  31323. var subMatId = parsedMultiMaterial.materials[matIndex];
  31324. loadedMaterialsIds.push(subMatId);
  31325. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  31326. log += "\n\tMaterial " + mat.toString(fullDetails);
  31327. }
  31328. loadedMaterialsIds.push(parsedMultiMaterial.id);
  31329. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31330. materialFound = true;
  31331. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  31332. break;
  31333. }
  31334. }
  31335. }
  31336. if (!materialFound) {
  31337. loadedMaterialsIds.push(parsedMesh.materialId);
  31338. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  31339. if (!mat) {
  31340. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  31341. }
  31342. else {
  31343. log += "\n\tMaterial " + mat.toString(fullDetails);
  31344. }
  31345. }
  31346. }
  31347. // Skeleton ?
  31348. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  31349. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  31350. if (!skeletonAlreadyLoaded) {
  31351. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  31352. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  31353. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  31354. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31355. skeletons.push(skeleton);
  31356. loadedSkeletonsIds.push(parsedSkeleton.id);
  31357. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  31358. }
  31359. }
  31360. }
  31361. }
  31362. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31363. meshes.push(mesh);
  31364. log += "\n\tMesh " + mesh.toString(fullDetails);
  31365. }
  31366. }
  31367. // Connecting parents
  31368. var currentMesh;
  31369. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31370. currentMesh = scene.meshes[index];
  31371. if (currentMesh._waitingParentId) {
  31372. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  31373. currentMesh._waitingParentId = undefined;
  31374. }
  31375. }
  31376. // freeze and compute world matrix application
  31377. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31378. currentMesh = scene.meshes[index];
  31379. if (currentMesh._waitingFreezeWorldMatrix) {
  31380. currentMesh.freezeWorldMatrix();
  31381. currentMesh._waitingFreezeWorldMatrix = undefined;
  31382. }
  31383. else {
  31384. currentMesh.computeWorldMatrix(true);
  31385. }
  31386. }
  31387. // Particles
  31388. if (parsedData.particleSystems) {
  31389. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31390. var parsedParticleSystem = parsedData.particleSystems[index];
  31391. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  31392. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  31393. }
  31394. }
  31395. }
  31396. return true;
  31397. }
  31398. catch (err) {
  31399. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  31400. log = null;
  31401. throw err;
  31402. }
  31403. finally {
  31404. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31405. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31406. }
  31407. }
  31408. },
  31409. load: function (scene, data, rootUrl) {
  31410. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31411. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31412. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31413. // and avoid problems with multiple concurrent .babylon loads.
  31414. var log = "importScene has failed JSON parse";
  31415. try {
  31416. var parsedData = JSON.parse(data);
  31417. log = "";
  31418. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31419. // Scene
  31420. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  31421. scene.autoClear = parsedData.autoClear;
  31422. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  31423. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  31424. if (parsedData.gravity) {
  31425. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  31426. }
  31427. // Fog
  31428. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  31429. scene.fogMode = parsedData.fogMode;
  31430. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  31431. scene.fogStart = parsedData.fogStart;
  31432. scene.fogEnd = parsedData.fogEnd;
  31433. scene.fogDensity = parsedData.fogDensity;
  31434. log += "\tFog mode for scene: ";
  31435. switch (scene.fogMode) {
  31436. // getters not compiling, so using hardcoded
  31437. case 1:
  31438. log += "exp\n";
  31439. break;
  31440. case 2:
  31441. log += "exp2\n";
  31442. break;
  31443. case 3:
  31444. log += "linear\n";
  31445. break;
  31446. }
  31447. }
  31448. //Physics
  31449. if (parsedData.physicsEnabled) {
  31450. var physicsPlugin;
  31451. if (parsedData.physicsEngine === "cannon") {
  31452. physicsPlugin = new BABYLON.CannonJSPlugin();
  31453. }
  31454. else if (parsedData.physicsEngine === "oimo") {
  31455. physicsPlugin = new BABYLON.OimoJSPlugin();
  31456. }
  31457. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  31458. //else - default engine, which is currently oimo
  31459. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  31460. scene.enablePhysics(physicsGravity, physicsPlugin);
  31461. }
  31462. // Metadata
  31463. if (parsedData.metadata !== undefined) {
  31464. scene.metadata = parsedData.metadata;
  31465. }
  31466. //collisions, if defined. otherwise, default is true
  31467. if (parsedData.collisionsEnabled != undefined) {
  31468. scene.collisionsEnabled = parsedData.collisionsEnabled;
  31469. }
  31470. scene.workerCollisions = !!parsedData.workerCollisions;
  31471. var index;
  31472. var cache;
  31473. // Lights
  31474. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  31475. var parsedLight = parsedData.lights[index];
  31476. var light = BABYLON.Light.Parse(parsedLight, scene);
  31477. log += (index === 0 ? "\n\tLights:" : "");
  31478. log += "\n\t\t" + light.toString(fullDetails);
  31479. }
  31480. // Animations
  31481. if (parsedData.animations) {
  31482. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  31483. var parsedAnimation = parsedData.animations[index];
  31484. var animation = BABYLON.Animation.Parse(parsedAnimation);
  31485. scene.animations.push(animation);
  31486. log += (index === 0 ? "\n\tAnimations:" : "");
  31487. log += "\n\t\t" + animation.toString(fullDetails);
  31488. }
  31489. }
  31490. if (parsedData.autoAnimate) {
  31491. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  31492. }
  31493. // Materials
  31494. if (parsedData.materials) {
  31495. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31496. var parsedMaterial = parsedData.materials[index];
  31497. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31498. log += (index === 0 ? "\n\tMaterials:" : "");
  31499. log += "\n\t\t" + mat.toString(fullDetails);
  31500. }
  31501. }
  31502. if (parsedData.multiMaterials) {
  31503. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  31504. var parsedMultiMaterial = parsedData.multiMaterials[index];
  31505. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31506. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  31507. log += "\n\t\t" + mmat.toString(fullDetails);
  31508. }
  31509. }
  31510. // Skeletons
  31511. if (parsedData.skeletons) {
  31512. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  31513. var parsedSkeleton = parsedData.skeletons[index];
  31514. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31515. log += (index === 0 ? "\n\tSkeletons:" : "");
  31516. log += "\n\t\t" + skeleton.toString(fullDetails);
  31517. }
  31518. }
  31519. // Geometries
  31520. var geometries = parsedData.geometries;
  31521. if (geometries) {
  31522. // Boxes
  31523. var boxes = geometries.boxes;
  31524. if (boxes) {
  31525. for (index = 0, cache = boxes.length; index < cache; index++) {
  31526. var parsedBox = boxes[index];
  31527. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  31528. }
  31529. }
  31530. // Spheres
  31531. var spheres = geometries.spheres;
  31532. if (spheres) {
  31533. for (index = 0, cache = spheres.length; index < cache; index++) {
  31534. var parsedSphere = spheres[index];
  31535. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  31536. }
  31537. }
  31538. // Cylinders
  31539. var cylinders = geometries.cylinders;
  31540. if (cylinders) {
  31541. for (index = 0, cache = cylinders.length; index < cache; index++) {
  31542. var parsedCylinder = cylinders[index];
  31543. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  31544. }
  31545. }
  31546. // Toruses
  31547. var toruses = geometries.toruses;
  31548. if (toruses) {
  31549. for (index = 0, cache = toruses.length; index < cache; index++) {
  31550. var parsedTorus = toruses[index];
  31551. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  31552. }
  31553. }
  31554. // Grounds
  31555. var grounds = geometries.grounds;
  31556. if (grounds) {
  31557. for (index = 0, cache = grounds.length; index < cache; index++) {
  31558. var parsedGround = grounds[index];
  31559. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  31560. }
  31561. }
  31562. // Planes
  31563. var planes = geometries.planes;
  31564. if (planes) {
  31565. for (index = 0, cache = planes.length; index < cache; index++) {
  31566. var parsedPlane = planes[index];
  31567. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  31568. }
  31569. }
  31570. // TorusKnots
  31571. var torusKnots = geometries.torusKnots;
  31572. if (torusKnots) {
  31573. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  31574. var parsedTorusKnot = torusKnots[index];
  31575. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  31576. }
  31577. }
  31578. // VertexData
  31579. var vertexData = geometries.vertexData;
  31580. if (vertexData) {
  31581. for (index = 0, cache = vertexData.length; index < cache; index++) {
  31582. var parsedVertexData = vertexData[index];
  31583. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  31584. }
  31585. }
  31586. }
  31587. // Meshes
  31588. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31589. var parsedMesh = parsedData.meshes[index];
  31590. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31591. log += (index === 0 ? "\n\tMeshes:" : "");
  31592. log += "\n\t\t" + mesh.toString(fullDetails);
  31593. }
  31594. // Cameras
  31595. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  31596. var parsedCamera = parsedData.cameras[index];
  31597. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  31598. log += (index === 0 ? "\n\tCameras:" : "");
  31599. log += "\n\t\t" + camera.toString(fullDetails);
  31600. }
  31601. if (parsedData.activeCameraID) {
  31602. scene.setActiveCameraByID(parsedData.activeCameraID);
  31603. }
  31604. // Browsing all the graph to connect the dots
  31605. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  31606. var camera = scene.cameras[index];
  31607. if (camera._waitingParentId) {
  31608. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  31609. camera._waitingParentId = undefined;
  31610. }
  31611. }
  31612. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  31613. var light = scene.lights[index];
  31614. if (light._waitingParentId) {
  31615. light.parent = scene.getLastEntryByID(light._waitingParentId);
  31616. light._waitingParentId = undefined;
  31617. }
  31618. }
  31619. // Sounds
  31620. var loadedSounds = [];
  31621. var loadedSound;
  31622. if (BABYLON.AudioEngine && parsedData.sounds) {
  31623. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  31624. var parsedSound = parsedData.sounds[index];
  31625. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31626. if (!parsedSound.url)
  31627. parsedSound.url = parsedSound.name;
  31628. if (!loadedSounds[parsedSound.url]) {
  31629. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  31630. loadedSounds[parsedSound.url] = loadedSound;
  31631. }
  31632. else {
  31633. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  31634. }
  31635. }
  31636. else {
  31637. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  31638. }
  31639. }
  31640. }
  31641. loadedSounds = [];
  31642. // Connect parents & children and parse actions
  31643. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31644. var mesh = scene.meshes[index];
  31645. if (mesh._waitingParentId) {
  31646. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  31647. mesh._waitingParentId = undefined;
  31648. }
  31649. if (mesh._waitingActions) {
  31650. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  31651. mesh._waitingActions = undefined;
  31652. }
  31653. }
  31654. // freeze world matrix application
  31655. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31656. var currentMesh = scene.meshes[index];
  31657. if (currentMesh._waitingFreezeWorldMatrix) {
  31658. currentMesh.freezeWorldMatrix();
  31659. currentMesh._waitingFreezeWorldMatrix = undefined;
  31660. }
  31661. else {
  31662. currentMesh.computeWorldMatrix(true);
  31663. }
  31664. }
  31665. // Particles Systems
  31666. if (parsedData.particleSystems) {
  31667. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31668. var parsedParticleSystem = parsedData.particleSystems[index];
  31669. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  31670. }
  31671. }
  31672. // Lens flares
  31673. if (parsedData.lensFlareSystems) {
  31674. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  31675. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  31676. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  31677. }
  31678. }
  31679. // Shadows
  31680. if (parsedData.shadowGenerators) {
  31681. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  31682. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  31683. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  31684. }
  31685. }
  31686. // Actions (scene)
  31687. if (parsedData.actions) {
  31688. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  31689. }
  31690. // Finish
  31691. return true;
  31692. }
  31693. catch (err) {
  31694. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  31695. log = null;
  31696. throw err;
  31697. }
  31698. finally {
  31699. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31700. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31701. }
  31702. }
  31703. }
  31704. });
  31705. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31706. })(BABYLON || (BABYLON = {}));
  31707. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  31708. var BABYLON;
  31709. (function (BABYLON) {
  31710. var SpriteManager = (function () {
  31711. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  31712. if (epsilon === void 0) { epsilon = 0.01; }
  31713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31714. this.name = name;
  31715. this.sprites = new Array();
  31716. this.renderingGroupId = 0;
  31717. this.layerMask = 0x0FFFFFFF;
  31718. this.fogEnabled = true;
  31719. this.isPickable = false;
  31720. /**
  31721. * An event triggered when the manager is disposed.
  31722. * @type {BABYLON.Observable}
  31723. */
  31724. this.onDisposeObservable = new BABYLON.Observable();
  31725. this._vertexBuffers = {};
  31726. this._capacity = capacity;
  31727. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  31728. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31729. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31730. if (cellSize.width && cellSize.height) {
  31731. this.cellWidth = cellSize.width;
  31732. this.cellHeight = cellSize.height;
  31733. }
  31734. else if (cellSize !== undefined) {
  31735. this.cellWidth = cellSize;
  31736. this.cellHeight = cellSize;
  31737. }
  31738. else {
  31739. return;
  31740. }
  31741. this._epsilon = epsilon;
  31742. this._scene = scene;
  31743. this._scene.spriteManagers.push(this);
  31744. var indices = [];
  31745. var index = 0;
  31746. for (var count = 0; count < capacity; count++) {
  31747. indices.push(index);
  31748. indices.push(index + 1);
  31749. indices.push(index + 2);
  31750. indices.push(index);
  31751. indices.push(index + 2);
  31752. indices.push(index + 3);
  31753. index += 4;
  31754. }
  31755. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31756. // VBO
  31757. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31758. this._vertexData = new Float32Array(capacity * 16 * 4);
  31759. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31760. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31761. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31762. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31763. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31764. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31765. this._vertexBuffers["options"] = options;
  31766. this._vertexBuffers["cellInfo"] = cellInfo;
  31767. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31768. // Effects
  31769. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31770. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31771. }
  31772. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31773. set: function (callback) {
  31774. if (this._onDisposeObserver) {
  31775. this.onDisposeObservable.remove(this._onDisposeObserver);
  31776. }
  31777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31778. },
  31779. enumerable: true,
  31780. configurable: true
  31781. });
  31782. Object.defineProperty(SpriteManager.prototype, "texture", {
  31783. get: function () {
  31784. return this._spriteTexture;
  31785. },
  31786. set: function (value) {
  31787. this._spriteTexture = value;
  31788. },
  31789. enumerable: true,
  31790. configurable: true
  31791. });
  31792. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31793. var arrayOffset = index * 16;
  31794. if (offsetX === 0)
  31795. offsetX = this._epsilon;
  31796. else if (offsetX === 1)
  31797. offsetX = 1 - this._epsilon;
  31798. if (offsetY === 0)
  31799. offsetY = this._epsilon;
  31800. else if (offsetY === 1)
  31801. offsetY = 1 - this._epsilon;
  31802. this._vertexData[arrayOffset] = sprite.position.x;
  31803. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31804. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31805. this._vertexData[arrayOffset + 3] = sprite.angle;
  31806. this._vertexData[arrayOffset + 4] = sprite.width;
  31807. this._vertexData[arrayOffset + 5] = sprite.height;
  31808. this._vertexData[arrayOffset + 6] = offsetX;
  31809. this._vertexData[arrayOffset + 7] = offsetY;
  31810. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31811. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31812. var offset = (sprite.cellIndex / rowSize) >> 0;
  31813. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31814. this._vertexData[arrayOffset + 11] = offset;
  31815. // Color
  31816. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31817. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31818. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31819. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31820. };
  31821. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31822. var count = Math.min(this._capacity, this.sprites.length);
  31823. var min = BABYLON.Vector3.Zero();
  31824. var max = BABYLON.Vector3.Zero();
  31825. var distance = Number.MAX_VALUE;
  31826. var currentSprite;
  31827. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31828. var cameraView = camera.getViewMatrix();
  31829. for (var index = 0; index < count; index++) {
  31830. var sprite = this.sprites[index];
  31831. if (!sprite) {
  31832. continue;
  31833. }
  31834. if (predicate) {
  31835. if (!predicate(sprite)) {
  31836. continue;
  31837. }
  31838. }
  31839. else if (!sprite.isPickable) {
  31840. continue;
  31841. }
  31842. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31843. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31844. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31845. if (ray.intersectsBoxMinMax(min, max)) {
  31846. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31847. if (distance > currentDistance) {
  31848. distance = currentDistance;
  31849. currentSprite = sprite;
  31850. if (fastCheck) {
  31851. break;
  31852. }
  31853. }
  31854. }
  31855. }
  31856. if (currentSprite) {
  31857. var result = new BABYLON.PickingInfo();
  31858. result.hit = true;
  31859. result.pickedSprite = currentSprite;
  31860. result.distance = distance;
  31861. return result;
  31862. }
  31863. return null;
  31864. };
  31865. SpriteManager.prototype.render = function () {
  31866. // Check
  31867. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31868. return;
  31869. var engine = this._scene.getEngine();
  31870. var baseSize = this._spriteTexture.getBaseSize();
  31871. // Sprites
  31872. var deltaTime = engine.getDeltaTime();
  31873. var max = Math.min(this._capacity, this.sprites.length);
  31874. var rowSize = baseSize.width / this.cellWidth;
  31875. var offset = 0;
  31876. for (var index = 0; index < max; index++) {
  31877. var sprite = this.sprites[index];
  31878. if (!sprite) {
  31879. continue;
  31880. }
  31881. sprite._animate(deltaTime);
  31882. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31883. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31884. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31885. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31886. }
  31887. this._buffer.update(this._vertexData);
  31888. // Render
  31889. var effect = this._effectBase;
  31890. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31891. effect = this._effectFog;
  31892. }
  31893. engine.enableEffect(effect);
  31894. var viewMatrix = this._scene.getViewMatrix();
  31895. effect.setTexture("diffuseSampler", this._spriteTexture);
  31896. effect.setMatrix("view", viewMatrix);
  31897. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31898. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31899. // Fog
  31900. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31901. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31902. effect.setColor3("vFogColor", this._scene.fogColor);
  31903. }
  31904. // VBOs
  31905. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31906. // Draw order
  31907. engine.setDepthFunctionToLessOrEqual();
  31908. effect.setBool("alphaTest", true);
  31909. engine.setColorWrite(false);
  31910. engine.draw(true, 0, max * 6);
  31911. engine.setColorWrite(true);
  31912. effect.setBool("alphaTest", false);
  31913. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31914. engine.draw(true, 0, max * 6);
  31915. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31916. };
  31917. SpriteManager.prototype.dispose = function () {
  31918. if (this._buffer) {
  31919. this._buffer.dispose();
  31920. this._buffer = null;
  31921. }
  31922. if (this._indexBuffer) {
  31923. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31924. this._indexBuffer = null;
  31925. }
  31926. if (this._spriteTexture) {
  31927. this._spriteTexture.dispose();
  31928. this._spriteTexture = null;
  31929. }
  31930. // Remove from scene
  31931. var index = this._scene.spriteManagers.indexOf(this);
  31932. this._scene.spriteManagers.splice(index, 1);
  31933. // Callback
  31934. this.onDisposeObservable.notifyObservers(this);
  31935. this.onDisposeObservable.clear();
  31936. };
  31937. return SpriteManager;
  31938. }());
  31939. BABYLON.SpriteManager = SpriteManager;
  31940. })(BABYLON || (BABYLON = {}));
  31941. //# sourceMappingURL=babylon.spriteManager.js.map
  31942. var BABYLON;
  31943. (function (BABYLON) {
  31944. var Sprite = (function () {
  31945. function Sprite(name, manager) {
  31946. this.name = name;
  31947. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31948. this.width = 1.0;
  31949. this.height = 1.0;
  31950. this.angle = 0;
  31951. this.cellIndex = 0;
  31952. this.invertU = 0;
  31953. this.invertV = 0;
  31954. this.animations = new Array();
  31955. this.isPickable = false;
  31956. this._animationStarted = false;
  31957. this._loopAnimation = false;
  31958. this._fromIndex = 0;
  31959. this._toIndex = 0;
  31960. this._delay = 0;
  31961. this._direction = 1;
  31962. this._frameCount = 0;
  31963. this._time = 0;
  31964. this._manager = manager;
  31965. this._manager.sprites.push(this);
  31966. this.position = BABYLON.Vector3.Zero();
  31967. }
  31968. Object.defineProperty(Sprite.prototype, "size", {
  31969. get: function () {
  31970. return this.width;
  31971. },
  31972. set: function (value) {
  31973. this.width = value;
  31974. this.height = value;
  31975. },
  31976. enumerable: true,
  31977. configurable: true
  31978. });
  31979. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31980. this._fromIndex = from;
  31981. this._toIndex = to;
  31982. this._loopAnimation = loop;
  31983. this._delay = delay;
  31984. this._animationStarted = true;
  31985. this._direction = from < to ? 1 : -1;
  31986. this.cellIndex = from;
  31987. this._time = 0;
  31988. this._onAnimationEnd = onAnimationEnd;
  31989. };
  31990. Sprite.prototype.stopAnimation = function () {
  31991. this._animationStarted = false;
  31992. };
  31993. Sprite.prototype._animate = function (deltaTime) {
  31994. if (!this._animationStarted)
  31995. return;
  31996. this._time += deltaTime;
  31997. if (this._time > this._delay) {
  31998. this._time = this._time % this._delay;
  31999. this.cellIndex += this._direction;
  32000. if (this.cellIndex === this._toIndex) {
  32001. if (this._loopAnimation) {
  32002. this.cellIndex = this._fromIndex;
  32003. }
  32004. else {
  32005. this._animationStarted = false;
  32006. if (this._onAnimationEnd) {
  32007. this._onAnimationEnd();
  32008. }
  32009. if (this.disposeWhenFinishedAnimating) {
  32010. this.dispose();
  32011. }
  32012. }
  32013. }
  32014. }
  32015. };
  32016. Sprite.prototype.dispose = function () {
  32017. for (var i = 0; i < this._manager.sprites.length; i++) {
  32018. if (this._manager.sprites[i] == this) {
  32019. this._manager.sprites.splice(i, 1);
  32020. }
  32021. }
  32022. };
  32023. return Sprite;
  32024. }());
  32025. BABYLON.Sprite = Sprite;
  32026. })(BABYLON || (BABYLON = {}));
  32027. //# sourceMappingURL=babylon.sprite.js.map
  32028. var BABYLON;
  32029. (function (BABYLON) {
  32030. var Layer = (function () {
  32031. function Layer(name, imgUrl, scene, isBackground, color) {
  32032. this.name = name;
  32033. this.scale = new BABYLON.Vector2(1, 1);
  32034. this.offset = new BABYLON.Vector2(0, 0);
  32035. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  32036. this._vertexBuffers = {};
  32037. // Events
  32038. /**
  32039. * An event triggered when the layer is disposed.
  32040. * @type {BABYLON.Observable}
  32041. */
  32042. this.onDisposeObservable = new BABYLON.Observable();
  32043. /**
  32044. * An event triggered before rendering the scene
  32045. * @type {BABYLON.Observable}
  32046. */
  32047. this.onBeforeRenderObservable = new BABYLON.Observable();
  32048. /**
  32049. * An event triggered after rendering the scene
  32050. * @type {BABYLON.Observable}
  32051. */
  32052. this.onAfterRenderObservable = new BABYLON.Observable();
  32053. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  32054. this.isBackground = isBackground === undefined ? true : isBackground;
  32055. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  32056. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32057. this._scene.layers.push(this);
  32058. var engine = scene.getEngine();
  32059. // VBO
  32060. var vertices = [];
  32061. vertices.push(1, 1);
  32062. vertices.push(-1, 1);
  32063. vertices.push(-1, -1);
  32064. vertices.push(1, -1);
  32065. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32066. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  32067. // Indices
  32068. var indices = [];
  32069. indices.push(0);
  32070. indices.push(1);
  32071. indices.push(2);
  32072. indices.push(0);
  32073. indices.push(2);
  32074. indices.push(3);
  32075. this._indexBuffer = engine.createIndexBuffer(indices);
  32076. // Effects
  32077. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  32078. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  32079. }
  32080. Object.defineProperty(Layer.prototype, "onDispose", {
  32081. set: function (callback) {
  32082. if (this._onDisposeObserver) {
  32083. this.onDisposeObservable.remove(this._onDisposeObserver);
  32084. }
  32085. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32086. },
  32087. enumerable: true,
  32088. configurable: true
  32089. });
  32090. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  32091. set: function (callback) {
  32092. if (this._onBeforeRenderObserver) {
  32093. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32094. }
  32095. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32096. },
  32097. enumerable: true,
  32098. configurable: true
  32099. });
  32100. Object.defineProperty(Layer.prototype, "onAfterRender", {
  32101. set: function (callback) {
  32102. if (this._onAfterRenderObserver) {
  32103. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32104. }
  32105. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32106. },
  32107. enumerable: true,
  32108. configurable: true
  32109. });
  32110. Layer.prototype.render = function () {
  32111. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  32112. // Check
  32113. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  32114. return;
  32115. var engine = this._scene.getEngine();
  32116. this.onBeforeRenderObservable.notifyObservers(this);
  32117. // Render
  32118. engine.enableEffect(currentEffect);
  32119. engine.setState(false);
  32120. // Texture
  32121. currentEffect.setTexture("textureSampler", this.texture);
  32122. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  32123. // Color
  32124. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  32125. // Scale / offset
  32126. currentEffect.setVector2("offset", this.offset);
  32127. currentEffect.setVector2("scale", this.scale);
  32128. // VBOs
  32129. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  32130. // Draw order
  32131. if (!this.alphaTest) {
  32132. engine.setAlphaMode(this.alphaBlendingMode);
  32133. engine.draw(true, 0, 6);
  32134. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32135. }
  32136. else {
  32137. engine.draw(true, 0, 6);
  32138. }
  32139. this.onAfterRenderObservable.notifyObservers(this);
  32140. };
  32141. Layer.prototype.dispose = function () {
  32142. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32143. if (vertexBuffer) {
  32144. vertexBuffer.dispose();
  32145. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32146. }
  32147. if (this._indexBuffer) {
  32148. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32149. this._indexBuffer = null;
  32150. }
  32151. if (this.texture) {
  32152. this.texture.dispose();
  32153. this.texture = null;
  32154. }
  32155. // Remove from scene
  32156. var index = this._scene.layers.indexOf(this);
  32157. this._scene.layers.splice(index, 1);
  32158. // Callback
  32159. this.onDisposeObservable.notifyObservers(this);
  32160. this.onDisposeObservable.clear();
  32161. this.onAfterRenderObservable.clear();
  32162. this.onBeforeRenderObservable.clear();
  32163. };
  32164. return Layer;
  32165. }());
  32166. BABYLON.Layer = Layer;
  32167. })(BABYLON || (BABYLON = {}));
  32168. //# sourceMappingURL=babylon.layer.js.map
  32169. var BABYLON;
  32170. (function (BABYLON) {
  32171. var Particle = (function () {
  32172. function Particle() {
  32173. this.position = BABYLON.Vector3.Zero();
  32174. this.direction = BABYLON.Vector3.Zero();
  32175. this.color = new BABYLON.Color4(0, 0, 0, 0);
  32176. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  32177. this.lifeTime = 1.0;
  32178. this.age = 0;
  32179. this.size = 0;
  32180. this.angle = 0;
  32181. this.angularSpeed = 0;
  32182. }
  32183. Particle.prototype.copyTo = function (other) {
  32184. other.position.copyFrom(this.position);
  32185. other.direction.copyFrom(this.direction);
  32186. other.color.copyFrom(this.color);
  32187. other.colorStep.copyFrom(this.colorStep);
  32188. other.lifeTime = this.lifeTime;
  32189. other.age = this.age;
  32190. other.size = this.size;
  32191. other.angle = this.angle;
  32192. other.angularSpeed = this.angularSpeed;
  32193. };
  32194. return Particle;
  32195. }());
  32196. BABYLON.Particle = Particle;
  32197. })(BABYLON || (BABYLON = {}));
  32198. //# sourceMappingURL=babylon.particle.js.map
  32199. var BABYLON;
  32200. (function (BABYLON) {
  32201. var randomNumber = function (min, max) {
  32202. if (min === max) {
  32203. return (min);
  32204. }
  32205. var random = Math.random();
  32206. return ((random * (max - min)) + min);
  32207. };
  32208. var ParticleSystem = (function () {
  32209. function ParticleSystem(name, capacity, scene, customEffect) {
  32210. var _this = this;
  32211. this.name = name;
  32212. // Members
  32213. this.animations = [];
  32214. this.renderingGroupId = 0;
  32215. this.emitter = null;
  32216. this.emitRate = 10;
  32217. this.manualEmitCount = -1;
  32218. this.updateSpeed = 0.01;
  32219. this.targetStopDuration = 0;
  32220. this.disposeOnStop = false;
  32221. this.minEmitPower = 1;
  32222. this.maxEmitPower = 1;
  32223. this.minLifeTime = 1;
  32224. this.maxLifeTime = 1;
  32225. this.minSize = 1;
  32226. this.maxSize = 1;
  32227. this.minAngularSpeed = 0;
  32228. this.maxAngularSpeed = 0;
  32229. this.layerMask = 0x0FFFFFFF;
  32230. this.customShader = null;
  32231. this.preventAutoStart = false;
  32232. /**
  32233. * An event triggered when the system is disposed.
  32234. * @type {BABYLON.Observable}
  32235. */
  32236. this.onDisposeObservable = new BABYLON.Observable();
  32237. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  32238. this.forceDepthWrite = false;
  32239. this.gravity = BABYLON.Vector3.Zero();
  32240. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  32241. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  32242. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  32243. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32244. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32245. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32246. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  32247. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32248. this.particles = new Array();
  32249. this._stockParticles = new Array();
  32250. this._newPartsExcess = 0;
  32251. this._vertexBuffers = {};
  32252. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  32253. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  32254. this._scaledDirection = BABYLON.Vector3.Zero();
  32255. this._scaledGravity = BABYLON.Vector3.Zero();
  32256. this._currentRenderId = -1;
  32257. this._started = false;
  32258. this._stopped = false;
  32259. this._actualFrame = 0;
  32260. this.id = name;
  32261. this._capacity = capacity;
  32262. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32263. this._customEffect = customEffect;
  32264. scene.particleSystems.push(this);
  32265. var indices = [];
  32266. var index = 0;
  32267. for (var count = 0; count < capacity; count++) {
  32268. indices.push(index);
  32269. indices.push(index + 1);
  32270. indices.push(index + 2);
  32271. indices.push(index);
  32272. indices.push(index + 2);
  32273. indices.push(index + 3);
  32274. index += 4;
  32275. }
  32276. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32277. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  32278. this._vertexData = new Float32Array(capacity * 11 * 4);
  32279. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  32280. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  32281. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  32282. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  32283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  32284. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  32285. this._vertexBuffers["options"] = options;
  32286. // Default behaviors
  32287. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  32288. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  32289. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  32290. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  32291. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  32292. };
  32293. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  32294. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  32295. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  32296. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  32297. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  32298. };
  32299. this.updateFunction = function (particles) {
  32300. for (var index = 0; index < particles.length; index++) {
  32301. var particle = particles[index];
  32302. particle.age += _this._scaledUpdateSpeed;
  32303. if (particle.age >= particle.lifeTime) {
  32304. _this.recycleParticle(particle);
  32305. index--;
  32306. continue;
  32307. }
  32308. else {
  32309. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  32310. particle.color.addInPlace(_this._scaledColorStep);
  32311. if (particle.color.a < 0)
  32312. particle.color.a = 0;
  32313. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  32314. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  32315. particle.position.addInPlace(_this._scaledDirection);
  32316. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  32317. particle.direction.addInPlace(_this._scaledGravity);
  32318. }
  32319. }
  32320. };
  32321. }
  32322. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  32323. set: function (callback) {
  32324. if (this._onDisposeObserver) {
  32325. this.onDisposeObservable.remove(this._onDisposeObserver);
  32326. }
  32327. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32328. },
  32329. enumerable: true,
  32330. configurable: true
  32331. });
  32332. ParticleSystem.prototype.recycleParticle = function (particle) {
  32333. var lastParticle = this.particles.pop();
  32334. if (lastParticle !== particle) {
  32335. lastParticle.copyTo(particle);
  32336. this._stockParticles.push(lastParticle);
  32337. }
  32338. };
  32339. ParticleSystem.prototype.getCapacity = function () {
  32340. return this._capacity;
  32341. };
  32342. ParticleSystem.prototype.isAlive = function () {
  32343. return this._alive;
  32344. };
  32345. ParticleSystem.prototype.isStarted = function () {
  32346. return this._started;
  32347. };
  32348. ParticleSystem.prototype.start = function () {
  32349. this._started = true;
  32350. this._stopped = false;
  32351. this._actualFrame = 0;
  32352. };
  32353. ParticleSystem.prototype.stop = function () {
  32354. this._stopped = true;
  32355. };
  32356. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  32357. var offset = index * 11;
  32358. this._vertexData[offset] = particle.position.x;
  32359. this._vertexData[offset + 1] = particle.position.y;
  32360. this._vertexData[offset + 2] = particle.position.z;
  32361. this._vertexData[offset + 3] = particle.color.r;
  32362. this._vertexData[offset + 4] = particle.color.g;
  32363. this._vertexData[offset + 5] = particle.color.b;
  32364. this._vertexData[offset + 6] = particle.color.a;
  32365. this._vertexData[offset + 7] = particle.angle;
  32366. this._vertexData[offset + 8] = particle.size;
  32367. this._vertexData[offset + 9] = offsetX;
  32368. this._vertexData[offset + 10] = offsetY;
  32369. };
  32370. ParticleSystem.prototype._update = function (newParticles) {
  32371. // Update current
  32372. this._alive = this.particles.length > 0;
  32373. this.updateFunction(this.particles);
  32374. // Add new ones
  32375. var worldMatrix;
  32376. if (this.emitter.position) {
  32377. worldMatrix = this.emitter.getWorldMatrix();
  32378. }
  32379. else {
  32380. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  32381. }
  32382. var particle;
  32383. for (var index = 0; index < newParticles; index++) {
  32384. if (this.particles.length === this._capacity) {
  32385. break;
  32386. }
  32387. if (this._stockParticles.length !== 0) {
  32388. particle = this._stockParticles.pop();
  32389. particle.age = 0;
  32390. }
  32391. else {
  32392. particle = new BABYLON.Particle();
  32393. }
  32394. this.particles.push(particle);
  32395. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  32396. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  32397. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  32398. particle.size = randomNumber(this.minSize, this.maxSize);
  32399. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  32400. this.startPositionFunction(worldMatrix, particle.position, particle);
  32401. var step = randomNumber(0, 1.0);
  32402. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  32403. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  32404. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  32405. }
  32406. };
  32407. ParticleSystem.prototype._getEffect = function () {
  32408. if (this._customEffect) {
  32409. return this._customEffect;
  32410. }
  32411. ;
  32412. var defines = [];
  32413. if (this._scene.clipPlane) {
  32414. defines.push("#define CLIPPLANE");
  32415. }
  32416. // Effect
  32417. var join = defines.join("\n");
  32418. if (this._cachedDefines !== join) {
  32419. this._cachedDefines = join;
  32420. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  32421. }
  32422. return this._effect;
  32423. };
  32424. ParticleSystem.prototype.animate = function () {
  32425. if (!this._started)
  32426. return;
  32427. var effect = this._getEffect();
  32428. // Check
  32429. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  32430. return;
  32431. if (this._currentRenderId === this._scene.getRenderId()) {
  32432. return;
  32433. }
  32434. this._currentRenderId = this._scene.getRenderId();
  32435. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  32436. // determine the number of particles we need to create
  32437. var newParticles;
  32438. if (this.manualEmitCount > -1) {
  32439. newParticles = this.manualEmitCount;
  32440. this._newPartsExcess = 0;
  32441. this.manualEmitCount = 0;
  32442. }
  32443. else {
  32444. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  32445. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  32446. }
  32447. if (this._newPartsExcess > 1.0) {
  32448. newParticles += this._newPartsExcess >> 0;
  32449. this._newPartsExcess -= this._newPartsExcess >> 0;
  32450. }
  32451. this._alive = false;
  32452. if (!this._stopped) {
  32453. this._actualFrame += this._scaledUpdateSpeed;
  32454. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  32455. this.stop();
  32456. }
  32457. else {
  32458. newParticles = 0;
  32459. }
  32460. this._update(newParticles);
  32461. // Stopped?
  32462. if (this._stopped) {
  32463. if (!this._alive) {
  32464. this._started = false;
  32465. if (this.disposeOnStop) {
  32466. this._scene._toBeDisposed.push(this);
  32467. }
  32468. }
  32469. }
  32470. // Update VBO
  32471. var offset = 0;
  32472. for (var index = 0; index < this.particles.length; index++) {
  32473. var particle = this.particles[index];
  32474. this._appendParticleVertex(offset++, particle, 0, 0);
  32475. this._appendParticleVertex(offset++, particle, 1, 0);
  32476. this._appendParticleVertex(offset++, particle, 1, 1);
  32477. this._appendParticleVertex(offset++, particle, 0, 1);
  32478. }
  32479. this._vertexBuffer.update(this._vertexData);
  32480. };
  32481. ParticleSystem.prototype.render = function () {
  32482. var effect = this._getEffect();
  32483. // Check
  32484. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  32485. return 0;
  32486. var engine = this._scene.getEngine();
  32487. // Render
  32488. engine.enableEffect(effect);
  32489. engine.setState(false);
  32490. var viewMatrix = this._scene.getViewMatrix();
  32491. effect.setTexture("diffuseSampler", this.particleTexture);
  32492. effect.setMatrix("view", viewMatrix);
  32493. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  32494. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  32495. if (this._scene.clipPlane) {
  32496. var clipPlane = this._scene.clipPlane;
  32497. var invView = viewMatrix.clone();
  32498. invView.invert();
  32499. effect.setMatrix("invView", invView);
  32500. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  32501. }
  32502. // VBOs
  32503. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32504. // Draw order
  32505. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  32506. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32507. }
  32508. else {
  32509. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32510. }
  32511. if (this.forceDepthWrite) {
  32512. engine.setDepthWrite(true);
  32513. }
  32514. engine.draw(true, 0, this.particles.length * 6);
  32515. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32516. return this.particles.length;
  32517. };
  32518. ParticleSystem.prototype.dispose = function () {
  32519. if (this._vertexBuffer) {
  32520. this._vertexBuffer.dispose();
  32521. this._vertexBuffer = null;
  32522. }
  32523. if (this._indexBuffer) {
  32524. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32525. this._indexBuffer = null;
  32526. }
  32527. if (this.particleTexture) {
  32528. this.particleTexture.dispose();
  32529. this.particleTexture = null;
  32530. }
  32531. // Remove from scene
  32532. var index = this._scene.particleSystems.indexOf(this);
  32533. this._scene.particleSystems.splice(index, 1);
  32534. // Callback
  32535. this.onDisposeObservable.notifyObservers(this);
  32536. this.onDisposeObservable.clear();
  32537. };
  32538. // Clone
  32539. ParticleSystem.prototype.clone = function (name, newEmitter) {
  32540. var custom = null;
  32541. var program = null;
  32542. if (this.customShader != null) {
  32543. program = this.customShader;
  32544. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32545. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32546. }
  32547. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  32548. result.customShader = program;
  32549. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  32550. if (newEmitter === undefined) {
  32551. newEmitter = this.emitter;
  32552. }
  32553. result.emitter = newEmitter;
  32554. if (this.particleTexture) {
  32555. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  32556. }
  32557. if (!this.preventAutoStart) {
  32558. result.start();
  32559. }
  32560. return result;
  32561. };
  32562. ParticleSystem.prototype.serialize = function () {
  32563. var serializationObject = {};
  32564. serializationObject.name = this.name;
  32565. serializationObject.id = this.id;
  32566. // Emitter
  32567. if (this.emitter.position) {
  32568. serializationObject.emitterId = this.emitter.id;
  32569. }
  32570. else {
  32571. serializationObject.emitter = this.emitter.asArray();
  32572. }
  32573. serializationObject.capacity = this.getCapacity();
  32574. if (this.particleTexture) {
  32575. serializationObject.textureName = this.particleTexture.name;
  32576. }
  32577. // Animations
  32578. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32579. // Particle system
  32580. serializationObject.minAngularSpeed = this.minAngularSpeed;
  32581. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  32582. serializationObject.minSize = this.minSize;
  32583. serializationObject.maxSize = this.maxSize;
  32584. serializationObject.minEmitPower = this.minEmitPower;
  32585. serializationObject.maxEmitPower = this.maxEmitPower;
  32586. serializationObject.minLifeTime = this.minLifeTime;
  32587. serializationObject.maxLifeTime = this.maxLifeTime;
  32588. serializationObject.emitRate = this.emitRate;
  32589. serializationObject.minEmitBox = this.minEmitBox.asArray();
  32590. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  32591. serializationObject.gravity = this.gravity.asArray();
  32592. serializationObject.direction1 = this.direction1.asArray();
  32593. serializationObject.direction2 = this.direction2.asArray();
  32594. serializationObject.color1 = this.color1.asArray();
  32595. serializationObject.color2 = this.color2.asArray();
  32596. serializationObject.colorDead = this.colorDead.asArray();
  32597. serializationObject.updateSpeed = this.updateSpeed;
  32598. serializationObject.targetStopDuration = this.targetStopDuration;
  32599. serializationObject.textureMask = this.textureMask.asArray();
  32600. serializationObject.blendMode = this.blendMode;
  32601. serializationObject.customShader = this.customShader;
  32602. serializationObject.preventAutoStart = this.preventAutoStart;
  32603. return serializationObject;
  32604. };
  32605. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  32606. var name = parsedParticleSystem.name;
  32607. var custom = null;
  32608. var program = null;
  32609. if (parsedParticleSystem.customShader) {
  32610. program = parsedParticleSystem.customShader;
  32611. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32612. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32613. }
  32614. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  32615. particleSystem.customShader = program;
  32616. if (parsedParticleSystem.id) {
  32617. particleSystem.id = parsedParticleSystem.id;
  32618. }
  32619. // Auto start
  32620. if (parsedParticleSystem.preventAutoStart) {
  32621. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  32622. }
  32623. // Texture
  32624. if (parsedParticleSystem.textureName) {
  32625. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  32626. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  32627. }
  32628. // Emitter
  32629. if (parsedParticleSystem.emitterId) {
  32630. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  32631. }
  32632. else {
  32633. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  32634. }
  32635. // Animations
  32636. if (parsedParticleSystem.animations) {
  32637. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  32638. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  32639. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32640. }
  32641. }
  32642. if (parsedParticleSystem.autoAnimate) {
  32643. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  32644. }
  32645. // Particle system
  32646. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  32647. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  32648. particleSystem.minSize = parsedParticleSystem.minSize;
  32649. particleSystem.maxSize = parsedParticleSystem.maxSize;
  32650. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  32651. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  32652. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  32653. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  32654. particleSystem.emitRate = parsedParticleSystem.emitRate;
  32655. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  32656. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  32657. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  32658. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  32659. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  32660. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  32661. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  32662. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  32663. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  32664. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  32665. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  32666. particleSystem.blendMode = parsedParticleSystem.blendMode;
  32667. if (!particleSystem.preventAutoStart) {
  32668. particleSystem.start();
  32669. }
  32670. return particleSystem;
  32671. };
  32672. return ParticleSystem;
  32673. }());
  32674. // Statics
  32675. ParticleSystem.BLENDMODE_ONEONE = 0;
  32676. ParticleSystem.BLENDMODE_STANDARD = 1;
  32677. BABYLON.ParticleSystem = ParticleSystem;
  32678. })(BABYLON || (BABYLON = {}));
  32679. //# sourceMappingURL=babylon.particleSystem.js.map
  32680. var BABYLON;
  32681. (function (BABYLON) {
  32682. var AnimationRange = (function () {
  32683. function AnimationRange(name, from, to) {
  32684. this.name = name;
  32685. this.from = from;
  32686. this.to = to;
  32687. }
  32688. AnimationRange.prototype.clone = function () {
  32689. return new AnimationRange(this.name, this.from, this.to);
  32690. };
  32691. return AnimationRange;
  32692. }());
  32693. BABYLON.AnimationRange = AnimationRange;
  32694. /**
  32695. * Composed of a frame, and an action function
  32696. */
  32697. var AnimationEvent = (function () {
  32698. function AnimationEvent(frame, action, onlyOnce) {
  32699. this.frame = frame;
  32700. this.action = action;
  32701. this.onlyOnce = onlyOnce;
  32702. this.isDone = false;
  32703. }
  32704. return AnimationEvent;
  32705. }());
  32706. BABYLON.AnimationEvent = AnimationEvent;
  32707. var PathCursor = (function () {
  32708. function PathCursor(path) {
  32709. this.path = path;
  32710. this._onchange = new Array();
  32711. this.value = 0;
  32712. this.animations = new Array();
  32713. }
  32714. PathCursor.prototype.getPoint = function () {
  32715. var point = this.path.getPointAtLengthPosition(this.value);
  32716. return new BABYLON.Vector3(point.x, 0, point.y);
  32717. };
  32718. PathCursor.prototype.moveAhead = function (step) {
  32719. if (step === void 0) { step = 0.002; }
  32720. this.move(step);
  32721. return this;
  32722. };
  32723. PathCursor.prototype.moveBack = function (step) {
  32724. if (step === void 0) { step = 0.002; }
  32725. this.move(-step);
  32726. return this;
  32727. };
  32728. PathCursor.prototype.move = function (step) {
  32729. if (Math.abs(step) > 1) {
  32730. throw "step size should be less than 1.";
  32731. }
  32732. this.value += step;
  32733. this.ensureLimits();
  32734. this.raiseOnChange();
  32735. return this;
  32736. };
  32737. PathCursor.prototype.ensureLimits = function () {
  32738. while (this.value > 1) {
  32739. this.value -= 1;
  32740. }
  32741. while (this.value < 0) {
  32742. this.value += 1;
  32743. }
  32744. return this;
  32745. };
  32746. // used by animation engine
  32747. PathCursor.prototype.markAsDirty = function (propertyName) {
  32748. this.ensureLimits();
  32749. this.raiseOnChange();
  32750. return this;
  32751. };
  32752. PathCursor.prototype.raiseOnChange = function () {
  32753. var _this = this;
  32754. this._onchange.forEach(function (f) { return f(_this); });
  32755. return this;
  32756. };
  32757. PathCursor.prototype.onchange = function (f) {
  32758. this._onchange.push(f);
  32759. return this;
  32760. };
  32761. return PathCursor;
  32762. }());
  32763. BABYLON.PathCursor = PathCursor;
  32764. var Animation = (function () {
  32765. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32766. this.name = name;
  32767. this.targetProperty = targetProperty;
  32768. this.framePerSecond = framePerSecond;
  32769. this.dataType = dataType;
  32770. this.loopMode = loopMode;
  32771. this.enableBlending = enableBlending;
  32772. this._offsetsCache = {};
  32773. this._highLimitsCache = {};
  32774. this._stopped = false;
  32775. this._blendingFactor = 0;
  32776. // The set of event that will be linked to this animation
  32777. this._events = new Array();
  32778. this.allowMatricesInterpolation = false;
  32779. this.blendingSpeed = 0.01;
  32780. this._ranges = {};
  32781. this.targetPropertyPath = targetProperty.split(".");
  32782. this.dataType = dataType;
  32783. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32784. }
  32785. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32786. var dataType = undefined;
  32787. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32788. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32789. }
  32790. else if (from instanceof BABYLON.Quaternion) {
  32791. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32792. }
  32793. else if (from instanceof BABYLON.Vector3) {
  32794. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32795. }
  32796. else if (from instanceof BABYLON.Vector2) {
  32797. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32798. }
  32799. else if (from instanceof BABYLON.Color3) {
  32800. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32801. }
  32802. else if (from instanceof BABYLON.Size) {
  32803. dataType = Animation.ANIMATIONTYPE_SIZE;
  32804. }
  32805. if (dataType == undefined) {
  32806. return null;
  32807. }
  32808. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32809. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32810. animation.setKeys(keys);
  32811. if (easingFunction !== undefined) {
  32812. animation.setEasingFunction(easingFunction);
  32813. }
  32814. return animation;
  32815. };
  32816. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32817. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32818. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32819. };
  32820. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32821. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32822. node.animations.push(animation);
  32823. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32824. };
  32825. // Methods
  32826. /**
  32827. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32828. */
  32829. Animation.prototype.toString = function (fullDetails) {
  32830. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32831. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32832. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32833. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32834. if (fullDetails) {
  32835. ret += ", Ranges: {";
  32836. var first = true;
  32837. for (var name in this._ranges) {
  32838. if (first) {
  32839. ret += ", ";
  32840. first = false;
  32841. }
  32842. ret += name;
  32843. }
  32844. ret += "}";
  32845. }
  32846. return ret;
  32847. };
  32848. /**
  32849. * Add an event to this animation.
  32850. */
  32851. Animation.prototype.addEvent = function (event) {
  32852. this._events.push(event);
  32853. };
  32854. /**
  32855. * Remove all events found at the given frame
  32856. * @param frame
  32857. */
  32858. Animation.prototype.removeEvents = function (frame) {
  32859. for (var index = 0; index < this._events.length; index++) {
  32860. if (this._events[index].frame === frame) {
  32861. this._events.splice(index, 1);
  32862. index--;
  32863. }
  32864. }
  32865. };
  32866. Animation.prototype.createRange = function (name, from, to) {
  32867. // check name not already in use; could happen for bones after serialized
  32868. if (!this._ranges[name]) {
  32869. this._ranges[name] = new AnimationRange(name, from, to);
  32870. }
  32871. };
  32872. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32873. if (deleteFrames === void 0) { deleteFrames = true; }
  32874. if (this._ranges[name]) {
  32875. if (deleteFrames) {
  32876. var from = this._ranges[name].from;
  32877. var to = this._ranges[name].to;
  32878. // this loop MUST go high to low for multiple splices to work
  32879. for (var key = this._keys.length - 1; key >= 0; key--) {
  32880. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32881. this._keys.splice(key, 1);
  32882. }
  32883. }
  32884. }
  32885. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32886. }
  32887. };
  32888. Animation.prototype.getRange = function (name) {
  32889. return this._ranges[name];
  32890. };
  32891. Animation.prototype.reset = function () {
  32892. this._offsetsCache = {};
  32893. this._highLimitsCache = {};
  32894. this.currentFrame = 0;
  32895. this._blendingFactor = 0;
  32896. this._originalBlendValue = null;
  32897. };
  32898. Animation.prototype.isStopped = function () {
  32899. return this._stopped;
  32900. };
  32901. Animation.prototype.getKeys = function () {
  32902. return this._keys;
  32903. };
  32904. Animation.prototype.getHighestFrame = function () {
  32905. var ret = 0;
  32906. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32907. if (ret < this._keys[key].frame) {
  32908. ret = this._keys[key].frame;
  32909. }
  32910. }
  32911. return ret;
  32912. };
  32913. Animation.prototype.getEasingFunction = function () {
  32914. return this._easingFunction;
  32915. };
  32916. Animation.prototype.setEasingFunction = function (easingFunction) {
  32917. this._easingFunction = easingFunction;
  32918. };
  32919. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32920. return startValue + (endValue - startValue) * gradient;
  32921. };
  32922. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32923. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32924. };
  32925. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32926. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32927. };
  32928. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32929. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32930. };
  32931. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32932. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32933. };
  32934. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32935. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32936. };
  32937. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32938. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32939. };
  32940. Animation.prototype.clone = function () {
  32941. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32942. clone.enableBlending = this.enableBlending;
  32943. clone.blendingSpeed = this.blendingSpeed;
  32944. if (this._keys) {
  32945. clone.setKeys(this._keys);
  32946. }
  32947. if (this._ranges) {
  32948. clone._ranges = {};
  32949. for (var name in this._ranges) {
  32950. clone._ranges[name] = this._ranges[name].clone();
  32951. }
  32952. }
  32953. return clone;
  32954. };
  32955. Animation.prototype.setKeys = function (values) {
  32956. this._keys = values.slice(0);
  32957. this._offsetsCache = {};
  32958. this._highLimitsCache = {};
  32959. };
  32960. Animation.prototype._getKeyValue = function (value) {
  32961. if (typeof value === "function") {
  32962. return value();
  32963. }
  32964. return value;
  32965. };
  32966. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32967. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32968. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32969. }
  32970. this.currentFrame = currentFrame;
  32971. // Try to get a hash to find the right key
  32972. 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));
  32973. if (this._keys[startKey].frame >= currentFrame) {
  32974. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32975. startKey--;
  32976. }
  32977. }
  32978. for (var key = startKey; key < this._keys.length; key++) {
  32979. if (this._keys[key + 1].frame >= currentFrame) {
  32980. var startValue = this._getKeyValue(this._keys[key].value);
  32981. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32982. // gradient : percent of currentFrame between the frame inf and the frame sup
  32983. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32984. // check for easingFunction and correction of gradient
  32985. if (this._easingFunction != null) {
  32986. gradient = this._easingFunction.ease(gradient);
  32987. }
  32988. switch (this.dataType) {
  32989. // Float
  32990. case Animation.ANIMATIONTYPE_FLOAT:
  32991. switch (loopMode) {
  32992. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32993. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32994. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32995. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32996. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32997. }
  32998. break;
  32999. // Quaternion
  33000. case Animation.ANIMATIONTYPE_QUATERNION:
  33001. var quaternion = null;
  33002. switch (loopMode) {
  33003. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33004. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33005. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  33006. break;
  33007. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33008. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33009. break;
  33010. }
  33011. return quaternion;
  33012. // Vector3
  33013. case Animation.ANIMATIONTYPE_VECTOR3:
  33014. switch (loopMode) {
  33015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33017. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  33018. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33019. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33020. }
  33021. // Vector2
  33022. case Animation.ANIMATIONTYPE_VECTOR2:
  33023. switch (loopMode) {
  33024. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33025. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33026. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  33027. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33028. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33029. }
  33030. // Size
  33031. case Animation.ANIMATIONTYPE_SIZE:
  33032. switch (loopMode) {
  33033. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33034. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33035. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  33036. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33037. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33038. }
  33039. // Color3
  33040. case Animation.ANIMATIONTYPE_COLOR3:
  33041. switch (loopMode) {
  33042. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33043. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33044. return this.color3InterpolateFunction(startValue, endValue, gradient);
  33045. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33046. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33047. }
  33048. // Matrix
  33049. case Animation.ANIMATIONTYPE_MATRIX:
  33050. switch (loopMode) {
  33051. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33052. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33053. if (this.allowMatricesInterpolation) {
  33054. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  33055. }
  33056. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33057. return startValue;
  33058. }
  33059. default:
  33060. break;
  33061. }
  33062. break;
  33063. }
  33064. }
  33065. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  33066. };
  33067. Animation.prototype.setValue = function (currentValue, blend) {
  33068. if (blend === void 0) { blend = false; }
  33069. // Set value
  33070. var path;
  33071. var destination;
  33072. if (this.targetPropertyPath.length > 1) {
  33073. var property = this._target[this.targetPropertyPath[0]];
  33074. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  33075. property = property[this.targetPropertyPath[index]];
  33076. }
  33077. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  33078. destination = property;
  33079. }
  33080. else {
  33081. path = this.targetPropertyPath[0];
  33082. destination = this._target;
  33083. }
  33084. // Blending
  33085. if (this.enableBlending && this._blendingFactor <= 1.0) {
  33086. if (!this._originalBlendValue) {
  33087. if (destination[path].clone) {
  33088. this._originalBlendValue = destination[path].clone();
  33089. }
  33090. else {
  33091. this._originalBlendValue = destination[path];
  33092. }
  33093. }
  33094. if (this._originalBlendValue.prototype) {
  33095. if (this._originalBlendValue.prototype.Lerp) {
  33096. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  33097. }
  33098. else {
  33099. destination[path] = currentValue;
  33100. }
  33101. }
  33102. else if (this._originalBlendValue.m) {
  33103. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  33104. }
  33105. else {
  33106. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  33107. }
  33108. this._blendingFactor += this.blendingSpeed;
  33109. }
  33110. else {
  33111. destination[path] = currentValue;
  33112. }
  33113. if (this._target.markAsDirty) {
  33114. this._target.markAsDirty(this.targetProperty);
  33115. }
  33116. };
  33117. Animation.prototype.goToFrame = function (frame) {
  33118. if (frame < this._keys[0].frame) {
  33119. frame = this._keys[0].frame;
  33120. }
  33121. else if (frame > this._keys[this._keys.length - 1].frame) {
  33122. frame = this._keys[this._keys.length - 1].frame;
  33123. }
  33124. var currentValue = this._interpolate(frame, 0, this.loopMode);
  33125. this.setValue(currentValue);
  33126. };
  33127. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  33128. if (blend === void 0) { blend = false; }
  33129. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  33130. this._stopped = true;
  33131. return false;
  33132. }
  33133. var returnValue = true;
  33134. // Adding a start key at frame 0 if missing
  33135. if (this._keys[0].frame !== 0) {
  33136. var newKey = { frame: 0, value: this._keys[0].value };
  33137. this._keys.splice(0, 0, newKey);
  33138. }
  33139. // Check limits
  33140. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  33141. from = this._keys[0].frame;
  33142. }
  33143. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  33144. to = this._keys[this._keys.length - 1].frame;
  33145. }
  33146. //to and from cannot be the same key
  33147. if (from === to) {
  33148. from++;
  33149. }
  33150. // Compute ratio
  33151. var range = to - from;
  33152. var offsetValue;
  33153. // ratio represents the frame delta between from and to
  33154. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  33155. var highLimitValue = 0;
  33156. if (ratio > range && !loop) {
  33157. returnValue = false;
  33158. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  33159. }
  33160. else {
  33161. // Get max value if required
  33162. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  33163. var keyOffset = to.toString() + from.toString();
  33164. if (!this._offsetsCache[keyOffset]) {
  33165. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33166. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33167. switch (this.dataType) {
  33168. // Float
  33169. case Animation.ANIMATIONTYPE_FLOAT:
  33170. this._offsetsCache[keyOffset] = toValue - fromValue;
  33171. break;
  33172. // Quaternion
  33173. case Animation.ANIMATIONTYPE_QUATERNION:
  33174. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33175. break;
  33176. // Vector3
  33177. case Animation.ANIMATIONTYPE_VECTOR3:
  33178. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33179. // Vector2
  33180. case Animation.ANIMATIONTYPE_VECTOR2:
  33181. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33182. // Size
  33183. case Animation.ANIMATIONTYPE_SIZE:
  33184. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33185. // Color3
  33186. case Animation.ANIMATIONTYPE_COLOR3:
  33187. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33188. default:
  33189. break;
  33190. }
  33191. this._highLimitsCache[keyOffset] = toValue;
  33192. }
  33193. highLimitValue = this._highLimitsCache[keyOffset];
  33194. offsetValue = this._offsetsCache[keyOffset];
  33195. }
  33196. }
  33197. if (offsetValue === undefined) {
  33198. switch (this.dataType) {
  33199. // Float
  33200. case Animation.ANIMATIONTYPE_FLOAT:
  33201. offsetValue = 0;
  33202. break;
  33203. // Quaternion
  33204. case Animation.ANIMATIONTYPE_QUATERNION:
  33205. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  33206. break;
  33207. // Vector3
  33208. case Animation.ANIMATIONTYPE_VECTOR3:
  33209. offsetValue = BABYLON.Vector3.Zero();
  33210. break;
  33211. // Vector2
  33212. case Animation.ANIMATIONTYPE_VECTOR2:
  33213. offsetValue = BABYLON.Vector2.Zero();
  33214. break;
  33215. // Size
  33216. case Animation.ANIMATIONTYPE_SIZE:
  33217. offsetValue = BABYLON.Size.Zero();
  33218. break;
  33219. // Color3
  33220. case Animation.ANIMATIONTYPE_COLOR3:
  33221. offsetValue = BABYLON.Color3.Black();
  33222. }
  33223. }
  33224. // Compute value
  33225. var repeatCount = (ratio / range) >> 0;
  33226. var currentFrame = returnValue ? from + ratio % range : to;
  33227. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  33228. // Set value
  33229. this.setValue(currentValue);
  33230. // Check events
  33231. for (var index = 0; index < this._events.length; index++) {
  33232. if (currentFrame >= this._events[index].frame) {
  33233. var event = this._events[index];
  33234. if (!event.isDone) {
  33235. // If event should be done only once, remove it.
  33236. if (event.onlyOnce) {
  33237. this._events.splice(index, 1);
  33238. index--;
  33239. }
  33240. event.isDone = true;
  33241. event.action();
  33242. } // Don't do anything if the event has already be done.
  33243. }
  33244. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  33245. // reset event, the animation is looping
  33246. this._events[index].isDone = false;
  33247. }
  33248. }
  33249. if (!returnValue) {
  33250. this._stopped = true;
  33251. }
  33252. return returnValue;
  33253. };
  33254. Animation.prototype.serialize = function () {
  33255. var serializationObject = {};
  33256. serializationObject.name = this.name;
  33257. serializationObject.property = this.targetProperty;
  33258. serializationObject.framePerSecond = this.framePerSecond;
  33259. serializationObject.dataType = this.dataType;
  33260. serializationObject.loopBehavior = this.loopMode;
  33261. serializationObject.enableBlending = this.enableBlending;
  33262. serializationObject.blendingSpeed = this.blendingSpeed;
  33263. var dataType = this.dataType;
  33264. serializationObject.keys = [];
  33265. var keys = this.getKeys();
  33266. for (var index = 0; index < keys.length; index++) {
  33267. var animationKey = keys[index];
  33268. var key = {};
  33269. key.frame = animationKey.frame;
  33270. switch (dataType) {
  33271. case Animation.ANIMATIONTYPE_FLOAT:
  33272. key.values = [animationKey.value];
  33273. break;
  33274. case Animation.ANIMATIONTYPE_QUATERNION:
  33275. case Animation.ANIMATIONTYPE_MATRIX:
  33276. case Animation.ANIMATIONTYPE_VECTOR3:
  33277. case Animation.ANIMATIONTYPE_COLOR3:
  33278. key.values = animationKey.value.asArray();
  33279. break;
  33280. }
  33281. serializationObject.keys.push(key);
  33282. }
  33283. serializationObject.ranges = [];
  33284. for (var name in this._ranges) {
  33285. var range = {};
  33286. range.name = name;
  33287. range.from = this._ranges[name].from;
  33288. range.to = this._ranges[name].to;
  33289. serializationObject.ranges.push(range);
  33290. }
  33291. return serializationObject;
  33292. };
  33293. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  33294. get: function () {
  33295. return Animation._ANIMATIONTYPE_FLOAT;
  33296. },
  33297. enumerable: true,
  33298. configurable: true
  33299. });
  33300. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  33301. get: function () {
  33302. return Animation._ANIMATIONTYPE_VECTOR3;
  33303. },
  33304. enumerable: true,
  33305. configurable: true
  33306. });
  33307. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  33308. get: function () {
  33309. return Animation._ANIMATIONTYPE_VECTOR2;
  33310. },
  33311. enumerable: true,
  33312. configurable: true
  33313. });
  33314. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  33315. get: function () {
  33316. return Animation._ANIMATIONTYPE_SIZE;
  33317. },
  33318. enumerable: true,
  33319. configurable: true
  33320. });
  33321. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  33322. get: function () {
  33323. return Animation._ANIMATIONTYPE_QUATERNION;
  33324. },
  33325. enumerable: true,
  33326. configurable: true
  33327. });
  33328. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  33329. get: function () {
  33330. return Animation._ANIMATIONTYPE_MATRIX;
  33331. },
  33332. enumerable: true,
  33333. configurable: true
  33334. });
  33335. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33336. get: function () {
  33337. return Animation._ANIMATIONTYPE_COLOR3;
  33338. },
  33339. enumerable: true,
  33340. configurable: true
  33341. });
  33342. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33343. get: function () {
  33344. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33345. },
  33346. enumerable: true,
  33347. configurable: true
  33348. });
  33349. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33350. get: function () {
  33351. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33352. },
  33353. enumerable: true,
  33354. configurable: true
  33355. });
  33356. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33357. get: function () {
  33358. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33359. },
  33360. enumerable: true,
  33361. configurable: true
  33362. });
  33363. Animation.Parse = function (parsedAnimation) {
  33364. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33365. var dataType = parsedAnimation.dataType;
  33366. var keys = [];
  33367. var data;
  33368. var index;
  33369. if (parsedAnimation.enableBlending) {
  33370. animation.enableBlending = parsedAnimation.enableBlending;
  33371. }
  33372. if (parsedAnimation.blendingSpeed) {
  33373. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33374. }
  33375. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33376. var key = parsedAnimation.keys[index];
  33377. switch (dataType) {
  33378. case Animation.ANIMATIONTYPE_FLOAT:
  33379. data = key.values[0];
  33380. break;
  33381. case Animation.ANIMATIONTYPE_QUATERNION:
  33382. data = BABYLON.Quaternion.FromArray(key.values);
  33383. break;
  33384. case Animation.ANIMATIONTYPE_MATRIX:
  33385. data = BABYLON.Matrix.FromArray(key.values);
  33386. break;
  33387. case Animation.ANIMATIONTYPE_COLOR3:
  33388. data = BABYLON.Color3.FromArray(key.values);
  33389. break;
  33390. case Animation.ANIMATIONTYPE_VECTOR3:
  33391. default:
  33392. data = BABYLON.Vector3.FromArray(key.values);
  33393. break;
  33394. }
  33395. keys.push({
  33396. frame: key.frame,
  33397. value: data
  33398. });
  33399. }
  33400. animation.setKeys(keys);
  33401. if (parsedAnimation.ranges) {
  33402. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33403. data = parsedAnimation.ranges[index];
  33404. animation.createRange(data.name, data.from, data.to);
  33405. }
  33406. }
  33407. return animation;
  33408. };
  33409. Animation.AppendSerializedAnimations = function (source, destination) {
  33410. if (source.animations) {
  33411. destination.animations = [];
  33412. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33413. var animation = source.animations[animationIndex];
  33414. destination.animations.push(animation.serialize());
  33415. }
  33416. }
  33417. };
  33418. return Animation;
  33419. }());
  33420. // Statics
  33421. Animation._ANIMATIONTYPE_FLOAT = 0;
  33422. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33423. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33424. Animation._ANIMATIONTYPE_MATRIX = 3;
  33425. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33426. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33427. Animation._ANIMATIONTYPE_SIZE = 6;
  33428. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33429. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33430. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33431. BABYLON.Animation = Animation;
  33432. })(BABYLON || (BABYLON = {}));
  33433. //# sourceMappingURL=babylon.animation.js.map
  33434. var BABYLON;
  33435. (function (BABYLON) {
  33436. var Animatable = (function () {
  33437. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33438. if (fromFrame === void 0) { fromFrame = 0; }
  33439. if (toFrame === void 0) { toFrame = 100; }
  33440. if (loopAnimation === void 0) { loopAnimation = false; }
  33441. if (speedRatio === void 0) { speedRatio = 1.0; }
  33442. this.target = target;
  33443. this.fromFrame = fromFrame;
  33444. this.toFrame = toFrame;
  33445. this.loopAnimation = loopAnimation;
  33446. this.speedRatio = speedRatio;
  33447. this.onAnimationEnd = onAnimationEnd;
  33448. this._animations = new Array();
  33449. this._paused = false;
  33450. this.animationStarted = false;
  33451. if (animations) {
  33452. this.appendAnimations(target, animations);
  33453. }
  33454. this._scene = scene;
  33455. scene._activeAnimatables.push(this);
  33456. }
  33457. // Methods
  33458. Animatable.prototype.getAnimations = function () {
  33459. return this._animations;
  33460. };
  33461. Animatable.prototype.appendAnimations = function (target, animations) {
  33462. for (var index = 0; index < animations.length; index++) {
  33463. var animation = animations[index];
  33464. animation._target = target;
  33465. this._animations.push(animation);
  33466. }
  33467. };
  33468. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33469. var animations = this._animations;
  33470. for (var index = 0; index < animations.length; index++) {
  33471. if (animations[index].targetProperty === property) {
  33472. return animations[index];
  33473. }
  33474. }
  33475. return null;
  33476. };
  33477. Animatable.prototype.reset = function () {
  33478. var animations = this._animations;
  33479. for (var index = 0; index < animations.length; index++) {
  33480. animations[index].reset();
  33481. }
  33482. this._localDelayOffset = null;
  33483. this._pausedDelay = null;
  33484. };
  33485. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33486. var animations = this._animations;
  33487. for (var index = 0; index < animations.length; index++) {
  33488. animations[index].enableBlending = true;
  33489. animations[index].blendingSpeed = blendingSpeed;
  33490. }
  33491. };
  33492. Animatable.prototype.disableBlending = function () {
  33493. var animations = this._animations;
  33494. for (var index = 0; index < animations.length; index++) {
  33495. animations[index].enableBlending = false;
  33496. }
  33497. };
  33498. Animatable.prototype.goToFrame = function (frame) {
  33499. var animations = this._animations;
  33500. if (animations[0]) {
  33501. var fps = animations[0].framePerSecond;
  33502. var currentFrame = animations[0].currentFrame;
  33503. var adjustTime = frame - currentFrame;
  33504. var delay = adjustTime * 1000 / fps;
  33505. this._localDelayOffset -= delay;
  33506. }
  33507. for (var index = 0; index < animations.length; index++) {
  33508. animations[index].goToFrame(frame);
  33509. }
  33510. };
  33511. Animatable.prototype.pause = function () {
  33512. if (this._paused) {
  33513. return;
  33514. }
  33515. this._paused = true;
  33516. };
  33517. Animatable.prototype.restart = function () {
  33518. this._paused = false;
  33519. };
  33520. Animatable.prototype.stop = function (animationName) {
  33521. if (animationName) {
  33522. var idx = this._scene._activeAnimatables.indexOf(this);
  33523. if (idx > -1) {
  33524. var animations = this._animations;
  33525. for (var index = animations.length - 1; index >= 0; index--) {
  33526. if (typeof animationName === "string" && animations[index].name != animationName) {
  33527. continue;
  33528. }
  33529. animations[index].reset();
  33530. animations.splice(index, 1);
  33531. }
  33532. if (animations.length == 0) {
  33533. this._scene._activeAnimatables.splice(idx, 1);
  33534. if (this.onAnimationEnd) {
  33535. this.onAnimationEnd();
  33536. }
  33537. }
  33538. }
  33539. }
  33540. else {
  33541. var index = this._scene._activeAnimatables.indexOf(this);
  33542. if (index > -1) {
  33543. this._scene._activeAnimatables.splice(index, 1);
  33544. var animations = this._animations;
  33545. for (var index = 0; index < animations.length; index++) {
  33546. animations[index].reset();
  33547. }
  33548. if (this.onAnimationEnd) {
  33549. this.onAnimationEnd();
  33550. }
  33551. }
  33552. }
  33553. };
  33554. Animatable.prototype._animate = function (delay) {
  33555. if (this._paused) {
  33556. this.animationStarted = false;
  33557. if (!this._pausedDelay) {
  33558. this._pausedDelay = delay;
  33559. }
  33560. return true;
  33561. }
  33562. if (!this._localDelayOffset) {
  33563. this._localDelayOffset = delay;
  33564. }
  33565. else if (this._pausedDelay) {
  33566. this._localDelayOffset += delay - this._pausedDelay;
  33567. this._pausedDelay = null;
  33568. }
  33569. // Animating
  33570. var running = false;
  33571. var animations = this._animations;
  33572. var index;
  33573. for (index = 0; index < animations.length; index++) {
  33574. var animation = animations[index];
  33575. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33576. running = running || isRunning;
  33577. }
  33578. this.animationStarted = running;
  33579. if (!running) {
  33580. // Remove from active animatables
  33581. index = this._scene._activeAnimatables.indexOf(this);
  33582. this._scene._activeAnimatables.splice(index, 1);
  33583. }
  33584. if (!running && this.onAnimationEnd) {
  33585. this.onAnimationEnd();
  33586. this.onAnimationEnd = null;
  33587. }
  33588. return running;
  33589. };
  33590. return Animatable;
  33591. }());
  33592. BABYLON.Animatable = Animatable;
  33593. })(BABYLON || (BABYLON = {}));
  33594. //# sourceMappingURL=babylon.animatable.js.map
  33595. var BABYLON;
  33596. (function (BABYLON) {
  33597. var EasingFunction = (function () {
  33598. function EasingFunction() {
  33599. // Properties
  33600. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33601. }
  33602. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33603. get: function () {
  33604. return EasingFunction._EASINGMODE_EASEIN;
  33605. },
  33606. enumerable: true,
  33607. configurable: true
  33608. });
  33609. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33610. get: function () {
  33611. return EasingFunction._EASINGMODE_EASEOUT;
  33612. },
  33613. enumerable: true,
  33614. configurable: true
  33615. });
  33616. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33617. get: function () {
  33618. return EasingFunction._EASINGMODE_EASEINOUT;
  33619. },
  33620. enumerable: true,
  33621. configurable: true
  33622. });
  33623. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33624. var n = Math.min(Math.max(easingMode, 0), 2);
  33625. this._easingMode = n;
  33626. };
  33627. EasingFunction.prototype.getEasingMode = function () {
  33628. return this._easingMode;
  33629. };
  33630. EasingFunction.prototype.easeInCore = function (gradient) {
  33631. throw new Error('You must implement this method');
  33632. };
  33633. EasingFunction.prototype.ease = function (gradient) {
  33634. switch (this._easingMode) {
  33635. case EasingFunction.EASINGMODE_EASEIN:
  33636. return this.easeInCore(gradient);
  33637. case EasingFunction.EASINGMODE_EASEOUT:
  33638. return (1 - this.easeInCore(1 - gradient));
  33639. }
  33640. if (gradient >= 0.5) {
  33641. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33642. }
  33643. return (this.easeInCore(gradient * 2) * 0.5);
  33644. };
  33645. return EasingFunction;
  33646. }());
  33647. //Statics
  33648. EasingFunction._EASINGMODE_EASEIN = 0;
  33649. EasingFunction._EASINGMODE_EASEOUT = 1;
  33650. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33651. BABYLON.EasingFunction = EasingFunction;
  33652. var CircleEase = (function (_super) {
  33653. __extends(CircleEase, _super);
  33654. function CircleEase() {
  33655. return _super.apply(this, arguments) || this;
  33656. }
  33657. CircleEase.prototype.easeInCore = function (gradient) {
  33658. gradient = Math.max(0, Math.min(1, gradient));
  33659. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33660. };
  33661. return CircleEase;
  33662. }(EasingFunction));
  33663. BABYLON.CircleEase = CircleEase;
  33664. var BackEase = (function (_super) {
  33665. __extends(BackEase, _super);
  33666. function BackEase(amplitude) {
  33667. if (amplitude === void 0) { amplitude = 1; }
  33668. var _this = _super.call(this) || this;
  33669. _this.amplitude = amplitude;
  33670. return _this;
  33671. }
  33672. BackEase.prototype.easeInCore = function (gradient) {
  33673. var num = Math.max(0, this.amplitude);
  33674. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33675. };
  33676. return BackEase;
  33677. }(EasingFunction));
  33678. BABYLON.BackEase = BackEase;
  33679. var BounceEase = (function (_super) {
  33680. __extends(BounceEase, _super);
  33681. function BounceEase(bounces, bounciness) {
  33682. if (bounces === void 0) { bounces = 3; }
  33683. if (bounciness === void 0) { bounciness = 2; }
  33684. var _this = _super.call(this) || this;
  33685. _this.bounces = bounces;
  33686. _this.bounciness = bounciness;
  33687. return _this;
  33688. }
  33689. BounceEase.prototype.easeInCore = function (gradient) {
  33690. var y = Math.max(0.0, this.bounces);
  33691. var bounciness = this.bounciness;
  33692. if (bounciness <= 1.0) {
  33693. bounciness = 1.001;
  33694. }
  33695. var num9 = Math.pow(bounciness, y);
  33696. var num5 = 1.0 - bounciness;
  33697. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33698. var num15 = gradient * num4;
  33699. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33700. var num3 = Math.floor(num65);
  33701. var num13 = num3 + 1.0;
  33702. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33703. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33704. var num7 = (num8 + num12) * 0.5;
  33705. var num6 = gradient - num7;
  33706. var num2 = num7 - num8;
  33707. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33708. };
  33709. return BounceEase;
  33710. }(EasingFunction));
  33711. BABYLON.BounceEase = BounceEase;
  33712. var CubicEase = (function (_super) {
  33713. __extends(CubicEase, _super);
  33714. function CubicEase() {
  33715. return _super.apply(this, arguments) || this;
  33716. }
  33717. CubicEase.prototype.easeInCore = function (gradient) {
  33718. return (gradient * gradient * gradient);
  33719. };
  33720. return CubicEase;
  33721. }(EasingFunction));
  33722. BABYLON.CubicEase = CubicEase;
  33723. var ElasticEase = (function (_super) {
  33724. __extends(ElasticEase, _super);
  33725. function ElasticEase(oscillations, springiness) {
  33726. if (oscillations === void 0) { oscillations = 3; }
  33727. if (springiness === void 0) { springiness = 3; }
  33728. var _this = _super.call(this) || this;
  33729. _this.oscillations = oscillations;
  33730. _this.springiness = springiness;
  33731. return _this;
  33732. }
  33733. ElasticEase.prototype.easeInCore = function (gradient) {
  33734. var num2;
  33735. var num3 = Math.max(0.0, this.oscillations);
  33736. var num = Math.max(0.0, this.springiness);
  33737. if (num == 0) {
  33738. num2 = gradient;
  33739. }
  33740. else {
  33741. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33742. }
  33743. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33744. };
  33745. return ElasticEase;
  33746. }(EasingFunction));
  33747. BABYLON.ElasticEase = ElasticEase;
  33748. var ExponentialEase = (function (_super) {
  33749. __extends(ExponentialEase, _super);
  33750. function ExponentialEase(exponent) {
  33751. if (exponent === void 0) { exponent = 2; }
  33752. var _this = _super.call(this) || this;
  33753. _this.exponent = exponent;
  33754. return _this;
  33755. }
  33756. ExponentialEase.prototype.easeInCore = function (gradient) {
  33757. if (this.exponent <= 0) {
  33758. return gradient;
  33759. }
  33760. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33761. };
  33762. return ExponentialEase;
  33763. }(EasingFunction));
  33764. BABYLON.ExponentialEase = ExponentialEase;
  33765. var PowerEase = (function (_super) {
  33766. __extends(PowerEase, _super);
  33767. function PowerEase(power) {
  33768. if (power === void 0) { power = 2; }
  33769. var _this = _super.call(this) || this;
  33770. _this.power = power;
  33771. return _this;
  33772. }
  33773. PowerEase.prototype.easeInCore = function (gradient) {
  33774. var y = Math.max(0.0, this.power);
  33775. return Math.pow(gradient, y);
  33776. };
  33777. return PowerEase;
  33778. }(EasingFunction));
  33779. BABYLON.PowerEase = PowerEase;
  33780. var QuadraticEase = (function (_super) {
  33781. __extends(QuadraticEase, _super);
  33782. function QuadraticEase() {
  33783. return _super.apply(this, arguments) || this;
  33784. }
  33785. QuadraticEase.prototype.easeInCore = function (gradient) {
  33786. return (gradient * gradient);
  33787. };
  33788. return QuadraticEase;
  33789. }(EasingFunction));
  33790. BABYLON.QuadraticEase = QuadraticEase;
  33791. var QuarticEase = (function (_super) {
  33792. __extends(QuarticEase, _super);
  33793. function QuarticEase() {
  33794. return _super.apply(this, arguments) || this;
  33795. }
  33796. QuarticEase.prototype.easeInCore = function (gradient) {
  33797. return (gradient * gradient * gradient * gradient);
  33798. };
  33799. return QuarticEase;
  33800. }(EasingFunction));
  33801. BABYLON.QuarticEase = QuarticEase;
  33802. var QuinticEase = (function (_super) {
  33803. __extends(QuinticEase, _super);
  33804. function QuinticEase() {
  33805. return _super.apply(this, arguments) || this;
  33806. }
  33807. QuinticEase.prototype.easeInCore = function (gradient) {
  33808. return (gradient * gradient * gradient * gradient * gradient);
  33809. };
  33810. return QuinticEase;
  33811. }(EasingFunction));
  33812. BABYLON.QuinticEase = QuinticEase;
  33813. var SineEase = (function (_super) {
  33814. __extends(SineEase, _super);
  33815. function SineEase() {
  33816. return _super.apply(this, arguments) || this;
  33817. }
  33818. SineEase.prototype.easeInCore = function (gradient) {
  33819. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33820. };
  33821. return SineEase;
  33822. }(EasingFunction));
  33823. BABYLON.SineEase = SineEase;
  33824. var BezierCurveEase = (function (_super) {
  33825. __extends(BezierCurveEase, _super);
  33826. function BezierCurveEase(x1, y1, x2, y2) {
  33827. if (x1 === void 0) { x1 = 0; }
  33828. if (y1 === void 0) { y1 = 0; }
  33829. if (x2 === void 0) { x2 = 1; }
  33830. if (y2 === void 0) { y2 = 1; }
  33831. var _this = _super.call(this) || this;
  33832. _this.x1 = x1;
  33833. _this.y1 = y1;
  33834. _this.x2 = x2;
  33835. _this.y2 = y2;
  33836. return _this;
  33837. }
  33838. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33839. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33840. };
  33841. return BezierCurveEase;
  33842. }(EasingFunction));
  33843. BABYLON.BezierCurveEase = BezierCurveEase;
  33844. })(BABYLON || (BABYLON = {}));
  33845. //# sourceMappingURL=babylon.easing.js.map
  33846. /// <reference path="..\babylon.node.ts" />
  33847. var BABYLON;
  33848. (function (BABYLON) {
  33849. var Bone = (function (_super) {
  33850. __extends(Bone, _super);
  33851. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33852. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33853. _this.name = name;
  33854. _this.children = new Array();
  33855. _this.animations = new Array();
  33856. _this._worldTransform = new BABYLON.Matrix();
  33857. _this._absoluteTransform = new BABYLON.Matrix();
  33858. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33859. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33860. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33861. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33862. _this._scalingDeterminant = 1;
  33863. _this._skeleton = skeleton;
  33864. _this._localMatrix = matrix;
  33865. _this._baseMatrix = matrix.clone();
  33866. _this._restPose = restPose ? restPose : matrix.clone();
  33867. skeleton.bones.push(_this);
  33868. if (parentBone) {
  33869. _this._parent = parentBone;
  33870. parentBone.children.push(_this);
  33871. }
  33872. else {
  33873. _this._parent = null;
  33874. }
  33875. _this._updateDifferenceMatrix();
  33876. if (_this.getAbsoluteTransform().determinant() < 0) {
  33877. _this._scalingDeterminant *= -1;
  33878. }
  33879. return _this;
  33880. }
  33881. Object.defineProperty(Bone.prototype, "_matrix", {
  33882. get: function () {
  33883. return this._localMatrix;
  33884. },
  33885. set: function (val) {
  33886. if (this._localMatrix) {
  33887. this._localMatrix.copyFrom(val);
  33888. }
  33889. else {
  33890. this._localMatrix = val;
  33891. }
  33892. },
  33893. enumerable: true,
  33894. configurable: true
  33895. });
  33896. // Members
  33897. Bone.prototype.getParent = function () {
  33898. return this._parent;
  33899. };
  33900. Bone.prototype.getLocalMatrix = function () {
  33901. return this._localMatrix;
  33902. };
  33903. Bone.prototype.getBaseMatrix = function () {
  33904. return this._baseMatrix;
  33905. };
  33906. Bone.prototype.getRestPose = function () {
  33907. return this._restPose;
  33908. };
  33909. Bone.prototype.returnToRest = function () {
  33910. this.updateMatrix(this._restPose.clone());
  33911. };
  33912. Bone.prototype.getWorldMatrix = function () {
  33913. return this._worldTransform;
  33914. };
  33915. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33916. return this._invertedAbsoluteTransform;
  33917. };
  33918. Bone.prototype.getAbsoluteTransform = function () {
  33919. return this._absoluteTransform;
  33920. };
  33921. // Methods
  33922. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33923. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33924. this._baseMatrix = matrix.clone();
  33925. this._localMatrix = matrix.clone();
  33926. this._skeleton._markAsDirty();
  33927. if (updateDifferenceMatrix) {
  33928. this._updateDifferenceMatrix();
  33929. }
  33930. };
  33931. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33932. if (!rootMatrix) {
  33933. rootMatrix = this._baseMatrix;
  33934. }
  33935. if (this._parent) {
  33936. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33937. }
  33938. else {
  33939. this._absoluteTransform.copyFrom(rootMatrix);
  33940. }
  33941. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33942. for (var index = 0; index < this.children.length; index++) {
  33943. this.children[index]._updateDifferenceMatrix();
  33944. }
  33945. };
  33946. Bone.prototype.markAsDirty = function () {
  33947. this._currentRenderId++;
  33948. this._skeleton._markAsDirty();
  33949. };
  33950. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33951. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33952. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33953. // all animation may be coming from a library skeleton, so may need to create animation
  33954. if (this.animations.length === 0) {
  33955. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33956. this.animations[0].setKeys([]);
  33957. }
  33958. // get animation info / verify there is such a range from the source bone
  33959. var sourceRange = source.animations[0].getRange(rangeName);
  33960. if (!sourceRange) {
  33961. return false;
  33962. }
  33963. var from = sourceRange.from;
  33964. var to = sourceRange.to;
  33965. var sourceKeys = source.animations[0].getKeys();
  33966. // rescaling prep
  33967. var sourceBoneLength = source.length;
  33968. var sourceParent = source.getParent();
  33969. var parent = this.getParent();
  33970. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33971. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33972. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33973. var destKeys = this.animations[0].getKeys();
  33974. // loop vars declaration
  33975. var orig;
  33976. var origTranslation;
  33977. var mat;
  33978. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33979. orig = sourceKeys[key];
  33980. if (orig.frame >= from && orig.frame <= to) {
  33981. if (rescaleAsRequired) {
  33982. mat = orig.value.clone();
  33983. // scale based on parent ratio, when bone has parent
  33984. if (parentScalingReqd) {
  33985. origTranslation = mat.getTranslation();
  33986. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33987. }
  33988. else if (dimensionsScalingReqd) {
  33989. origTranslation = mat.getTranslation();
  33990. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33991. }
  33992. else {
  33993. mat = orig.value;
  33994. }
  33995. }
  33996. else {
  33997. mat = orig.value;
  33998. }
  33999. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  34000. }
  34001. }
  34002. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  34003. return true;
  34004. };
  34005. /**
  34006. * Translate the bone in local or world space.
  34007. * @param vec The amount to translate the bone.
  34008. * @param space The space that the translation is in.
  34009. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34010. */
  34011. Bone.prototype.translate = function (vec, space, mesh) {
  34012. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34013. var lm = this.getLocalMatrix();
  34014. if (space == BABYLON.Space.LOCAL) {
  34015. lm.m[12] += vec.x;
  34016. lm.m[13] += vec.y;
  34017. lm.m[14] += vec.z;
  34018. }
  34019. else {
  34020. var wm;
  34021. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34022. if (mesh) {
  34023. wm = mesh.getWorldMatrix();
  34024. }
  34025. this._skeleton.computeAbsoluteTransforms();
  34026. var tmat = BABYLON.Tmp.Matrix[0];
  34027. var tvec = BABYLON.Tmp.Vector3[0];
  34028. if (mesh) {
  34029. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34030. tmat.multiplyToRef(wm, tmat);
  34031. }
  34032. else {
  34033. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34034. }
  34035. tmat.m[12] = 0;
  34036. tmat.m[13] = 0;
  34037. tmat.m[14] = 0;
  34038. tmat.invert();
  34039. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  34040. lm.m[12] += tvec.x;
  34041. lm.m[13] += tvec.y;
  34042. lm.m[14] += tvec.z;
  34043. }
  34044. this.markAsDirty();
  34045. };
  34046. /**
  34047. * Set the postion of the bone in local or world space.
  34048. * @param position The position to set the bone.
  34049. * @param space The space that the position is in.
  34050. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34051. */
  34052. Bone.prototype.setPosition = function (position, space, mesh) {
  34053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34054. var lm = this.getLocalMatrix();
  34055. if (space == BABYLON.Space.LOCAL) {
  34056. lm.m[12] = position.x;
  34057. lm.m[13] = position.y;
  34058. lm.m[14] = position.z;
  34059. }
  34060. else {
  34061. var wm;
  34062. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34063. if (mesh) {
  34064. wm = mesh.getWorldMatrix();
  34065. }
  34066. this._skeleton.computeAbsoluteTransforms();
  34067. var tmat = BABYLON.Tmp.Matrix[0];
  34068. var vec = BABYLON.Tmp.Vector3[0];
  34069. if (mesh) {
  34070. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34071. tmat.multiplyToRef(wm, tmat);
  34072. }
  34073. else {
  34074. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34075. }
  34076. tmat.invert();
  34077. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  34078. lm.m[12] = vec.x;
  34079. lm.m[13] = vec.y;
  34080. lm.m[14] = vec.z;
  34081. }
  34082. this.markAsDirty();
  34083. };
  34084. /**
  34085. * Set the absolute postion of the bone (world space).
  34086. * @param position The position to set the bone.
  34087. * @param mesh The mesh that this bone is attached to.
  34088. */
  34089. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  34090. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  34091. };
  34092. /**
  34093. * Set the scale of the bone on the x, y and z axes.
  34094. * @param x The scale of the bone on the x axis.
  34095. * @param x The scale of the bone on the y axis.
  34096. * @param z The scale of the bone on the z axis.
  34097. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34098. */
  34099. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  34100. if (scaleChildren === void 0) { scaleChildren = false; }
  34101. if (this.animations[0] && !this.animations[0].isStopped()) {
  34102. if (!scaleChildren) {
  34103. this._negateScaleChildren.x = 1 / x;
  34104. this._negateScaleChildren.y = 1 / y;
  34105. this._negateScaleChildren.z = 1 / z;
  34106. }
  34107. this._syncScaleVector();
  34108. }
  34109. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  34110. };
  34111. /**
  34112. * Scale the bone on the x, y and z axes.
  34113. * @param x The amount to scale the bone on the x axis.
  34114. * @param x The amount to scale the bone on the y axis.
  34115. * @param z The amount to scale the bone on the z axis.
  34116. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34117. */
  34118. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  34119. if (scaleChildren === void 0) { scaleChildren = false; }
  34120. var locMat = this.getLocalMatrix();
  34121. var origLocMat = BABYLON.Tmp.Matrix[0];
  34122. origLocMat.copyFrom(locMat);
  34123. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  34124. origLocMatInv.copyFrom(origLocMat);
  34125. origLocMatInv.invert();
  34126. var scaleMat = BABYLON.Tmp.Matrix[2];
  34127. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  34128. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  34129. this._scaleVector.x *= x;
  34130. this._scaleVector.y *= y;
  34131. this._scaleVector.z *= z;
  34132. locMat.multiplyToRef(origLocMatInv, locMat);
  34133. locMat.multiplyToRef(scaleMat, locMat);
  34134. locMat.multiplyToRef(origLocMat, locMat);
  34135. var parent = this.getParent();
  34136. if (parent) {
  34137. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  34138. }
  34139. else {
  34140. this.getAbsoluteTransform().copyFrom(locMat);
  34141. }
  34142. var len = this.children.length;
  34143. scaleMat.invert();
  34144. for (var i = 0; i < len; i++) {
  34145. var child = this.children[i];
  34146. var cm = child.getLocalMatrix();
  34147. cm.multiplyToRef(scaleMat, cm);
  34148. var lm = child.getLocalMatrix();
  34149. lm.m[12] *= x;
  34150. lm.m[13] *= y;
  34151. lm.m[14] *= z;
  34152. }
  34153. this.computeAbsoluteTransforms();
  34154. if (scaleChildren) {
  34155. for (var i = 0; i < len; i++) {
  34156. this.children[i].scale(x, y, z, scaleChildren);
  34157. }
  34158. }
  34159. this.markAsDirty();
  34160. };
  34161. /**
  34162. * Set the yaw, pitch, and roll of the bone in local or world space.
  34163. * @param yaw The rotation of the bone on the y axis.
  34164. * @param pitch The rotation of the bone on the x axis.
  34165. * @param roll The rotation of the bone on the z axis.
  34166. * @param space The space that the axes of rotation are in.
  34167. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34168. */
  34169. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  34170. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34171. var rotMat = BABYLON.Tmp.Matrix[0];
  34172. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  34173. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34174. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34175. rotMatInv.multiplyToRef(rotMat, rotMat);
  34176. this._rotateWithMatrix(rotMat, space, mesh);
  34177. };
  34178. /**
  34179. * Rotate the bone on an axis in local or world space.
  34180. * @param axis The axis to rotate the bone on.
  34181. * @param amount The amount to rotate the bone.
  34182. * @param space The space that the axis is in.
  34183. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34184. */
  34185. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  34186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34187. var rmat = BABYLON.Tmp.Matrix[0];
  34188. rmat.m[12] = 0;
  34189. rmat.m[13] = 0;
  34190. rmat.m[14] = 0;
  34191. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  34192. this._rotateWithMatrix(rmat, space, mesh);
  34193. };
  34194. /**
  34195. * Set the rotation of the bone to a particular axis angle in local or world space.
  34196. * @param axis The axis to rotate the bone on.
  34197. * @param angle The angle that the bone should be rotated to.
  34198. * @param space The space that the axis is in.
  34199. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34200. */
  34201. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  34202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34203. var rotMat = BABYLON.Tmp.Matrix[0];
  34204. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  34205. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34206. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34207. rotMatInv.multiplyToRef(rotMat, rotMat);
  34208. this._rotateWithMatrix(rotMat, space, mesh);
  34209. };
  34210. /**
  34211. * Set the euler rotation of the bone in local of world space.
  34212. * @param rotation The euler rotation that the bone should be set to.
  34213. * @param space The space that the rotation is in.
  34214. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34215. */
  34216. Bone.prototype.setRotation = function (rotation, space, mesh) {
  34217. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34218. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  34219. };
  34220. /**
  34221. * Set the quaternion rotation of the bone in local of world space.
  34222. * @param quat The quaternion rotation that the bone should be set to.
  34223. * @param space The space that the rotation is in.
  34224. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34225. */
  34226. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  34227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34228. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34229. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34230. var rotMat = BABYLON.Tmp.Matrix[1];
  34231. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  34232. rotMatInv.multiplyToRef(rotMat, rotMat);
  34233. this._rotateWithMatrix(rotMat, space, mesh);
  34234. };
  34235. /**
  34236. * Set the rotation matrix of the bone in local of world space.
  34237. * @param rotMat The rotation matrix that the bone should be set to.
  34238. * @param space The space that the rotation is in.
  34239. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34240. */
  34241. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  34242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34243. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34244. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34245. var rotMat2 = BABYLON.Tmp.Matrix[1];
  34246. rotMat2.copyFrom(rotMat);
  34247. rotMatInv.multiplyToRef(rotMat, rotMat2);
  34248. this._rotateWithMatrix(rotMat2, space, mesh);
  34249. };
  34250. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  34251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34252. var lmat = this.getLocalMatrix();
  34253. var lx = lmat.m[12];
  34254. var ly = lmat.m[13];
  34255. var lz = lmat.m[14];
  34256. var parent = this.getParent();
  34257. var parentScale = BABYLON.Tmp.Matrix[3];
  34258. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  34259. if (parent) {
  34260. if (space == BABYLON.Space.WORLD) {
  34261. if (mesh) {
  34262. parentScale.copyFrom(mesh.getWorldMatrix());
  34263. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  34264. }
  34265. else {
  34266. parentScale.copyFrom(parent.getAbsoluteTransform());
  34267. }
  34268. }
  34269. else {
  34270. parentScale = parent._scaleMatrix;
  34271. }
  34272. parentScaleInv.copyFrom(parentScale);
  34273. parentScaleInv.invert();
  34274. lmat.multiplyToRef(parentScale, lmat);
  34275. lmat.multiplyToRef(rmat, lmat);
  34276. lmat.multiplyToRef(parentScaleInv, lmat);
  34277. }
  34278. else {
  34279. if (space == BABYLON.Space.WORLD && mesh) {
  34280. parentScale.copyFrom(mesh.getWorldMatrix());
  34281. parentScaleInv.copyFrom(parentScale);
  34282. parentScaleInv.invert();
  34283. lmat.multiplyToRef(parentScale, lmat);
  34284. lmat.multiplyToRef(rmat, lmat);
  34285. lmat.multiplyToRef(parentScaleInv, lmat);
  34286. }
  34287. else {
  34288. lmat.multiplyToRef(rmat, lmat);
  34289. }
  34290. }
  34291. lmat.m[12] = lx;
  34292. lmat.m[13] = ly;
  34293. lmat.m[14] = lz;
  34294. this.computeAbsoluteTransforms();
  34295. this.markAsDirty();
  34296. };
  34297. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  34298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34299. if (space == BABYLON.Space.WORLD) {
  34300. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34301. scaleMatrix.copyFrom(this._scaleMatrix);
  34302. rotMatInv.copyFrom(this.getAbsoluteTransform());
  34303. if (mesh) {
  34304. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  34305. var meshScale = BABYLON.Tmp.Matrix[3];
  34306. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  34307. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  34308. }
  34309. rotMatInv.invert();
  34310. scaleMatrix.m[0] *= this._scalingDeterminant;
  34311. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34312. }
  34313. else {
  34314. rotMatInv.copyFrom(this.getLocalMatrix());
  34315. rotMatInv.invert();
  34316. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34317. scaleMatrix.copyFrom(this._scaleMatrix);
  34318. if (this._parent) {
  34319. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  34320. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  34321. pscaleMatrix.invert();
  34322. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  34323. }
  34324. else {
  34325. scaleMatrix.m[0] *= this._scalingDeterminant;
  34326. }
  34327. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34328. }
  34329. };
  34330. /**
  34331. * Get the scale of the bone
  34332. * @returns the scale of the bone
  34333. */
  34334. Bone.prototype.getScale = function () {
  34335. return this._scaleVector.clone();
  34336. };
  34337. /**
  34338. * Copy the scale of the bone to a vector3.
  34339. * @param result The vector3 to copy the scale to
  34340. */
  34341. Bone.prototype.getScaleToRef = function (result) {
  34342. result.copyFrom(this._scaleVector);
  34343. };
  34344. /**
  34345. * Get the position of the bone in local or world space.
  34346. * @param space The space that the returned position is in.
  34347. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34348. * @returns The position of the bone
  34349. */
  34350. Bone.prototype.getPosition = function (space, mesh) {
  34351. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34352. var pos = BABYLON.Vector3.Zero();
  34353. this.getPositionToRef(space, mesh, pos);
  34354. return pos;
  34355. };
  34356. /**
  34357. * Copy the position of the bone to a vector3 in local or world space.
  34358. * @param space The space that the returned position is in.
  34359. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34360. * @param result The vector3 to copy the position to.
  34361. */
  34362. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  34363. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34364. if (space == BABYLON.Space.LOCAL) {
  34365. var lm = this.getLocalMatrix();
  34366. result.x = lm.m[12];
  34367. result.y = lm.m[13];
  34368. result.z = lm.m[14];
  34369. }
  34370. else {
  34371. var wm;
  34372. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34373. if (mesh) {
  34374. wm = mesh.getWorldMatrix();
  34375. }
  34376. this._skeleton.computeAbsoluteTransforms();
  34377. var tmat = BABYLON.Tmp.Matrix[0];
  34378. if (mesh) {
  34379. tmat.copyFrom(this.getAbsoluteTransform());
  34380. tmat.multiplyToRef(wm, tmat);
  34381. }
  34382. else {
  34383. tmat = this.getAbsoluteTransform();
  34384. }
  34385. result.x = tmat.m[12];
  34386. result.y = tmat.m[13];
  34387. result.z = tmat.m[14];
  34388. }
  34389. };
  34390. /**
  34391. * Get the absolute position of the bone (world space).
  34392. * @param mesh The mesh that this bone is attached to.
  34393. * @returns The absolute position of the bone
  34394. */
  34395. Bone.prototype.getAbsolutePosition = function (mesh) {
  34396. var pos = BABYLON.Vector3.Zero();
  34397. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  34398. return pos;
  34399. };
  34400. /**
  34401. * Copy the absolute position of the bone (world space) to the result param.
  34402. * @param mesh The mesh that this bone is attached to.
  34403. * @param result The vector3 to copy the absolute position to.
  34404. */
  34405. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  34406. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  34407. };
  34408. /**
  34409. * Compute the absolute transforms of this bone and its children.
  34410. */
  34411. Bone.prototype.computeAbsoluteTransforms = function () {
  34412. if (this._parent) {
  34413. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  34414. }
  34415. else {
  34416. this._absoluteTransform.copyFrom(this._localMatrix);
  34417. var poseMatrix = this._skeleton.getPoseMatrix();
  34418. if (poseMatrix) {
  34419. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  34420. }
  34421. }
  34422. var children = this.children;
  34423. var len = children.length;
  34424. for (var i = 0; i < len; i++) {
  34425. children[i].computeAbsoluteTransforms();
  34426. }
  34427. };
  34428. Bone.prototype._syncScaleVector = function () {
  34429. var lm = this.getLocalMatrix();
  34430. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  34431. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  34432. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  34433. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  34434. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  34435. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  34436. this._scaleVector.x = xs * Math.sqrt(xsq);
  34437. this._scaleVector.y = ys * Math.sqrt(ysq);
  34438. this._scaleVector.z = zs * Math.sqrt(zsq);
  34439. if (this._parent) {
  34440. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  34441. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  34442. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  34443. }
  34444. 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);
  34445. };
  34446. /**
  34447. * Get the world direction from an axis that is in the local space of the bone.
  34448. * @param localAxis The local direction that is used to compute the world direction.
  34449. * @param mesh The mesh that this bone is attached to.
  34450. * @returns The world direction
  34451. */
  34452. Bone.prototype.getDirection = function (localAxis, mesh) {
  34453. var result = BABYLON.Vector3.Zero();
  34454. this.getDirectionToRef(localAxis, mesh, result);
  34455. return result;
  34456. };
  34457. /**
  34458. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  34459. * @param localAxis The local direction that is used to compute the world direction.
  34460. * @param mesh The mesh that this bone is attached to.
  34461. * @param result The vector3 that the world direction will be copied to.
  34462. */
  34463. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  34464. var wm;
  34465. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34466. if (mesh) {
  34467. wm = mesh.getWorldMatrix();
  34468. }
  34469. this._skeleton.computeAbsoluteTransforms();
  34470. var mat = BABYLON.Tmp.Matrix[0];
  34471. mat.copyFrom(this.getAbsoluteTransform());
  34472. if (mesh) {
  34473. mat.multiplyToRef(wm, mat);
  34474. }
  34475. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  34476. result.normalize();
  34477. };
  34478. /**
  34479. * Get the euler rotation of the bone in local or world space.
  34480. * @param space The space that the rotation should be in.
  34481. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34482. * @returns The euler rotation
  34483. */
  34484. Bone.prototype.getRotation = function (space, mesh) {
  34485. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34486. var result = BABYLON.Vector3.Zero();
  34487. this.getRotationToRef(space, mesh, result);
  34488. return result;
  34489. };
  34490. /**
  34491. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  34492. * @param space The space that the rotation should be in.
  34493. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34494. * @param result The vector3 that the rotation should be copied to.
  34495. */
  34496. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  34497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34498. var quat = BABYLON.Tmp.Quaternion[0];
  34499. this.getRotationQuaternionToRef(space, mesh, quat);
  34500. quat.toEulerAnglesToRef(result);
  34501. };
  34502. /**
  34503. * Get the quaternion rotation of the bone in either local or world space.
  34504. * @param space The space that the rotation should be in.
  34505. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34506. * @returns The quaternion rotation
  34507. */
  34508. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  34509. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34510. var result = BABYLON.Quaternion.Identity();
  34511. this.getRotationQuaternionToRef(space, mesh, result);
  34512. return result;
  34513. };
  34514. /**
  34515. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  34516. * @param space The space that the rotation should be in.
  34517. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34518. * @param result The quaternion that the rotation should be copied to.
  34519. */
  34520. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  34521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34522. if (space == BABYLON.Space.LOCAL) {
  34523. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34524. }
  34525. else {
  34526. var mat = BABYLON.Tmp.Matrix[0];
  34527. var amat = this.getAbsoluteTransform();
  34528. if (mesh) {
  34529. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34530. }
  34531. else {
  34532. mat.copyFrom(amat);
  34533. }
  34534. mat.m[0] *= this._scalingDeterminant;
  34535. mat.m[1] *= this._scalingDeterminant;
  34536. mat.m[2] *= this._scalingDeterminant;
  34537. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34538. }
  34539. };
  34540. /**
  34541. * Get the rotation matrix of the bone in local or world space.
  34542. * @param space The space that the rotation should be in.
  34543. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34544. * @returns The rotation matrix
  34545. */
  34546. Bone.prototype.getRotationMatrix = function (space, mesh) {
  34547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34548. var result = BABYLON.Matrix.Identity();
  34549. this.getRotationMatrixToRef(space, mesh, result);
  34550. return result;
  34551. };
  34552. /**
  34553. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  34554. * @param space The space that the rotation should be in.
  34555. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34556. * @param result The quaternion that the rotation should be copied to.
  34557. */
  34558. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  34559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34560. if (space == BABYLON.Space.LOCAL) {
  34561. this.getLocalMatrix().getRotationMatrixToRef(result);
  34562. }
  34563. else {
  34564. var mat = BABYLON.Tmp.Matrix[0];
  34565. var amat = this.getAbsoluteTransform();
  34566. if (mesh) {
  34567. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34568. }
  34569. else {
  34570. mat.copyFrom(amat);
  34571. }
  34572. mat.m[0] *= this._scalingDeterminant;
  34573. mat.m[1] *= this._scalingDeterminant;
  34574. mat.m[2] *= this._scalingDeterminant;
  34575. mat.getRotationMatrixToRef(result);
  34576. }
  34577. };
  34578. /**
  34579. * Get the world position of a point that is in the local space of the bone.
  34580. * @param position The local position
  34581. * @param mesh The mesh that this bone is attached to.
  34582. * @returns The world position
  34583. */
  34584. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  34585. var result = BABYLON.Vector3.Zero();
  34586. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  34587. return result;
  34588. };
  34589. /**
  34590. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  34591. * @param position The local position
  34592. * @param mesh The mesh that this bone is attached to.
  34593. * @param result The vector3 that the world position should be copied to.
  34594. */
  34595. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  34596. var wm;
  34597. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34598. if (mesh) {
  34599. wm = mesh.getWorldMatrix();
  34600. }
  34601. this._skeleton.computeAbsoluteTransforms();
  34602. var tmat = BABYLON.Tmp.Matrix[0];
  34603. if (mesh) {
  34604. tmat.copyFrom(this.getAbsoluteTransform());
  34605. tmat.multiplyToRef(wm, tmat);
  34606. }
  34607. else {
  34608. tmat = this.getAbsoluteTransform();
  34609. }
  34610. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34611. };
  34612. /**
  34613. * Get the local position of a point that is in world space.
  34614. * @param position The world position
  34615. * @param mesh The mesh that this bone is attached to.
  34616. * @returns The local position
  34617. */
  34618. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  34619. var result = BABYLON.Vector3.Zero();
  34620. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  34621. return result;
  34622. };
  34623. /**
  34624. * Get the local position of a point that is in world space and copy it to the result param.
  34625. * @param position The world position
  34626. * @param mesh The mesh that this bone is attached to.
  34627. * @param result The vector3 that the local position should be copied to.
  34628. */
  34629. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  34630. var wm;
  34631. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34632. if (mesh) {
  34633. wm = mesh.getWorldMatrix();
  34634. }
  34635. this._skeleton.computeAbsoluteTransforms();
  34636. var tmat = BABYLON.Tmp.Matrix[0];
  34637. tmat.copyFrom(this.getAbsoluteTransform());
  34638. if (mesh) {
  34639. tmat.multiplyToRef(wm, tmat);
  34640. }
  34641. tmat.invert();
  34642. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34643. };
  34644. return Bone;
  34645. }(BABYLON.Node));
  34646. BABYLON.Bone = Bone;
  34647. })(BABYLON || (BABYLON = {}));
  34648. //# sourceMappingURL=babylon.bone.js.map
  34649. var BABYLON;
  34650. (function (BABYLON) {
  34651. var BoneIKController = (function () {
  34652. function BoneIKController(mesh, bone, options) {
  34653. this.targetPosition = BABYLON.Vector3.Zero();
  34654. this.poleTargetPosition = BABYLON.Vector3.Zero();
  34655. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  34656. this.poleAngle = 0;
  34657. this.slerpAmount = 1;
  34658. this._bone1Quat = BABYLON.Quaternion.Identity();
  34659. this._bone1Mat = BABYLON.Matrix.Identity();
  34660. this._bone2Ang = Math.PI;
  34661. this._maxAngle = Math.PI;
  34662. this._rightHandedSystem = false;
  34663. this._bendAxis = BABYLON.Vector3.Right();
  34664. this._slerping = false;
  34665. this._adjustRoll = 0;
  34666. this._bone2 = bone;
  34667. this._bone1 = bone.getParent();
  34668. this.mesh = mesh;
  34669. var bonePos = bone.getPosition();
  34670. if (bone.getAbsoluteTransform().determinant() > 0) {
  34671. this._rightHandedSystem = true;
  34672. this._bendAxis.x = 0;
  34673. this._bendAxis.y = 0;
  34674. this._bendAxis.z = -1;
  34675. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  34676. this._adjustRoll = Math.PI * .5;
  34677. this._bendAxis.z = 1;
  34678. }
  34679. }
  34680. if (this._bone1.length) {
  34681. var boneScale1 = this._bone1.getScale();
  34682. var boneScale2 = this._bone2.getScale();
  34683. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  34684. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  34685. }
  34686. else if (this._bone1.children[0]) {
  34687. mesh.computeWorldMatrix(true);
  34688. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  34689. var pos2 = this._bone2.getAbsolutePosition(mesh);
  34690. var pos3 = this._bone1.getAbsolutePosition(mesh);
  34691. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  34692. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  34693. }
  34694. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  34695. this.maxAngle = Math.PI;
  34696. if (options) {
  34697. if (options.targetMesh) {
  34698. this.targetMesh = options.targetMesh;
  34699. this.targetMesh.computeWorldMatrix(true);
  34700. }
  34701. if (options.poleTargetMesh) {
  34702. this.poleTargetMesh = options.poleTargetMesh;
  34703. this.poleTargetMesh.computeWorldMatrix(true);
  34704. }
  34705. else if (options.poleTargetBone) {
  34706. this.poleTargetBone = options.poleTargetBone;
  34707. }
  34708. else if (this._bone1.getParent()) {
  34709. this.poleTargetBone = this._bone1.getParent();
  34710. }
  34711. if (options.poleTargetLocalOffset) {
  34712. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  34713. }
  34714. if (options.poleAngle) {
  34715. this.poleAngle = options.poleAngle;
  34716. }
  34717. if (options.bendAxis) {
  34718. this._bendAxis.copyFrom(options.bendAxis);
  34719. }
  34720. if (options.maxAngle) {
  34721. this.maxAngle = options.maxAngle;
  34722. }
  34723. if (options.slerpAmount) {
  34724. this.slerpAmount = options.slerpAmount;
  34725. }
  34726. }
  34727. }
  34728. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  34729. get: function () {
  34730. return this._maxAngle;
  34731. },
  34732. set: function (value) {
  34733. this._setMaxAngle(value);
  34734. },
  34735. enumerable: true,
  34736. configurable: true
  34737. });
  34738. BoneIKController.prototype._setMaxAngle = function (ang) {
  34739. if (ang < 0) {
  34740. ang = 0;
  34741. }
  34742. if (ang > Math.PI || ang == undefined) {
  34743. ang = Math.PI;
  34744. }
  34745. this._maxAngle = ang;
  34746. var a = this._bone1Length;
  34747. var b = this._bone2Length;
  34748. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  34749. };
  34750. BoneIKController.prototype.update = function () {
  34751. var bone1 = this._bone1;
  34752. var target = this.targetPosition;
  34753. var poleTarget = this.poleTargetPosition;
  34754. var mat1 = BoneIKController._tmpMats[0];
  34755. var mat2 = BoneIKController._tmpMats[1];
  34756. if (this.targetMesh) {
  34757. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34758. }
  34759. if (this.poleTargetBone) {
  34760. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34761. }
  34762. else if (this.poleTargetMesh) {
  34763. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34764. }
  34765. var bonePos = BoneIKController._tmpVecs[0];
  34766. var zaxis = BoneIKController._tmpVecs[1];
  34767. var xaxis = BoneIKController._tmpVecs[2];
  34768. var yaxis = BoneIKController._tmpVecs[3];
  34769. var upAxis = BoneIKController._tmpVecs[4];
  34770. var _tmpQuat = BoneIKController._tmpQuat;
  34771. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34772. poleTarget.subtractToRef(bonePos, upAxis);
  34773. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34774. upAxis.y = 1;
  34775. }
  34776. else {
  34777. upAxis.normalize();
  34778. }
  34779. target.subtractToRef(bonePos, yaxis);
  34780. yaxis.normalize();
  34781. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34782. zaxis.normalize();
  34783. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34784. xaxis.normalize();
  34785. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34786. var a = this._bone1Length;
  34787. var b = this._bone2Length;
  34788. var c = BABYLON.Vector3.Distance(bonePos, target);
  34789. if (this._maxReach > 0) {
  34790. c = Math.min(this._maxReach, c);
  34791. }
  34792. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34793. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34794. if (acosa > 1) {
  34795. acosa = 1;
  34796. }
  34797. if (acosb > 1) {
  34798. acosb = 1;
  34799. }
  34800. if (acosa < -1) {
  34801. acosa = -1;
  34802. }
  34803. if (acosb < -1) {
  34804. acosb = -1;
  34805. }
  34806. var angA = Math.acos(acosa);
  34807. var angB = Math.acos(acosb);
  34808. var angC = -angA - angB;
  34809. if (this._rightHandedSystem) {
  34810. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34811. mat2.multiplyToRef(mat1, mat1);
  34812. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34813. mat2.multiplyToRef(mat1, mat1);
  34814. }
  34815. else {
  34816. var _tmpVec = BoneIKController._tmpVecs[5];
  34817. _tmpVec.copyFrom(this._bendAxis);
  34818. _tmpVec.x *= -1;
  34819. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  34820. mat2.multiplyToRef(mat1, mat1);
  34821. }
  34822. if (this.poleAngle) {
  34823. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34824. mat1.multiplyToRef(mat2, mat1);
  34825. }
  34826. if (this.slerpAmount < 1) {
  34827. if (!this._slerping) {
  34828. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34829. }
  34830. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  34831. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  34832. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34833. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34834. this._slerping = true;
  34835. }
  34836. else {
  34837. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34838. this._bone1Mat.copyFrom(mat1);
  34839. this._slerping = false;
  34840. }
  34841. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34842. this._bone2Ang = angC;
  34843. };
  34844. return BoneIKController;
  34845. }());
  34846. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  34847. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  34848. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  34849. BABYLON.BoneIKController = BoneIKController;
  34850. })(BABYLON || (BABYLON = {}));
  34851. //# sourceMappingURL=babylon.boneIKController.js.map
  34852. var BABYLON;
  34853. (function (BABYLON) {
  34854. var BoneLookController = (function () {
  34855. /**
  34856. * Create a BoneLookController
  34857. * @param mesh the mesh that the bone belongs to
  34858. * @param bone the bone that will be looking to the target
  34859. * @param target the target Vector3 to look at
  34860. * @param settings optional settings:
  34861. * - maxYaw: the maximum angle the bone will yaw to
  34862. * - minYaw: the minimum angle the bone will yaw to
  34863. * - maxPitch: the maximum angle the bone will pitch to
  34864. * - minPitch: the minimum angle the bone will yaw to
  34865. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  34866. * - upAxis: the up axis of the coordinate system
  34867. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34868. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  34869. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  34870. * - adjustYaw: used to make an adjustment to the yaw of the bone
  34871. * - adjustPitch: used to make an adjustment to the pitch of the bone
  34872. * - adjustRoll: used to make an adjustment to the roll of the bone
  34873. **/
  34874. function BoneLookController(mesh, bone, target, options) {
  34875. /**
  34876. * The up axis of the coordinate system that is used when the bone is rotated.
  34877. */
  34878. this.upAxis = BABYLON.Vector3.Up();
  34879. /**
  34880. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34881. */
  34882. this.upAxisSpace = BABYLON.Space.LOCAL;
  34883. /**
  34884. * Used to make an adjustment to the yaw of the bone.
  34885. */
  34886. this.adjustYaw = 0;
  34887. /**
  34888. * Used to make an adjustment to the pitch of the bone.
  34889. */
  34890. this.adjustPitch = 0;
  34891. /**
  34892. * Used to make an adjustment to the roll of the bone.
  34893. */
  34894. this.adjustRoll = 0;
  34895. /**
  34896. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  34897. */
  34898. this.slerpAmount = 1;
  34899. this._boneQuat = BABYLON.Quaternion.Identity();
  34900. this._slerping = false;
  34901. this._firstFrameSkipped = false;
  34902. this._fowardAxis = BABYLON.Vector3.Forward();
  34903. this.mesh = mesh;
  34904. this.bone = bone;
  34905. this.target = target;
  34906. if (options) {
  34907. if (options.adjustYaw) {
  34908. this.adjustYaw = options.adjustYaw;
  34909. }
  34910. if (options.adjustPitch) {
  34911. this.adjustPitch = options.adjustPitch;
  34912. }
  34913. if (options.adjustRoll) {
  34914. this.adjustRoll = options.adjustRoll;
  34915. }
  34916. if (options.maxYaw != null) {
  34917. this.maxYaw = options.maxYaw;
  34918. }
  34919. else {
  34920. this.maxYaw = Math.PI;
  34921. }
  34922. if (options.minYaw != null) {
  34923. this.minYaw = options.minYaw;
  34924. }
  34925. else {
  34926. this.minYaw = -Math.PI;
  34927. }
  34928. if (options.maxPitch != null) {
  34929. this.maxPitch = options.maxPitch;
  34930. }
  34931. else {
  34932. this.maxPitch = Math.PI;
  34933. }
  34934. if (options.minPitch != null) {
  34935. this.minPitch = options.minPitch;
  34936. }
  34937. else {
  34938. this.minPitch = -Math.PI;
  34939. }
  34940. if (options.slerpAmount != null) {
  34941. this.slerpAmount = options.slerpAmount;
  34942. }
  34943. if (options.upAxis != null) {
  34944. this.upAxis = options.upAxis;
  34945. }
  34946. if (options.upAxisSpace != null) {
  34947. this.upAxisSpace = options.upAxisSpace;
  34948. }
  34949. if (options.yawAxis != null || options.pitchAxis != null) {
  34950. var newYawAxis = BABYLON.Axis.Y;
  34951. var newPitchAxis = BABYLON.Axis.X;
  34952. if (options.yawAxis != null) {
  34953. newYawAxis = options.yawAxis.clone();
  34954. newYawAxis.normalize();
  34955. }
  34956. if (options.pitchAxis != null) {
  34957. newPitchAxis = options.pitchAxis.clone();
  34958. newPitchAxis.normalize();
  34959. }
  34960. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  34961. this._transformYawPitch = BABYLON.Matrix.Identity();
  34962. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  34963. this._transformYawPitchInv = this._transformYawPitch.clone();
  34964. this._transformYawPitch.invert();
  34965. }
  34966. }
  34967. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  34968. this.upAxisSpace = BABYLON.Space.LOCAL;
  34969. }
  34970. }
  34971. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  34972. /**
  34973. * Get/set the minimum yaw angle that the bone can look to.
  34974. */
  34975. get: function () {
  34976. return this._minYaw;
  34977. },
  34978. set: function (value) {
  34979. this._minYaw = value;
  34980. this._minYawSin = Math.sin(value);
  34981. this._minYawCos = Math.cos(value);
  34982. if (this._maxYaw != null) {
  34983. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34984. this._yawRange = this._maxYaw - this._minYaw;
  34985. }
  34986. },
  34987. enumerable: true,
  34988. configurable: true
  34989. });
  34990. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  34991. /**
  34992. * Get/set the maximum yaw angle that the bone can look to.
  34993. */
  34994. get: function () {
  34995. return this._maxYaw;
  34996. },
  34997. set: function (value) {
  34998. this._maxYaw = value;
  34999. this._maxYawSin = Math.sin(value);
  35000. this._maxYawCos = Math.cos(value);
  35001. if (this._minYaw != null) {
  35002. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  35003. this._yawRange = this._maxYaw - this._minYaw;
  35004. }
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  35010. /**
  35011. * Get/set the minimum pitch angle that the bone can look to.
  35012. */
  35013. get: function () {
  35014. return this._minPitch;
  35015. },
  35016. set: function (value) {
  35017. this._minPitch = value;
  35018. this._minPitchTan = Math.tan(value);
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  35024. /**
  35025. * Get/set the maximum pitch angle that the bone can look to.
  35026. */
  35027. get: function () {
  35028. return this._maxPitch;
  35029. },
  35030. set: function (value) {
  35031. this._maxPitch = value;
  35032. this._maxPitchTan = Math.tan(value);
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. /**
  35038. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  35039. */
  35040. BoneLookController.prototype.update = function () {
  35041. //skip the first frame when slerping so that the mesh rotation is correct
  35042. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  35043. this._firstFrameSkipped = true;
  35044. return;
  35045. }
  35046. var bone = this.bone;
  35047. var bonePos = BoneLookController._tmpVecs[0];
  35048. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  35049. var target = this.target;
  35050. var _tmpMat1 = BoneLookController._tmpMats[0];
  35051. var _tmpMat2 = BoneLookController._tmpMats[1];
  35052. var mesh = this.mesh;
  35053. var parentBone = bone.getParent();
  35054. var upAxis = BoneLookController._tmpVecs[1];
  35055. upAxis.copyFrom(this.upAxis);
  35056. if (this.upAxisSpace == BABYLON.Space.BONE) {
  35057. if (this._transformYawPitch) {
  35058. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  35059. }
  35060. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  35061. }
  35062. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  35063. mesh.getDirectionToRef(upAxis, upAxis);
  35064. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  35065. upAxis.normalize();
  35066. }
  35067. }
  35068. var checkYaw = false;
  35069. var checkPitch = false;
  35070. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  35071. checkYaw = true;
  35072. }
  35073. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  35074. checkPitch = true;
  35075. }
  35076. if (checkYaw || checkPitch) {
  35077. var spaceMat = BoneLookController._tmpMats[2];
  35078. var spaceMatInv = BoneLookController._tmpMats[3];
  35079. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  35080. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  35081. }
  35082. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  35083. spaceMat.copyFrom(mesh.getWorldMatrix());
  35084. }
  35085. else {
  35086. var forwardAxis = BoneLookController._tmpVecs[2];
  35087. forwardAxis.copyFrom(this._fowardAxis);
  35088. if (this._transformYawPitch) {
  35089. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  35090. }
  35091. if (parentBone) {
  35092. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  35093. }
  35094. else {
  35095. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  35096. }
  35097. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  35098. rightAxis.normalize();
  35099. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  35100. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  35101. }
  35102. spaceMat.invertToRef(spaceMatInv);
  35103. var xzlen;
  35104. if (checkPitch) {
  35105. var localTarget = BoneLookController._tmpVecs[3];
  35106. target.subtractToRef(bonePos, localTarget);
  35107. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35108. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35109. var pitch = Math.atan2(localTarget.y, xzlen);
  35110. var newPitch = pitch;
  35111. if (pitch > this._maxPitch) {
  35112. localTarget.y = this._maxPitchTan * xzlen;
  35113. newPitch = this._maxPitch;
  35114. }
  35115. else if (pitch < this._minPitch) {
  35116. localTarget.y = this._minPitchTan * xzlen;
  35117. newPitch = this._minPitch;
  35118. }
  35119. if (pitch != newPitch) {
  35120. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35121. localTarget.addInPlace(bonePos);
  35122. target = localTarget;
  35123. }
  35124. }
  35125. if (checkYaw) {
  35126. var localTarget = BoneLookController._tmpVecs[4];
  35127. target.subtractToRef(bonePos, localTarget);
  35128. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35129. var yaw = Math.atan2(localTarget.x, localTarget.z);
  35130. var newYaw = yaw;
  35131. if (yaw > this._maxYaw || yaw < this._minYaw) {
  35132. if (xzlen == null) {
  35133. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35134. }
  35135. if (this._yawRange > Math.PI) {
  35136. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  35137. localTarget.z = this._maxYawCos * xzlen;
  35138. localTarget.x = this._maxYawSin * xzlen;
  35139. newYaw = this._maxYaw;
  35140. }
  35141. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  35142. localTarget.z = this._minYawCos * xzlen;
  35143. localTarget.x = this._minYawSin * xzlen;
  35144. newYaw = this._minYaw;
  35145. }
  35146. }
  35147. else {
  35148. if (yaw > this._maxYaw) {
  35149. localTarget.z = this._maxYawCos * xzlen;
  35150. localTarget.x = this._maxYawSin * xzlen;
  35151. newYaw = this._maxYaw;
  35152. }
  35153. else if (yaw < this._minYaw) {
  35154. localTarget.z = this._minYawCos * xzlen;
  35155. localTarget.x = this._minYawSin * xzlen;
  35156. newYaw = this._minYaw;
  35157. }
  35158. }
  35159. }
  35160. if (this._slerping && this._yawRange > Math.PI) {
  35161. //are we going to be crossing into the min/max region?
  35162. var boneFwd = BoneLookController._tmpVecs[8];
  35163. boneFwd.copyFrom(BABYLON.Axis.Z);
  35164. if (this._transformYawPitch) {
  35165. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  35166. }
  35167. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  35168. this._boneQuat.toRotationMatrix(boneRotMat);
  35169. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  35170. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  35171. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  35172. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  35173. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  35174. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  35175. if (angBtwTar > angBtwMidYaw) {
  35176. if (xzlen == null) {
  35177. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35178. }
  35179. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  35180. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  35181. if (angBtwMin < angBtwMax) {
  35182. newYaw = boneYaw + Math.PI * .75;
  35183. localTarget.z = Math.cos(newYaw) * xzlen;
  35184. localTarget.x = Math.sin(newYaw) * xzlen;
  35185. }
  35186. else {
  35187. newYaw = boneYaw - Math.PI * .75;
  35188. localTarget.z = Math.cos(newYaw) * xzlen;
  35189. localTarget.x = Math.sin(newYaw) * xzlen;
  35190. }
  35191. }
  35192. }
  35193. if (yaw != newYaw) {
  35194. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35195. localTarget.addInPlace(bonePos);
  35196. target = localTarget;
  35197. }
  35198. }
  35199. }
  35200. var zaxis = BoneLookController._tmpVecs[5];
  35201. var xaxis = BoneLookController._tmpVecs[6];
  35202. var yaxis = BoneLookController._tmpVecs[7];
  35203. var _tmpQuat = BoneLookController._tmpQuat;
  35204. target.subtractToRef(bonePos, zaxis);
  35205. zaxis.normalize();
  35206. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  35207. xaxis.normalize();
  35208. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  35209. yaxis.normalize();
  35210. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  35211. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  35212. return;
  35213. }
  35214. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  35215. return;
  35216. }
  35217. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  35218. return;
  35219. }
  35220. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  35221. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  35222. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  35223. }
  35224. if (this.slerpAmount < 1) {
  35225. if (!this._slerping) {
  35226. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  35227. }
  35228. if (this._transformYawPitch) {
  35229. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35230. }
  35231. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  35232. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  35233. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  35234. this._slerping = true;
  35235. }
  35236. else {
  35237. if (this._transformYawPitch) {
  35238. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35239. }
  35240. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  35241. this._slerping = false;
  35242. }
  35243. };
  35244. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  35245. var angDiff = ang2 - ang1;
  35246. angDiff %= Math.PI * 2;
  35247. if (angDiff > Math.PI) {
  35248. angDiff -= Math.PI * 2;
  35249. }
  35250. else if (angDiff < -Math.PI) {
  35251. angDiff += Math.PI * 2;
  35252. }
  35253. return angDiff;
  35254. };
  35255. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  35256. ang1 %= (2 * Math.PI);
  35257. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35258. ang2 %= (2 * Math.PI);
  35259. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35260. var ab = 0;
  35261. if (ang1 < ang2) {
  35262. ab = ang2 - ang1;
  35263. }
  35264. else {
  35265. ab = ang1 - ang2;
  35266. }
  35267. if (ab > Math.PI) {
  35268. ab = Math.PI * 2 - ab;
  35269. }
  35270. return ab;
  35271. };
  35272. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  35273. ang %= (2 * Math.PI);
  35274. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  35275. ang1 %= (2 * Math.PI);
  35276. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35277. ang2 %= (2 * Math.PI);
  35278. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35279. if (ang1 < ang2) {
  35280. if (ang > ang1 && ang < ang2) {
  35281. return true;
  35282. }
  35283. }
  35284. else {
  35285. if (ang > ang2 && ang < ang1) {
  35286. return true;
  35287. }
  35288. }
  35289. return false;
  35290. };
  35291. return BoneLookController;
  35292. }());
  35293. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  35294. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  35295. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  35296. BABYLON.BoneLookController = BoneLookController;
  35297. })(BABYLON || (BABYLON = {}));
  35298. //# sourceMappingURL=babylon.boneLookController.js.map
  35299. var BABYLON;
  35300. (function (BABYLON) {
  35301. var Skeleton = (function () {
  35302. function Skeleton(name, id, scene) {
  35303. this.name = name;
  35304. this.id = id;
  35305. this.bones = new Array();
  35306. this.needInitialSkinMatrix = false;
  35307. this._isDirty = true;
  35308. this._meshesWithPoseMatrix = new Array();
  35309. this._identity = BABYLON.Matrix.Identity();
  35310. this._ranges = {};
  35311. this._lastAbsoluteTransformsUpdateId = -1;
  35312. // Events
  35313. /**
  35314. * An event triggered before computing the skeleton's matrices
  35315. * @type {BABYLON.Observable}
  35316. */
  35317. this.onBeforeComputeObservable = new BABYLON.Observable();
  35318. this.bones = [];
  35319. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35320. scene.skeletons.push(this);
  35321. //make sure it will recalculate the matrix next time prepare is called.
  35322. this._isDirty = true;
  35323. }
  35324. // Members
  35325. Skeleton.prototype.getTransformMatrices = function (mesh) {
  35326. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  35327. return mesh._bonesTransformMatrices;
  35328. }
  35329. if (!this._transformMatrices) {
  35330. this.prepare();
  35331. }
  35332. return this._transformMatrices;
  35333. };
  35334. Skeleton.prototype.getScene = function () {
  35335. return this._scene;
  35336. };
  35337. // Methods
  35338. /**
  35339. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35340. */
  35341. Skeleton.prototype.toString = function (fullDetails) {
  35342. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  35343. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35344. if (fullDetails) {
  35345. ret += ", Ranges: {";
  35346. var first = true;
  35347. for (var name_1 in this._ranges) {
  35348. if (first) {
  35349. ret += ", ";
  35350. first = false;
  35351. }
  35352. ret += name_1;
  35353. }
  35354. ret += "}";
  35355. }
  35356. return ret;
  35357. };
  35358. /**
  35359. * Get bone's index searching by name
  35360. * @param {string} name is bone's name to search for
  35361. * @return {number} Indice of the bone. Returns -1 if not found
  35362. */
  35363. Skeleton.prototype.getBoneIndexByName = function (name) {
  35364. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  35365. if (this.bones[boneIndex].name === name) {
  35366. return boneIndex;
  35367. }
  35368. }
  35369. return -1;
  35370. };
  35371. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  35372. // check name not already in use
  35373. if (!this._ranges[name]) {
  35374. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  35375. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35376. if (this.bones[i].animations[0]) {
  35377. this.bones[i].animations[0].createRange(name, from, to);
  35378. }
  35379. }
  35380. }
  35381. };
  35382. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  35383. if (deleteFrames === void 0) { deleteFrames = true; }
  35384. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35385. if (this.bones[i].animations[0]) {
  35386. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  35387. }
  35388. }
  35389. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35390. };
  35391. Skeleton.prototype.getAnimationRange = function (name) {
  35392. return this._ranges[name];
  35393. };
  35394. /**
  35395. * Returns as an Array, all AnimationRanges defined on this skeleton
  35396. */
  35397. Skeleton.prototype.getAnimationRanges = function () {
  35398. var animationRanges = [];
  35399. var name;
  35400. var i = 0;
  35401. for (name in this._ranges) {
  35402. animationRanges[i] = this._ranges[name];
  35403. i++;
  35404. }
  35405. return animationRanges;
  35406. };
  35407. /**
  35408. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  35409. */
  35410. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  35411. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35412. if (this._ranges[name] || !source.getAnimationRange(name)) {
  35413. return false;
  35414. }
  35415. var ret = true;
  35416. var frameOffset = this._getHighestAnimationFrame() + 1;
  35417. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  35418. var boneDict = {};
  35419. var sourceBones = source.bones;
  35420. var nBones;
  35421. var i;
  35422. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  35423. boneDict[sourceBones[i].name] = sourceBones[i];
  35424. }
  35425. if (this.bones.length !== sourceBones.length) {
  35426. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  35427. ret = false;
  35428. }
  35429. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  35430. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  35431. var boneName = this.bones[i].name;
  35432. var sourceBone = boneDict[boneName];
  35433. if (sourceBone) {
  35434. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  35435. }
  35436. else {
  35437. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  35438. ret = false;
  35439. }
  35440. }
  35441. // do not call createAnimationRange(), since it also is done to bones, which was already done
  35442. var range = source.getAnimationRange(name);
  35443. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  35444. return ret;
  35445. };
  35446. Skeleton.prototype.returnToRest = function () {
  35447. for (var index = 0; index < this.bones.length; index++) {
  35448. this.bones[index].returnToRest();
  35449. }
  35450. };
  35451. Skeleton.prototype._getHighestAnimationFrame = function () {
  35452. var ret = 0;
  35453. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35454. if (this.bones[i].animations[0]) {
  35455. var highest = this.bones[i].animations[0].getHighestFrame();
  35456. if (ret < highest) {
  35457. ret = highest;
  35458. }
  35459. }
  35460. }
  35461. return ret;
  35462. };
  35463. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  35464. var range = this.getAnimationRange(name);
  35465. if (!range) {
  35466. return null;
  35467. }
  35468. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  35469. };
  35470. Skeleton.prototype._markAsDirty = function () {
  35471. this._isDirty = true;
  35472. };
  35473. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  35474. this._meshesWithPoseMatrix.push(mesh);
  35475. };
  35476. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  35477. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  35478. if (index > -1) {
  35479. this._meshesWithPoseMatrix.splice(index, 1);
  35480. }
  35481. };
  35482. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  35483. this.onBeforeComputeObservable.notifyObservers(this);
  35484. for (var index = 0; index < this.bones.length; index++) {
  35485. var bone = this.bones[index];
  35486. var parentBone = bone.getParent();
  35487. if (parentBone) {
  35488. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  35489. }
  35490. else {
  35491. if (initialSkinMatrix) {
  35492. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  35493. }
  35494. else {
  35495. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  35496. }
  35497. }
  35498. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  35499. }
  35500. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  35501. };
  35502. Skeleton.prototype.prepare = function () {
  35503. if (!this._isDirty) {
  35504. return;
  35505. }
  35506. if (this.needInitialSkinMatrix) {
  35507. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  35508. var mesh = this._meshesWithPoseMatrix[index];
  35509. var poseMatrix = mesh.getPoseMatrix();
  35510. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  35511. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35512. }
  35513. if (this._synchronizedWithMesh !== mesh) {
  35514. this._synchronizedWithMesh = mesh;
  35515. // Prepare bones
  35516. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  35517. var bone = this.bones[boneIndex];
  35518. if (!bone.getParent()) {
  35519. var matrix = bone.getBaseMatrix();
  35520. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  35521. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  35522. }
  35523. }
  35524. }
  35525. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  35526. }
  35527. }
  35528. else {
  35529. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  35530. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35531. }
  35532. this._computeTransformMatrices(this._transformMatrices, null);
  35533. }
  35534. this._isDirty = false;
  35535. this._scene._activeBones.addCount(this.bones.length, false);
  35536. };
  35537. Skeleton.prototype.getAnimatables = function () {
  35538. if (!this._animatables || this._animatables.length !== this.bones.length) {
  35539. this._animatables = [];
  35540. for (var index = 0; index < this.bones.length; index++) {
  35541. this._animatables.push(this.bones[index]);
  35542. }
  35543. }
  35544. return this._animatables;
  35545. };
  35546. Skeleton.prototype.clone = function (name, id) {
  35547. var result = new Skeleton(name, id || name, this._scene);
  35548. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35549. for (var index = 0; index < this.bones.length; index++) {
  35550. var source = this.bones[index];
  35551. var parentBone = null;
  35552. if (source.getParent()) {
  35553. var parentIndex = this.bones.indexOf(source.getParent());
  35554. parentBone = result.bones[parentIndex];
  35555. }
  35556. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  35557. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  35558. }
  35559. if (this._ranges) {
  35560. result._ranges = {};
  35561. for (var rangeName in this._ranges) {
  35562. result._ranges[rangeName] = this._ranges[rangeName].clone();
  35563. }
  35564. }
  35565. this._isDirty = true;
  35566. return result;
  35567. };
  35568. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  35569. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  35570. this.bones.forEach(function (bone) {
  35571. bone.animations.forEach(function (animation) {
  35572. animation.enableBlending = true;
  35573. animation.blendingSpeed = blendingSpeed;
  35574. });
  35575. });
  35576. };
  35577. Skeleton.prototype.dispose = function () {
  35578. this._meshesWithPoseMatrix = [];
  35579. // Animations
  35580. this.getScene().stopAnimation(this);
  35581. // Remove from scene
  35582. this.getScene().removeSkeleton(this);
  35583. };
  35584. Skeleton.prototype.serialize = function () {
  35585. var serializationObject = {};
  35586. serializationObject.name = this.name;
  35587. serializationObject.id = this.id;
  35588. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  35589. serializationObject.bones = [];
  35590. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35591. for (var index = 0; index < this.bones.length; index++) {
  35592. var bone = this.bones[index];
  35593. var serializedBone = {
  35594. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  35595. name: bone.name,
  35596. matrix: bone.getBaseMatrix().toArray(),
  35597. rest: bone.getRestPose().toArray()
  35598. };
  35599. serializationObject.bones.push(serializedBone);
  35600. if (bone.length) {
  35601. serializedBone.length = bone.length;
  35602. }
  35603. if (bone.animations && bone.animations.length > 0) {
  35604. serializedBone.animation = bone.animations[0].serialize();
  35605. }
  35606. serializationObject.ranges = [];
  35607. for (var name in this._ranges) {
  35608. var range = {};
  35609. range.name = name;
  35610. range.from = this._ranges[name].from;
  35611. range.to = this._ranges[name].to;
  35612. serializationObject.ranges.push(range);
  35613. }
  35614. }
  35615. return serializationObject;
  35616. };
  35617. Skeleton.Parse = function (parsedSkeleton, scene) {
  35618. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  35619. if (parsedSkeleton.dimensionsAtRest) {
  35620. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  35621. }
  35622. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  35623. var index;
  35624. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  35625. var parsedBone = parsedSkeleton.bones[index];
  35626. var parentBone = null;
  35627. if (parsedBone.parentBoneIndex > -1) {
  35628. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  35629. }
  35630. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  35631. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  35632. if (parsedBone.length) {
  35633. bone.length = parsedBone.length;
  35634. }
  35635. if (parsedBone.animation) {
  35636. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  35637. }
  35638. }
  35639. // placed after bones, so createAnimationRange can cascade down
  35640. if (parsedSkeleton.ranges) {
  35641. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  35642. var data = parsedSkeleton.ranges[index];
  35643. skeleton.createAnimationRange(data.name, data.from, data.to);
  35644. }
  35645. }
  35646. return skeleton;
  35647. };
  35648. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  35649. if (forceUpdate === void 0) { forceUpdate = false; }
  35650. var renderId = this._scene.getRenderId();
  35651. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  35652. this.bones[0].computeAbsoluteTransforms();
  35653. this._lastAbsoluteTransformsUpdateId = renderId;
  35654. }
  35655. };
  35656. Skeleton.prototype.getPoseMatrix = function () {
  35657. var poseMatrix;
  35658. if (this._meshesWithPoseMatrix.length > 0) {
  35659. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  35660. }
  35661. return poseMatrix;
  35662. };
  35663. return Skeleton;
  35664. }());
  35665. BABYLON.Skeleton = Skeleton;
  35666. })(BABYLON || (BABYLON = {}));
  35667. //# sourceMappingURL=babylon.skeleton.js.map
  35668. var BABYLON;
  35669. (function (BABYLON) {
  35670. var PostProcess = (function () {
  35671. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  35672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35673. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35674. this.name = name;
  35675. this.width = -1;
  35676. this.height = -1;
  35677. /*
  35678. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35679. Can only be used on a single postprocess or on the last one of a chain.
  35680. */
  35681. this.enablePixelPerfectMode = false;
  35682. this.samples = 1;
  35683. this._reusable = false;
  35684. this._textures = new BABYLON.SmartArray(2);
  35685. this._currentRenderTextureInd = 0;
  35686. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35687. // Events
  35688. /**
  35689. * An event triggered when the postprocess is activated.
  35690. * @type {BABYLON.Observable}
  35691. */
  35692. this.onActivateObservable = new BABYLON.Observable();
  35693. /**
  35694. * An event triggered when the postprocess changes its size.
  35695. * @type {BABYLON.Observable}
  35696. */
  35697. this.onSizeChangedObservable = new BABYLON.Observable();
  35698. /**
  35699. * An event triggered when the postprocess applies its effect.
  35700. * @type {BABYLON.Observable}
  35701. */
  35702. this.onApplyObservable = new BABYLON.Observable();
  35703. /**
  35704. * An event triggered before rendering the postprocess
  35705. * @type {BABYLON.Observable}
  35706. */
  35707. this.onBeforeRenderObservable = new BABYLON.Observable();
  35708. /**
  35709. * An event triggered after rendering the postprocess
  35710. * @type {BABYLON.Observable}
  35711. */
  35712. this.onAfterRenderObservable = new BABYLON.Observable();
  35713. if (camera != null) {
  35714. this._camera = camera;
  35715. this._scene = camera.getScene();
  35716. camera.attachPostProcess(this);
  35717. this._engine = this._scene.getEngine();
  35718. }
  35719. else {
  35720. this._engine = engine;
  35721. }
  35722. this._options = options;
  35723. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35724. this._reusable = reusable || false;
  35725. this._textureType = textureType;
  35726. this._samplers = samplers || [];
  35727. this._samplers.push("textureSampler");
  35728. this._fragmentUrl = fragmentUrl;
  35729. this._parameters = parameters || [];
  35730. this._parameters.push("scale");
  35731. this.updateEffect(defines);
  35732. }
  35733. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35734. set: function (callback) {
  35735. if (this._onActivateObserver) {
  35736. this.onActivateObservable.remove(this._onActivateObserver);
  35737. }
  35738. this._onActivateObserver = this.onActivateObservable.add(callback);
  35739. },
  35740. enumerable: true,
  35741. configurable: true
  35742. });
  35743. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35744. set: function (callback) {
  35745. if (this._onSizeChangedObserver) {
  35746. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35747. }
  35748. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35749. },
  35750. enumerable: true,
  35751. configurable: true
  35752. });
  35753. Object.defineProperty(PostProcess.prototype, "onApply", {
  35754. set: function (callback) {
  35755. if (this._onApplyObserver) {
  35756. this.onApplyObservable.remove(this._onApplyObserver);
  35757. }
  35758. this._onApplyObserver = this.onApplyObservable.add(callback);
  35759. },
  35760. enumerable: true,
  35761. configurable: true
  35762. });
  35763. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35764. set: function (callback) {
  35765. if (this._onBeforeRenderObserver) {
  35766. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35767. }
  35768. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35769. },
  35770. enumerable: true,
  35771. configurable: true
  35772. });
  35773. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35774. set: function (callback) {
  35775. if (this._onAfterRenderObserver) {
  35776. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35777. }
  35778. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35779. },
  35780. enumerable: true,
  35781. configurable: true
  35782. });
  35783. PostProcess.prototype.updateEffect = function (defines) {
  35784. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  35785. };
  35786. PostProcess.prototype.isReusable = function () {
  35787. return this._reusable;
  35788. };
  35789. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35790. PostProcess.prototype.markTextureDirty = function () {
  35791. this.width = -1;
  35792. };
  35793. PostProcess.prototype.activate = function (camera, sourceTexture) {
  35794. var _this = this;
  35795. camera = camera || this._camera;
  35796. var scene = camera.getScene();
  35797. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  35798. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35799. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35800. var desiredWidth = this._options.width || requiredWidth;
  35801. var desiredHeight = this._options.height || requiredHeight;
  35802. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  35803. if (!this._options.width) {
  35804. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  35805. }
  35806. if (!this._options.height) {
  35807. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  35808. }
  35809. }
  35810. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35811. if (this._textures.length > 0) {
  35812. for (var i = 0; i < this._textures.length; i++) {
  35813. this._engine._releaseTexture(this._textures.data[i]);
  35814. }
  35815. this._textures.reset();
  35816. }
  35817. this.width = desiredWidth;
  35818. this.height = desiredHeight;
  35819. var textureSize = { width: this.width, height: this.height };
  35820. var textureOptions = {
  35821. generateMipMaps: false,
  35822. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  35823. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  35824. samplingMode: this.renderTargetSamplingMode,
  35825. type: this._textureType
  35826. };
  35827. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35828. if (this._reusable) {
  35829. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35830. }
  35831. this.onSizeChangedObservable.notifyObservers(this);
  35832. }
  35833. this._textures.forEach(function (texture) {
  35834. if (texture.samples !== _this.samples) {
  35835. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35836. }
  35837. });
  35838. if (this.enablePixelPerfectMode) {
  35839. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35840. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  35841. }
  35842. else {
  35843. this._scaleRatio.copyFromFloats(1, 1);
  35844. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  35845. }
  35846. this.onActivateObservable.notifyObservers(camera);
  35847. // Clear
  35848. if (this.clearColor) {
  35849. this._engine.clear(this.clearColor, true, true, true);
  35850. }
  35851. else {
  35852. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  35853. }
  35854. if (this._reusable) {
  35855. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35856. }
  35857. };
  35858. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35859. get: function () {
  35860. return this._effect.isSupported;
  35861. },
  35862. enumerable: true,
  35863. configurable: true
  35864. });
  35865. PostProcess.prototype.apply = function () {
  35866. // Check
  35867. if (!this._effect.isReady())
  35868. return null;
  35869. // States
  35870. this._engine.enableEffect(this._effect);
  35871. this._engine.setState(false);
  35872. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35873. this._engine.setDepthBuffer(false);
  35874. this._engine.setDepthWrite(false);
  35875. // Texture
  35876. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  35877. // Parameters
  35878. this._effect.setVector2("scale", this._scaleRatio);
  35879. this.onApplyObservable.notifyObservers(this._effect);
  35880. return this._effect;
  35881. };
  35882. PostProcess.prototype.dispose = function (camera) {
  35883. camera = camera || this._camera;
  35884. if (this._textures.length > 0) {
  35885. for (var i = 0; i < this._textures.length; i++) {
  35886. this._engine._releaseTexture(this._textures.data[i]);
  35887. }
  35888. }
  35889. this._textures.dispose();
  35890. if (!camera) {
  35891. return;
  35892. }
  35893. camera.detachPostProcess(this);
  35894. var index = camera._postProcesses.indexOf(this);
  35895. if (index === 0 && camera._postProcesses.length > 0) {
  35896. this._camera._postProcesses[0].markTextureDirty();
  35897. }
  35898. this.onActivateObservable.clear();
  35899. this.onAfterRenderObservable.clear();
  35900. this.onApplyObservable.clear();
  35901. this.onBeforeRenderObservable.clear();
  35902. this.onSizeChangedObservable.clear();
  35903. };
  35904. return PostProcess;
  35905. }());
  35906. BABYLON.PostProcess = PostProcess;
  35907. })(BABYLON || (BABYLON = {}));
  35908. //# sourceMappingURL=babylon.postProcess.js.map
  35909. var BABYLON;
  35910. (function (BABYLON) {
  35911. var PostProcessManager = (function () {
  35912. function PostProcessManager(scene) {
  35913. this._vertexBuffers = {};
  35914. this._scene = scene;
  35915. }
  35916. PostProcessManager.prototype._prepareBuffers = function () {
  35917. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35918. return;
  35919. }
  35920. // VBO
  35921. var vertices = [];
  35922. vertices.push(1, 1);
  35923. vertices.push(-1, 1);
  35924. vertices.push(-1, -1);
  35925. vertices.push(1, -1);
  35926. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35927. // Indices
  35928. var indices = [];
  35929. indices.push(0);
  35930. indices.push(1);
  35931. indices.push(2);
  35932. indices.push(0);
  35933. indices.push(2);
  35934. indices.push(3);
  35935. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35936. };
  35937. // Methods
  35938. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  35939. var postProcesses = this._scene.activeCamera._postProcesses;
  35940. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35941. return false;
  35942. }
  35943. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  35944. return true;
  35945. };
  35946. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  35947. var engine = this._scene.getEngine();
  35948. for (var index = 0; index < postProcesses.length; index++) {
  35949. if (index < postProcesses.length - 1) {
  35950. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35951. }
  35952. else {
  35953. if (targetTexture) {
  35954. engine.bindFramebuffer(targetTexture);
  35955. }
  35956. else {
  35957. engine.restoreDefaultFramebuffer();
  35958. }
  35959. }
  35960. var pp = postProcesses[index];
  35961. var effect = pp.apply();
  35962. if (effect) {
  35963. pp.onBeforeRenderObservable.notifyObservers(effect);
  35964. // VBOs
  35965. this._prepareBuffers();
  35966. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35967. // Draw order
  35968. engine.draw(true, 0, 6);
  35969. pp.onAfterRenderObservable.notifyObservers(effect);
  35970. }
  35971. }
  35972. // Restore depth buffer
  35973. engine.setDepthBuffer(true);
  35974. engine.setDepthWrite(true);
  35975. };
  35976. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  35977. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  35978. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35979. return;
  35980. }
  35981. var engine = this._scene.getEngine();
  35982. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35983. if (index < len - 1) {
  35984. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35985. }
  35986. else {
  35987. if (targetTexture) {
  35988. engine.bindFramebuffer(targetTexture, faceIndex);
  35989. }
  35990. else {
  35991. engine.restoreDefaultFramebuffer();
  35992. }
  35993. }
  35994. if (doNotPresent) {
  35995. break;
  35996. }
  35997. var pp = postProcesses[index];
  35998. var effect = pp.apply();
  35999. if (effect) {
  36000. pp.onBeforeRenderObservable.notifyObservers(effect);
  36001. // VBOs
  36002. this._prepareBuffers();
  36003. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36004. // Draw order
  36005. engine.draw(true, 0, 6);
  36006. pp.onAfterRenderObservable.notifyObservers(effect);
  36007. }
  36008. }
  36009. // Restore depth buffer
  36010. engine.setDepthBuffer(true);
  36011. engine.setDepthWrite(true);
  36012. };
  36013. PostProcessManager.prototype.dispose = function () {
  36014. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36015. if (buffer) {
  36016. buffer.dispose();
  36017. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36018. }
  36019. if (this._indexBuffer) {
  36020. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36021. this._indexBuffer = null;
  36022. }
  36023. };
  36024. return PostProcessManager;
  36025. }());
  36026. BABYLON.PostProcessManager = PostProcessManager;
  36027. })(BABYLON || (BABYLON = {}));
  36028. //# sourceMappingURL=babylon.postProcessManager.js.map
  36029. var BABYLON;
  36030. (function (BABYLON) {
  36031. var PassPostProcess = (function (_super) {
  36032. __extends(PassPostProcess, _super);
  36033. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  36034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36035. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  36036. }
  36037. return PassPostProcess;
  36038. }(BABYLON.PostProcess));
  36039. BABYLON.PassPostProcess = PassPostProcess;
  36040. })(BABYLON || (BABYLON = {}));
  36041. //# sourceMappingURL=babylon.passPostProcess.js.map
  36042. var BABYLON;
  36043. (function (BABYLON) {
  36044. /**
  36045. * This is a holder class for the physics joint created by the physics plugin.
  36046. * It holds a set of functions to control the underlying joint.
  36047. */
  36048. var PhysicsJoint = (function () {
  36049. function PhysicsJoint(type, jointData) {
  36050. this.type = type;
  36051. this.jointData = jointData;
  36052. jointData.nativeParams = jointData.nativeParams || {};
  36053. }
  36054. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  36055. get: function () {
  36056. return this._physicsJoint;
  36057. },
  36058. set: function (newJoint) {
  36059. if (this._physicsJoint) {
  36060. }
  36061. this._physicsJoint = newJoint;
  36062. },
  36063. enumerable: true,
  36064. configurable: true
  36065. });
  36066. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  36067. set: function (physicsPlugin) {
  36068. this._physicsPlugin = physicsPlugin;
  36069. },
  36070. enumerable: true,
  36071. configurable: true
  36072. });
  36073. /**
  36074. * Execute a function that is physics-plugin specific.
  36075. * @param {Function} func the function that will be executed.
  36076. * It accepts two parameters: the physics world and the physics joint.
  36077. */
  36078. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  36079. func(this._physicsPlugin.world, this._physicsJoint);
  36080. };
  36081. return PhysicsJoint;
  36082. }());
  36083. //TODO check if the native joints are the same
  36084. //Joint Types
  36085. PhysicsJoint.DistanceJoint = 0;
  36086. PhysicsJoint.HingeJoint = 1;
  36087. PhysicsJoint.BallAndSocketJoint = 2;
  36088. PhysicsJoint.WheelJoint = 3;
  36089. PhysicsJoint.SliderJoint = 4;
  36090. //OIMO
  36091. PhysicsJoint.PrismaticJoint = 5;
  36092. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  36093. PhysicsJoint.UniversalJoint = 6;
  36094. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  36095. //Cannon
  36096. //Similar to a Ball-Joint. Different in params
  36097. PhysicsJoint.PointToPointJoint = 8;
  36098. //Cannon only at the moment
  36099. PhysicsJoint.SpringJoint = 9;
  36100. PhysicsJoint.LockJoint = 10;
  36101. BABYLON.PhysicsJoint = PhysicsJoint;
  36102. /**
  36103. * A class representing a physics distance joint.
  36104. */
  36105. var DistanceJoint = (function (_super) {
  36106. __extends(DistanceJoint, _super);
  36107. function DistanceJoint(jointData) {
  36108. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  36109. }
  36110. /**
  36111. * Update the predefined distance.
  36112. */
  36113. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  36114. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  36115. };
  36116. return DistanceJoint;
  36117. }(PhysicsJoint));
  36118. BABYLON.DistanceJoint = DistanceJoint;
  36119. var MotorEnabledJoint = (function (_super) {
  36120. __extends(MotorEnabledJoint, _super);
  36121. function MotorEnabledJoint(type, jointData) {
  36122. return _super.call(this, type, jointData) || this;
  36123. }
  36124. /**
  36125. * Set the motor values.
  36126. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36127. * @param {number} force the force to apply
  36128. * @param {number} maxForce max force for this motor.
  36129. */
  36130. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  36131. this._physicsPlugin.setMotor(this, force, maxForce);
  36132. };
  36133. /**
  36134. * Set the motor's limits.
  36135. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36136. */
  36137. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36138. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36139. };
  36140. return MotorEnabledJoint;
  36141. }(PhysicsJoint));
  36142. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  36143. /**
  36144. * This class represents a single hinge physics joint
  36145. */
  36146. var HingeJoint = (function (_super) {
  36147. __extends(HingeJoint, _super);
  36148. function HingeJoint(jointData) {
  36149. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  36150. }
  36151. /**
  36152. * Set the motor values.
  36153. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36154. * @param {number} force the force to apply
  36155. * @param {number} maxForce max force for this motor.
  36156. */
  36157. HingeJoint.prototype.setMotor = function (force, maxForce) {
  36158. this._physicsPlugin.setMotor(this, force, maxForce);
  36159. };
  36160. /**
  36161. * Set the motor's limits.
  36162. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36163. */
  36164. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36165. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36166. };
  36167. return HingeJoint;
  36168. }(MotorEnabledJoint));
  36169. BABYLON.HingeJoint = HingeJoint;
  36170. /**
  36171. * This class represents a dual hinge physics joint (same as wheel joint)
  36172. */
  36173. var Hinge2Joint = (function (_super) {
  36174. __extends(Hinge2Joint, _super);
  36175. function Hinge2Joint(jointData) {
  36176. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  36177. }
  36178. /**
  36179. * Set the motor values.
  36180. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36181. * @param {number} force the force to apply
  36182. * @param {number} maxForce max force for this motor.
  36183. * @param {motorIndex} the motor's index, 0 or 1.
  36184. */
  36185. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  36186. if (motorIndex === void 0) { motorIndex = 0; }
  36187. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  36188. };
  36189. /**
  36190. * Set the motor limits.
  36191. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36192. * @param {number} upperLimit the upper limit
  36193. * @param {number} lowerLimit lower limit
  36194. * @param {motorIndex} the motor's index, 0 or 1.
  36195. */
  36196. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  36197. if (motorIndex === void 0) { motorIndex = 0; }
  36198. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  36199. };
  36200. return Hinge2Joint;
  36201. }(MotorEnabledJoint));
  36202. BABYLON.Hinge2Joint = Hinge2Joint;
  36203. })(BABYLON || (BABYLON = {}));
  36204. //# sourceMappingURL=babylon.physicsJoint.js.map
  36205. var BABYLON;
  36206. (function (BABYLON) {
  36207. var PhysicsImpostor = (function () {
  36208. function PhysicsImpostor(object, type, _options, _scene) {
  36209. if (_options === void 0) { _options = { mass: 0 }; }
  36210. var _this = this;
  36211. this.object = object;
  36212. this.type = type;
  36213. this._options = _options;
  36214. this._scene = _scene;
  36215. this._bodyUpdateRequired = false;
  36216. this._onBeforePhysicsStepCallbacks = new Array();
  36217. this._onAfterPhysicsStepCallbacks = new Array();
  36218. this._onPhysicsCollideCallbacks = [];
  36219. this._deltaPosition = BABYLON.Vector3.Zero();
  36220. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  36221. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  36222. /**
  36223. * this function is executed by the physics engine.
  36224. */
  36225. this.beforeStep = function () {
  36226. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  36227. //conjugate deltaRotation
  36228. if (_this._deltaRotationConjugated) {
  36229. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  36230. }
  36231. else {
  36232. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  36233. }
  36234. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  36235. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  36236. func(_this);
  36237. });
  36238. };
  36239. /**
  36240. * this function is executed by the physics engine.
  36241. */
  36242. this.afterStep = function () {
  36243. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  36244. func(_this);
  36245. });
  36246. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  36247. _this.object.position.addInPlace(_this._deltaPosition);
  36248. if (_this._deltaRotation) {
  36249. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  36250. }
  36251. };
  36252. /**
  36253. * Legacy collision detection event support
  36254. */
  36255. this.onCollideEvent = null;
  36256. //event and body object due to cannon's event-based architecture.
  36257. this.onCollide = function (e) {
  36258. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  36259. return;
  36260. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  36261. if (otherImpostor) {
  36262. // Legacy collision detection event support
  36263. if (_this.onCollideEvent) {
  36264. _this.onCollideEvent(_this, otherImpostor);
  36265. }
  36266. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  36267. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  36268. }).forEach(function (obj) {
  36269. obj.callback(_this, otherImpostor);
  36270. });
  36271. }
  36272. };
  36273. //sanity check!
  36274. if (!this.object) {
  36275. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  36276. return;
  36277. }
  36278. //legacy support for old syntax.
  36279. if (!this._scene && object.getScene) {
  36280. this._scene = object.getScene();
  36281. }
  36282. this._physicsEngine = this._scene.getPhysicsEngine();
  36283. if (!this._physicsEngine) {
  36284. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  36285. }
  36286. else {
  36287. //set the object's quaternion, if not set
  36288. if (!this.object.rotationQuaternion) {
  36289. if (this.object.rotation) {
  36290. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  36291. }
  36292. else {
  36293. this.object.rotationQuaternion = new BABYLON.Quaternion();
  36294. }
  36295. }
  36296. //default options params
  36297. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  36298. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  36299. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  36300. this._joints = [];
  36301. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  36302. if (!this.object.parent) {
  36303. this._init();
  36304. }
  36305. }
  36306. }
  36307. /**
  36308. * This function will completly initialize this impostor.
  36309. * It will create a new body - but only if this mesh has no parent.
  36310. * If it has, this impostor will not be used other than to define the impostor
  36311. * of the child mesh.
  36312. */
  36313. PhysicsImpostor.prototype._init = function () {
  36314. this._physicsEngine.removeImpostor(this);
  36315. this.physicsBody = null;
  36316. this._parent = this._parent || this._getPhysicsParent();
  36317. if (!this.parent) {
  36318. this._physicsEngine.addImpostor(this);
  36319. }
  36320. };
  36321. PhysicsImpostor.prototype._getPhysicsParent = function () {
  36322. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  36323. var parentMesh = this.object.parent;
  36324. return parentMesh.physicsImpostor;
  36325. }
  36326. return;
  36327. };
  36328. /**
  36329. * Should a new body be generated.
  36330. */
  36331. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  36332. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  36333. };
  36334. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  36335. this.forceUpdate();
  36336. };
  36337. /**
  36338. * Force a regeneration of this or the parent's impostor's body.
  36339. * Use under cautious - This will remove all joints already implemented.
  36340. */
  36341. PhysicsImpostor.prototype.forceUpdate = function () {
  36342. this._init();
  36343. if (this.parent) {
  36344. this.parent.forceUpdate();
  36345. }
  36346. };
  36347. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  36348. /*public get mesh(): AbstractMesh {
  36349. return this._mesh;
  36350. }*/
  36351. /**
  36352. * Gets the body that holds this impostor. Either its own, or its parent.
  36353. */
  36354. get: function () {
  36355. return this._parent ? this._parent.physicsBody : this._physicsBody;
  36356. },
  36357. /**
  36358. * Set the physics body. Used mainly by the physics engine/plugin
  36359. */
  36360. set: function (physicsBody) {
  36361. if (this._physicsBody) {
  36362. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  36363. }
  36364. this._physicsBody = physicsBody;
  36365. this.resetUpdateFlags();
  36366. },
  36367. enumerable: true,
  36368. configurable: true
  36369. });
  36370. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  36371. get: function () {
  36372. return this._parent;
  36373. },
  36374. set: function (value) {
  36375. this._parent = value;
  36376. },
  36377. enumerable: true,
  36378. configurable: true
  36379. });
  36380. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  36381. this._bodyUpdateRequired = false;
  36382. };
  36383. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  36384. if (this.object.getBoundingInfo) {
  36385. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  36386. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  36387. }
  36388. else {
  36389. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  36390. }
  36391. };
  36392. PhysicsImpostor.prototype.getObjectCenter = function () {
  36393. if (this.object.getBoundingInfo) {
  36394. return this.object.getBoundingInfo().boundingBox.centerWorld;
  36395. }
  36396. else {
  36397. return this.object.position;
  36398. }
  36399. };
  36400. /**
  36401. * Get a specific parametes from the options parameter.
  36402. */
  36403. PhysicsImpostor.prototype.getParam = function (paramName) {
  36404. return this._options[paramName];
  36405. };
  36406. /**
  36407. * Sets a specific parameter in the options given to the physics plugin
  36408. */
  36409. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  36410. this._options[paramName] = value;
  36411. this._bodyUpdateRequired = true;
  36412. };
  36413. /**
  36414. * Specifically change the body's mass option. Won't recreate the physics body object
  36415. */
  36416. PhysicsImpostor.prototype.setMass = function (mass) {
  36417. if (this.getParam("mass") !== mass) {
  36418. this.setParam("mass", mass);
  36419. }
  36420. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  36421. };
  36422. PhysicsImpostor.prototype.getLinearVelocity = function () {
  36423. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  36424. };
  36425. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  36426. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  36427. };
  36428. PhysicsImpostor.prototype.getAngularVelocity = function () {
  36429. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  36430. };
  36431. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  36432. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  36433. };
  36434. /**
  36435. * Execute a function with the physics plugin native code.
  36436. * Provide a function the will have two variables - the world object and the physics body object.
  36437. */
  36438. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  36439. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  36440. };
  36441. /**
  36442. * Register a function that will be executed before the physics world is stepping forward.
  36443. */
  36444. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  36445. this._onBeforePhysicsStepCallbacks.push(func);
  36446. };
  36447. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  36448. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  36449. if (index > -1) {
  36450. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  36451. }
  36452. else {
  36453. BABYLON.Tools.Warn("Function to remove was not found");
  36454. }
  36455. };
  36456. /**
  36457. * Register a function that will be executed after the physics step
  36458. */
  36459. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  36460. this._onAfterPhysicsStepCallbacks.push(func);
  36461. };
  36462. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  36463. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  36464. if (index > -1) {
  36465. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  36466. }
  36467. else {
  36468. BABYLON.Tools.Warn("Function to remove was not found");
  36469. }
  36470. };
  36471. /**
  36472. * register a function that will be executed when this impostor collides against a different body.
  36473. */
  36474. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  36475. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36476. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  36477. };
  36478. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  36479. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36480. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  36481. if (index > -1) {
  36482. this._onPhysicsCollideCallbacks.splice(index, 1);
  36483. }
  36484. else {
  36485. BABYLON.Tools.Warn("Function to remove was not found");
  36486. }
  36487. };
  36488. /**
  36489. * Apply a force
  36490. */
  36491. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  36492. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  36493. };
  36494. /**
  36495. * Apply an impulse
  36496. */
  36497. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  36498. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  36499. };
  36500. /**
  36501. * A help function to create a joint.
  36502. */
  36503. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  36504. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  36505. this.addJoint(otherImpostor, joint);
  36506. };
  36507. /**
  36508. * Add a joint to this impostor with a different impostor.
  36509. */
  36510. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  36511. this._joints.push({
  36512. otherImpostor: otherImpostor,
  36513. joint: joint
  36514. });
  36515. this._physicsEngine.addJoint(this, otherImpostor, joint);
  36516. };
  36517. /**
  36518. * Will keep this body still, in a sleep mode.
  36519. */
  36520. PhysicsImpostor.prototype.sleep = function () {
  36521. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  36522. };
  36523. /**
  36524. * Wake the body up.
  36525. */
  36526. PhysicsImpostor.prototype.wakeUp = function () {
  36527. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  36528. };
  36529. PhysicsImpostor.prototype.clone = function (newObject) {
  36530. if (!newObject)
  36531. return null;
  36532. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  36533. };
  36534. PhysicsImpostor.prototype.dispose = function () {
  36535. var _this = this;
  36536. //no dispose if no physics engine is available.
  36537. if (!this._physicsEngine) {
  36538. return;
  36539. }
  36540. this._joints.forEach(function (j) {
  36541. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  36542. });
  36543. //dispose the physics body
  36544. this._physicsEngine.removeImpostor(this);
  36545. if (this.parent) {
  36546. this.parent.forceUpdate();
  36547. }
  36548. else {
  36549. }
  36550. };
  36551. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  36552. this._deltaPosition.copyFrom(position);
  36553. };
  36554. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  36555. if (!this._deltaRotation) {
  36556. this._deltaRotation = new BABYLON.Quaternion();
  36557. }
  36558. this._deltaRotation.copyFrom(rotation);
  36559. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  36560. };
  36561. return PhysicsImpostor;
  36562. }());
  36563. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  36564. //Impostor types
  36565. PhysicsImpostor.NoImpostor = 0;
  36566. PhysicsImpostor.SphereImpostor = 1;
  36567. PhysicsImpostor.BoxImpostor = 2;
  36568. PhysicsImpostor.PlaneImpostor = 3;
  36569. PhysicsImpostor.MeshImpostor = 4;
  36570. PhysicsImpostor.CylinderImpostor = 7;
  36571. PhysicsImpostor.ParticleImpostor = 8;
  36572. PhysicsImpostor.HeightmapImpostor = 9;
  36573. BABYLON.PhysicsImpostor = PhysicsImpostor;
  36574. })(BABYLON || (BABYLON = {}));
  36575. //# sourceMappingURL=babylon.physicsImpostor.js.map
  36576. var BABYLON;
  36577. (function (BABYLON) {
  36578. var PhysicsEngine = (function () {
  36579. function PhysicsEngine(gravity, _physicsPlugin) {
  36580. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  36581. this._physicsPlugin = _physicsPlugin;
  36582. //new methods and parameters
  36583. this._impostors = [];
  36584. this._joints = [];
  36585. if (!this._physicsPlugin.isSupported()) {
  36586. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  36587. + "Please make sure it is included.");
  36588. }
  36589. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  36590. this.setGravity(gravity);
  36591. this.setTimeStep();
  36592. }
  36593. PhysicsEngine.prototype.setGravity = function (gravity) {
  36594. this.gravity = gravity;
  36595. this._physicsPlugin.setGravity(this.gravity);
  36596. };
  36597. /**
  36598. * Set the time step of the physics engine.
  36599. * default is 1/60.
  36600. * To slow it down, enter 1/600 for example.
  36601. * To speed it up, 1/30
  36602. * @param {number} newTimeStep the new timestep to apply to this world.
  36603. */
  36604. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  36605. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  36606. this._physicsPlugin.setTimeStep(newTimeStep);
  36607. };
  36608. PhysicsEngine.prototype.dispose = function () {
  36609. this._impostors.forEach(function (impostor) {
  36610. impostor.dispose();
  36611. });
  36612. this._physicsPlugin.dispose();
  36613. };
  36614. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  36615. return this._physicsPlugin.name;
  36616. };
  36617. /**
  36618. * Adding a new impostor for the impostor tracking.
  36619. * This will be done by the impostor itself.
  36620. * @param {PhysicsImpostor} impostor the impostor to add
  36621. */
  36622. PhysicsEngine.prototype.addImpostor = function (impostor) {
  36623. impostor.uniqueId = this._impostors.push(impostor);
  36624. //if no parent, generate the body
  36625. if (!impostor.parent) {
  36626. this._physicsPlugin.generatePhysicsBody(impostor);
  36627. }
  36628. };
  36629. /**
  36630. * Remove an impostor from the engine.
  36631. * This impostor and its mesh will not longer be updated by the physics engine.
  36632. * @param {PhysicsImpostor} impostor the impostor to remove
  36633. */
  36634. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  36635. var index = this._impostors.indexOf(impostor);
  36636. if (index > -1) {
  36637. var removed = this._impostors.splice(index, 1);
  36638. //Is it needed?
  36639. if (removed.length) {
  36640. //this will also remove it from the world.
  36641. removed[0].physicsBody = null;
  36642. }
  36643. }
  36644. };
  36645. /**
  36646. * Add a joint to the physics engine
  36647. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  36648. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  36649. * @param {PhysicsJoint} the joint that will connect both impostors.
  36650. */
  36651. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  36652. var impostorJoint = {
  36653. mainImpostor: mainImpostor,
  36654. connectedImpostor: connectedImpostor,
  36655. joint: joint
  36656. };
  36657. joint.physicsPlugin = this._physicsPlugin;
  36658. this._joints.push(impostorJoint);
  36659. this._physicsPlugin.generateJoint(impostorJoint);
  36660. };
  36661. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  36662. var matchingJoints = this._joints.filter(function (impostorJoint) {
  36663. return (impostorJoint.connectedImpostor === connectedImpostor
  36664. && impostorJoint.joint === joint
  36665. && impostorJoint.mainImpostor === mainImpostor);
  36666. });
  36667. if (matchingJoints.length) {
  36668. this._physicsPlugin.removeJoint(matchingJoints[0]);
  36669. }
  36670. };
  36671. /**
  36672. * Called by the scene. no need to call it.
  36673. */
  36674. PhysicsEngine.prototype._step = function (delta) {
  36675. var _this = this;
  36676. //check if any mesh has no body / requires an update
  36677. this._impostors.forEach(function (impostor) {
  36678. if (impostor.isBodyInitRequired()) {
  36679. _this._physicsPlugin.generatePhysicsBody(impostor);
  36680. }
  36681. });
  36682. if (delta > 0.1) {
  36683. delta = 0.1;
  36684. }
  36685. else if (delta <= 0) {
  36686. delta = 1.0 / 60.0;
  36687. }
  36688. this._physicsPlugin.executeStep(delta, this._impostors);
  36689. };
  36690. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  36691. return this._physicsPlugin;
  36692. };
  36693. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  36694. for (var i = 0; i < this._impostors.length; ++i) {
  36695. if (this._impostors[i].object === object) {
  36696. return this._impostors[i];
  36697. }
  36698. }
  36699. };
  36700. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  36701. for (var i = 0; i < this._impostors.length; ++i) {
  36702. if (this._impostors[i].physicsBody === body) {
  36703. return this._impostors[i];
  36704. }
  36705. }
  36706. };
  36707. return PhysicsEngine;
  36708. }());
  36709. // Statics
  36710. PhysicsEngine.Epsilon = 0.001;
  36711. BABYLON.PhysicsEngine = PhysicsEngine;
  36712. })(BABYLON || (BABYLON = {}));
  36713. //# sourceMappingURL=babylon.physicsEngine.js.map
  36714. var BABYLON;
  36715. (function (BABYLON) {
  36716. var VertexData = (function () {
  36717. function VertexData() {
  36718. }
  36719. VertexData.prototype.set = function (data, kind) {
  36720. switch (kind) {
  36721. case BABYLON.VertexBuffer.PositionKind:
  36722. this.positions = data;
  36723. break;
  36724. case BABYLON.VertexBuffer.NormalKind:
  36725. this.normals = data;
  36726. break;
  36727. case BABYLON.VertexBuffer.TangentKind:
  36728. this.tangents = data;
  36729. break;
  36730. case BABYLON.VertexBuffer.UVKind:
  36731. this.uvs = data;
  36732. break;
  36733. case BABYLON.VertexBuffer.UV2Kind:
  36734. this.uvs2 = data;
  36735. break;
  36736. case BABYLON.VertexBuffer.UV3Kind:
  36737. this.uvs3 = data;
  36738. break;
  36739. case BABYLON.VertexBuffer.UV4Kind:
  36740. this.uvs4 = data;
  36741. break;
  36742. case BABYLON.VertexBuffer.UV5Kind:
  36743. this.uvs5 = data;
  36744. break;
  36745. case BABYLON.VertexBuffer.UV6Kind:
  36746. this.uvs6 = data;
  36747. break;
  36748. case BABYLON.VertexBuffer.ColorKind:
  36749. this.colors = data;
  36750. break;
  36751. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36752. this.matricesIndices = data;
  36753. break;
  36754. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36755. this.matricesWeights = data;
  36756. break;
  36757. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36758. this.matricesIndicesExtra = data;
  36759. break;
  36760. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36761. this.matricesWeightsExtra = data;
  36762. break;
  36763. }
  36764. };
  36765. /**
  36766. * Associates the vertexData to the passed Mesh.
  36767. * Sets it as updatable or not (default `false`).
  36768. * Returns the VertexData.
  36769. */
  36770. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36771. this._applyTo(mesh, updatable);
  36772. return this;
  36773. };
  36774. /**
  36775. * Associates the vertexData to the passed Geometry.
  36776. * Sets it as updatable or not (default `false`).
  36777. * Returns the VertexData.
  36778. */
  36779. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36780. this._applyTo(geometry, updatable);
  36781. return this;
  36782. };
  36783. /**
  36784. * Updates the associated mesh.
  36785. * Returns the VertexData.
  36786. */
  36787. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36788. this._update(mesh);
  36789. return this;
  36790. };
  36791. /**
  36792. * Updates the associated geometry.
  36793. * Returns the VertexData.
  36794. */
  36795. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36796. this._update(geometry);
  36797. return this;
  36798. };
  36799. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36800. if (this.positions) {
  36801. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36802. }
  36803. if (this.normals) {
  36804. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36805. }
  36806. if (this.tangents) {
  36807. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36808. }
  36809. if (this.uvs) {
  36810. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36811. }
  36812. if (this.uvs2) {
  36813. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36814. }
  36815. if (this.uvs3) {
  36816. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36817. }
  36818. if (this.uvs4) {
  36819. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36820. }
  36821. if (this.uvs5) {
  36822. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36823. }
  36824. if (this.uvs6) {
  36825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36826. }
  36827. if (this.colors) {
  36828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36829. }
  36830. if (this.matricesIndices) {
  36831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36832. }
  36833. if (this.matricesWeights) {
  36834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36835. }
  36836. if (this.matricesIndicesExtra) {
  36837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36838. }
  36839. if (this.matricesWeightsExtra) {
  36840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36841. }
  36842. if (this.indices) {
  36843. meshOrGeometry.setIndices(this.indices);
  36844. }
  36845. return this;
  36846. };
  36847. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36848. if (this.positions) {
  36849. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36850. }
  36851. if (this.normals) {
  36852. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36853. }
  36854. if (this.tangents) {
  36855. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36856. }
  36857. if (this.uvs) {
  36858. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36859. }
  36860. if (this.uvs2) {
  36861. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36862. }
  36863. if (this.uvs3) {
  36864. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36865. }
  36866. if (this.uvs4) {
  36867. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36868. }
  36869. if (this.uvs5) {
  36870. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36871. }
  36872. if (this.uvs6) {
  36873. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36874. }
  36875. if (this.colors) {
  36876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36877. }
  36878. if (this.matricesIndices) {
  36879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36880. }
  36881. if (this.matricesWeights) {
  36882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36883. }
  36884. if (this.matricesIndicesExtra) {
  36885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36886. }
  36887. if (this.matricesWeightsExtra) {
  36888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36889. }
  36890. if (this.indices) {
  36891. meshOrGeometry.setIndices(this.indices);
  36892. }
  36893. return this;
  36894. };
  36895. /**
  36896. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  36897. * Returns the VertexData.
  36898. */
  36899. VertexData.prototype.transform = function (matrix) {
  36900. var transformed = BABYLON.Vector3.Zero();
  36901. var index;
  36902. if (this.positions) {
  36903. var position = BABYLON.Vector3.Zero();
  36904. for (index = 0; index < this.positions.length; index += 3) {
  36905. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36906. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36907. this.positions[index] = transformed.x;
  36908. this.positions[index + 1] = transformed.y;
  36909. this.positions[index + 2] = transformed.z;
  36910. }
  36911. }
  36912. if (this.normals) {
  36913. var normal = BABYLON.Vector3.Zero();
  36914. for (index = 0; index < this.normals.length; index += 3) {
  36915. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36916. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36917. this.normals[index] = transformed.x;
  36918. this.normals[index + 1] = transformed.y;
  36919. this.normals[index + 2] = transformed.z;
  36920. }
  36921. }
  36922. if (this.tangents) {
  36923. var tangent = BABYLON.Vector4.Zero();
  36924. var tangentTransformed = BABYLON.Vector4.Zero();
  36925. for (index = 0; index < this.tangents.length; index += 4) {
  36926. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36927. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36928. this.tangents[index] = tangentTransformed.x;
  36929. this.tangents[index + 1] = tangentTransformed.y;
  36930. this.tangents[index + 2] = tangentTransformed.z;
  36931. this.tangents[index + 3] = tangentTransformed.w;
  36932. }
  36933. }
  36934. return this;
  36935. };
  36936. /**
  36937. * Merges the passed VertexData into the current one.
  36938. * Returns the modified VertexData.
  36939. */
  36940. VertexData.prototype.merge = function (other) {
  36941. if (other.indices) {
  36942. if (!this.indices) {
  36943. this.indices = [];
  36944. }
  36945. var offset = this.positions ? this.positions.length / 3 : 0;
  36946. for (var index = 0; index < other.indices.length; index++) {
  36947. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36948. this.indices.push(other.indices[index] + offset);
  36949. }
  36950. }
  36951. this.positions = this._mergeElement(this.positions, other.positions);
  36952. this.normals = this._mergeElement(this.normals, other.normals);
  36953. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36954. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36955. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36956. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36957. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36958. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36959. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36960. this.colors = this._mergeElement(this.colors, other.colors);
  36961. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36962. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36963. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36964. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36965. return this;
  36966. };
  36967. VertexData.prototype._mergeElement = function (source, other) {
  36968. if (!other)
  36969. return source;
  36970. if (!source)
  36971. return other;
  36972. var len = other.length + source.length;
  36973. var isSrcTypedArray = source instanceof Float32Array;
  36974. var isOthTypedArray = other instanceof Float32Array;
  36975. // use non-loop method when the source is Float32Array
  36976. if (isSrcTypedArray) {
  36977. var ret32 = new Float32Array(len);
  36978. ret32.set(source);
  36979. ret32.set(other, source.length);
  36980. return ret32;
  36981. }
  36982. else if (!isOthTypedArray) {
  36983. return source.concat(other);
  36984. }
  36985. else {
  36986. var ret = source.slice(0); // copy source to a separate array
  36987. for (var i = 0, len = other.length; i < len; i++) {
  36988. ret.push(other[i]);
  36989. }
  36990. return ret;
  36991. }
  36992. };
  36993. /**
  36994. * Serializes the VertexData.
  36995. * Returns a serialized object.
  36996. */
  36997. VertexData.prototype.serialize = function () {
  36998. var serializationObject = this.serialize();
  36999. if (this.positions) {
  37000. serializationObject.positions = this.positions;
  37001. }
  37002. if (this.normals) {
  37003. serializationObject.normals = this.normals;
  37004. }
  37005. if (this.tangents) {
  37006. serializationObject.tangents = this.tangents;
  37007. }
  37008. if (this.uvs) {
  37009. serializationObject.uvs = this.uvs;
  37010. }
  37011. if (this.uvs2) {
  37012. serializationObject.uvs2 = this.uvs2;
  37013. }
  37014. if (this.uvs3) {
  37015. serializationObject.uvs3 = this.uvs3;
  37016. }
  37017. if (this.uvs4) {
  37018. serializationObject.uvs4 = this.uvs4;
  37019. }
  37020. if (this.uvs5) {
  37021. serializationObject.uvs5 = this.uvs5;
  37022. }
  37023. if (this.uvs6) {
  37024. serializationObject.uvs6 = this.uvs6;
  37025. }
  37026. if (this.colors) {
  37027. serializationObject.colors = this.colors;
  37028. }
  37029. if (this.matricesIndices) {
  37030. serializationObject.matricesIndices = this.matricesIndices;
  37031. serializationObject.matricesIndices._isExpanded = true;
  37032. }
  37033. if (this.matricesWeights) {
  37034. serializationObject.matricesWeights = this.matricesWeights;
  37035. }
  37036. if (this.matricesIndicesExtra) {
  37037. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37038. serializationObject.matricesIndicesExtra._isExpanded = true;
  37039. }
  37040. if (this.matricesWeightsExtra) {
  37041. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37042. }
  37043. serializationObject.indices = this.indices;
  37044. return serializationObject;
  37045. };
  37046. // Statics
  37047. /**
  37048. * Returns the object VertexData associated to the passed mesh.
  37049. */
  37050. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  37051. return VertexData._ExtractFrom(mesh, copyWhenShared);
  37052. };
  37053. /**
  37054. * Returns the object VertexData associated to the passed geometry.
  37055. */
  37056. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  37057. return VertexData._ExtractFrom(geometry, copyWhenShared);
  37058. };
  37059. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  37060. var result = new VertexData();
  37061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37062. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  37063. }
  37064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37065. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  37066. }
  37067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37068. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  37069. }
  37070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37071. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  37072. }
  37073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37074. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  37075. }
  37076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37077. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  37078. }
  37079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37080. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  37081. }
  37082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37083. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  37084. }
  37085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37086. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  37087. }
  37088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37089. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  37090. }
  37091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37092. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  37093. }
  37094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37095. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  37096. }
  37097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37098. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  37099. }
  37100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37101. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  37102. }
  37103. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37104. return result;
  37105. };
  37106. /**
  37107. * Creates the vertexData of the Ribbon.
  37108. */
  37109. VertexData.CreateRibbon = function (options) {
  37110. var pathArray = options.pathArray;
  37111. var closeArray = options.closeArray || false;
  37112. var closePath = options.closePath || false;
  37113. var invertUV = options.invertUV || false;
  37114. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37115. var offset = options.offset || defaultOffset;
  37116. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37117. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37118. var customUV = options.uvs;
  37119. var customColors = options.colors;
  37120. var positions = [];
  37121. var indices = [];
  37122. var normals = [];
  37123. var uvs = [];
  37124. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37125. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37126. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37127. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37128. var minlg; // minimal length among all paths from pathArray
  37129. var lg = []; // array of path lengths : nb of vertex per path
  37130. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37131. var p; // path iterator
  37132. var i; // point iterator
  37133. var j; // point iterator
  37134. // if single path in pathArray
  37135. if (pathArray.length < 2) {
  37136. var ar1 = [];
  37137. var ar2 = [];
  37138. for (i = 0; i < pathArray[0].length - offset; i++) {
  37139. ar1.push(pathArray[0][i]);
  37140. ar2.push(pathArray[0][i + offset]);
  37141. }
  37142. pathArray = [ar1, ar2];
  37143. }
  37144. // positions and horizontal distances (u)
  37145. var idc = 0;
  37146. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37147. var path;
  37148. var l;
  37149. minlg = pathArray[0].length;
  37150. var vectlg;
  37151. var dist;
  37152. for (p = 0; p < pathArray.length; p++) {
  37153. uTotalDistance[p] = 0;
  37154. us[p] = [0];
  37155. path = pathArray[p];
  37156. l = path.length;
  37157. minlg = (minlg < l) ? minlg : l;
  37158. j = 0;
  37159. while (j < l) {
  37160. positions.push(path[j].x, path[j].y, path[j].z);
  37161. if (j > 0) {
  37162. vectlg = path[j].subtract(path[j - 1]).length();
  37163. dist = vectlg + uTotalDistance[p];
  37164. us[p].push(dist);
  37165. uTotalDistance[p] = dist;
  37166. }
  37167. j++;
  37168. }
  37169. if (closePath) {
  37170. j--;
  37171. positions.push(path[0].x, path[0].y, path[0].z);
  37172. vectlg = path[j].subtract(path[0]).length();
  37173. dist = vectlg + uTotalDistance[p];
  37174. us[p].push(dist);
  37175. uTotalDistance[p] = dist;
  37176. }
  37177. lg[p] = l + closePathCorr;
  37178. idx[p] = idc;
  37179. idc += (l + closePathCorr);
  37180. }
  37181. // vertical distances (v)
  37182. var path1;
  37183. var path2;
  37184. var vertex1;
  37185. var vertex2;
  37186. for (i = 0; i < minlg + closePathCorr; i++) {
  37187. vTotalDistance[i] = 0;
  37188. vs[i] = [0];
  37189. for (p = 0; p < pathArray.length - 1; p++) {
  37190. path1 = pathArray[p];
  37191. path2 = pathArray[p + 1];
  37192. if (i === minlg) {
  37193. vertex1 = path1[0];
  37194. vertex2 = path2[0];
  37195. }
  37196. else {
  37197. vertex1 = path1[i];
  37198. vertex2 = path2[i];
  37199. }
  37200. vectlg = vertex2.subtract(vertex1).length();
  37201. dist = vectlg + vTotalDistance[i];
  37202. vs[i].push(dist);
  37203. vTotalDistance[i] = dist;
  37204. }
  37205. if (closeArray) {
  37206. path1 = pathArray[p];
  37207. path2 = pathArray[0];
  37208. if (i === minlg) {
  37209. vertex2 = path2[0];
  37210. }
  37211. vectlg = vertex2.subtract(vertex1).length();
  37212. dist = vectlg + vTotalDistance[i];
  37213. vTotalDistance[i] = dist;
  37214. }
  37215. }
  37216. // uvs
  37217. var u;
  37218. var v;
  37219. if (customUV) {
  37220. for (p = 0; p < customUV.length; p++) {
  37221. uvs.push(customUV[p].x, customUV[p].y);
  37222. }
  37223. }
  37224. else {
  37225. for (p = 0; p < pathArray.length; p++) {
  37226. for (i = 0; i < minlg + closePathCorr; i++) {
  37227. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37228. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37229. if (invertUV) {
  37230. uvs.push(v, u);
  37231. }
  37232. else {
  37233. uvs.push(u, v);
  37234. }
  37235. }
  37236. }
  37237. }
  37238. // indices
  37239. p = 0; // path index
  37240. var pi = 0; // positions array index
  37241. var l1 = lg[p] - 1; // path1 length
  37242. var l2 = lg[p + 1] - 1; // path2 length
  37243. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37244. var shft = idx[1] - idx[0]; // shift
  37245. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37246. while (pi <= min && p < path1nb) {
  37247. // 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
  37248. indices.push(pi, pi + shft, pi + 1);
  37249. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37250. pi += 1;
  37251. if (pi === min) {
  37252. p++;
  37253. if (p === lg.length - 1) {
  37254. shft = idx[0] - idx[p];
  37255. l1 = lg[p] - 1;
  37256. l2 = lg[0] - 1;
  37257. }
  37258. else {
  37259. shft = idx[p + 1] - idx[p];
  37260. l1 = lg[p] - 1;
  37261. l2 = lg[p + 1] - 1;
  37262. }
  37263. pi = idx[p];
  37264. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37265. }
  37266. }
  37267. // normals
  37268. VertexData.ComputeNormals(positions, indices, normals);
  37269. if (closePath) {
  37270. var indexFirst = 0;
  37271. var indexLast = 0;
  37272. for (p = 0; p < pathArray.length; p++) {
  37273. indexFirst = idx[p] * 3;
  37274. if (p + 1 < pathArray.length) {
  37275. indexLast = (idx[p + 1] - 1) * 3;
  37276. }
  37277. else {
  37278. indexLast = normals.length - 3;
  37279. }
  37280. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37281. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37282. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37283. normals[indexLast] = normals[indexFirst];
  37284. normals[indexLast + 1] = normals[indexFirst + 1];
  37285. normals[indexLast + 2] = normals[indexFirst + 2];
  37286. }
  37287. }
  37288. // sides
  37289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37290. // Colors
  37291. if (customColors) {
  37292. var colors = new Float32Array(customColors.length * 4);
  37293. for (var c = 0; c < customColors.length; c++) {
  37294. colors[c * 4] = customColors[c].r;
  37295. colors[c * 4 + 1] = customColors[c].g;
  37296. colors[c * 4 + 2] = customColors[c].b;
  37297. colors[c * 4 + 3] = customColors[c].a;
  37298. }
  37299. }
  37300. // Result
  37301. var vertexData = new VertexData();
  37302. var positions32 = new Float32Array(positions);
  37303. var normals32 = new Float32Array(normals);
  37304. var uvs32 = new Float32Array(uvs);
  37305. vertexData.indices = indices;
  37306. vertexData.positions = positions32;
  37307. vertexData.normals = normals32;
  37308. vertexData.uvs = uvs32;
  37309. if (customColors) {
  37310. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37311. }
  37312. if (closePath) {
  37313. vertexData._idx = idx;
  37314. }
  37315. return vertexData;
  37316. };
  37317. /**
  37318. * Creates the VertexData of the Box.
  37319. */
  37320. VertexData.CreateBox = function (options) {
  37321. var normalsSource = [
  37322. new BABYLON.Vector3(0, 0, 1),
  37323. new BABYLON.Vector3(0, 0, -1),
  37324. new BABYLON.Vector3(1, 0, 0),
  37325. new BABYLON.Vector3(-1, 0, 0),
  37326. new BABYLON.Vector3(0, 1, 0),
  37327. new BABYLON.Vector3(0, -1, 0)
  37328. ];
  37329. var indices = [];
  37330. var positions = [];
  37331. var normals = [];
  37332. var uvs = [];
  37333. var width = options.width || options.size || 1;
  37334. var height = options.height || options.size || 1;
  37335. var depth = options.depth || options.size || 1;
  37336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37337. var faceUV = options.faceUV || new Array(6);
  37338. var faceColors = options.faceColors;
  37339. var colors = [];
  37340. // default face colors and UV if undefined
  37341. for (var f = 0; f < 6; f++) {
  37342. if (faceUV[f] === undefined) {
  37343. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37344. }
  37345. if (faceColors && faceColors[f] === undefined) {
  37346. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37347. }
  37348. }
  37349. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37350. // Create each face in turn.
  37351. for (var index = 0; index < normalsSource.length; index++) {
  37352. var normal = normalsSource[index];
  37353. // Get two vectors perpendicular to the face normal and to each other.
  37354. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37355. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37356. // Six indices (two triangles) per face.
  37357. var verticesLength = positions.length / 3;
  37358. indices.push(verticesLength);
  37359. indices.push(verticesLength + 1);
  37360. indices.push(verticesLength + 2);
  37361. indices.push(verticesLength);
  37362. indices.push(verticesLength + 2);
  37363. indices.push(verticesLength + 3);
  37364. // Four vertices per face.
  37365. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37366. positions.push(vertex.x, vertex.y, vertex.z);
  37367. normals.push(normal.x, normal.y, normal.z);
  37368. uvs.push(faceUV[index].z, faceUV[index].w);
  37369. if (faceColors) {
  37370. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37371. }
  37372. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37373. positions.push(vertex.x, vertex.y, vertex.z);
  37374. normals.push(normal.x, normal.y, normal.z);
  37375. uvs.push(faceUV[index].x, faceUV[index].w);
  37376. if (faceColors) {
  37377. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37378. }
  37379. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37380. positions.push(vertex.x, vertex.y, vertex.z);
  37381. normals.push(normal.x, normal.y, normal.z);
  37382. uvs.push(faceUV[index].x, faceUV[index].y);
  37383. if (faceColors) {
  37384. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37385. }
  37386. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37387. positions.push(vertex.x, vertex.y, vertex.z);
  37388. normals.push(normal.x, normal.y, normal.z);
  37389. uvs.push(faceUV[index].z, faceUV[index].y);
  37390. if (faceColors) {
  37391. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37392. }
  37393. }
  37394. // sides
  37395. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37396. // Result
  37397. var vertexData = new VertexData();
  37398. vertexData.indices = indices;
  37399. vertexData.positions = positions;
  37400. vertexData.normals = normals;
  37401. vertexData.uvs = uvs;
  37402. if (faceColors) {
  37403. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37404. vertexData.colors = totalColors;
  37405. }
  37406. return vertexData;
  37407. };
  37408. /**
  37409. * Creates the VertexData of the Sphere.
  37410. */
  37411. VertexData.CreateSphere = function (options) {
  37412. var segments = options.segments || 32;
  37413. var diameterX = options.diameterX || options.diameter || 1;
  37414. var diameterY = options.diameterY || options.diameter || 1;
  37415. var diameterZ = options.diameterZ || options.diameter || 1;
  37416. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37417. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37418. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37419. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37420. var totalZRotationSteps = 2 + segments;
  37421. var totalYRotationSteps = 2 * totalZRotationSteps;
  37422. var indices = [];
  37423. var positions = [];
  37424. var normals = [];
  37425. var uvs = [];
  37426. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37427. var normalizedZ = zRotationStep / totalZRotationSteps;
  37428. var angleZ = normalizedZ * Math.PI * slice;
  37429. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37430. var normalizedY = yRotationStep / totalYRotationSteps;
  37431. var angleY = normalizedY * Math.PI * 2 * arc;
  37432. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37433. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37434. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37435. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37436. var vertex = complete.multiply(radius);
  37437. var normal = complete.divide(radius).normalize();
  37438. positions.push(vertex.x, vertex.y, vertex.z);
  37439. normals.push(normal.x, normal.y, normal.z);
  37440. uvs.push(normalizedY, normalizedZ);
  37441. }
  37442. if (zRotationStep > 0) {
  37443. var verticesCount = positions.length / 3;
  37444. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37445. indices.push((firstIndex));
  37446. indices.push((firstIndex + 1));
  37447. indices.push(firstIndex + totalYRotationSteps + 1);
  37448. indices.push((firstIndex + totalYRotationSteps + 1));
  37449. indices.push((firstIndex + 1));
  37450. indices.push((firstIndex + totalYRotationSteps + 2));
  37451. }
  37452. }
  37453. }
  37454. // Sides
  37455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37456. // Result
  37457. var vertexData = new VertexData();
  37458. vertexData.indices = indices;
  37459. vertexData.positions = positions;
  37460. vertexData.normals = normals;
  37461. vertexData.uvs = uvs;
  37462. return vertexData;
  37463. };
  37464. /**
  37465. * Creates the VertexData of the Cylinder or Cone.
  37466. */
  37467. VertexData.CreateCylinder = function (options) {
  37468. var height = options.height || 2;
  37469. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37470. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37471. var tessellation = options.tessellation || 24;
  37472. var subdivisions = options.subdivisions || 1;
  37473. var hasRings = options.hasRings;
  37474. var enclose = options.enclose;
  37475. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37476. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37477. var faceUV = options.faceUV || new Array(3);
  37478. var faceColors = options.faceColors;
  37479. // default face colors and UV if undefined
  37480. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37481. var ringNb = (hasRings) ? subdivisions : 1;
  37482. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37483. var f;
  37484. for (f = 0; f < surfaceNb; f++) {
  37485. if (faceColors && faceColors[f] === undefined) {
  37486. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37487. }
  37488. }
  37489. for (f = 0; f < surfaceNb; f++) {
  37490. if (faceUV && faceUV[f] === undefined) {
  37491. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37492. }
  37493. }
  37494. var indices = [];
  37495. var positions = [];
  37496. var normals = [];
  37497. var uvs = [];
  37498. var colors = [];
  37499. var angle_step = Math.PI * 2 * arc / tessellation;
  37500. var angle;
  37501. var h;
  37502. var radius;
  37503. var tan = (diameterBottom - diameterTop) / 2 / height;
  37504. var ringVertex = BABYLON.Vector3.Zero();
  37505. var ringNormal = BABYLON.Vector3.Zero();
  37506. var ringFirstVertex = BABYLON.Vector3.Zero();
  37507. var ringFirstNormal = BABYLON.Vector3.Zero();
  37508. var quadNormal = BABYLON.Vector3.Zero();
  37509. var Y = BABYLON.Axis.Y;
  37510. // positions, normals, uvs
  37511. var i;
  37512. var j;
  37513. var r;
  37514. var ringIdx = 1;
  37515. var s = 1; // surface index
  37516. var cs = 0;
  37517. var v = 0;
  37518. for (i = 0; i <= subdivisions; i++) {
  37519. h = i / subdivisions;
  37520. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37521. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37522. for (r = 0; r < ringIdx; r++) {
  37523. if (hasRings) {
  37524. s += r;
  37525. }
  37526. if (enclose) {
  37527. s += 2 * r;
  37528. }
  37529. for (j = 0; j <= tessellation; j++) {
  37530. angle = j * angle_step;
  37531. // position
  37532. ringVertex.x = Math.cos(-angle) * radius;
  37533. ringVertex.y = -height / 2 + h * height;
  37534. ringVertex.z = Math.sin(-angle) * radius;
  37535. // normal
  37536. if (diameterTop === 0 && i === subdivisions) {
  37537. // if no top cap, reuse former normals
  37538. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37539. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37540. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37541. }
  37542. else {
  37543. ringNormal.x = ringVertex.x;
  37544. ringNormal.z = ringVertex.z;
  37545. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37546. ringNormal.normalize();
  37547. }
  37548. // keep first ring vertex values for enclose
  37549. if (j === 0) {
  37550. ringFirstVertex.copyFrom(ringVertex);
  37551. ringFirstNormal.copyFrom(ringNormal);
  37552. }
  37553. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37554. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37555. if (hasRings) {
  37556. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37557. }
  37558. else {
  37559. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37560. }
  37561. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37562. if (faceColors) {
  37563. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37564. }
  37565. }
  37566. // if enclose, add four vertices and their dedicated normals
  37567. if (arc !== 1 && enclose) {
  37568. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37569. positions.push(0, ringVertex.y, 0);
  37570. positions.push(0, ringVertex.y, 0);
  37571. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37572. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37573. quadNormal.normalize();
  37574. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37575. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37576. quadNormal.normalize();
  37577. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37578. if (hasRings) {
  37579. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37580. }
  37581. else {
  37582. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37583. }
  37584. uvs.push(faceUV[s + 1].x, v);
  37585. uvs.push(faceUV[s + 1].z, v);
  37586. if (hasRings) {
  37587. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37588. }
  37589. else {
  37590. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37591. }
  37592. uvs.push(faceUV[s + 2].x, v);
  37593. uvs.push(faceUV[s + 2].z, v);
  37594. if (faceColors) {
  37595. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37596. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37597. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37598. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37599. }
  37600. }
  37601. if (cs !== s) {
  37602. cs = s;
  37603. }
  37604. }
  37605. }
  37606. // indices
  37607. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37608. var s;
  37609. i = 0;
  37610. for (s = 0; s < subdivisions; s++) {
  37611. for (j = 0; j < tessellation; j++) {
  37612. var i0 = i * (e + 1) + j;
  37613. var i1 = (i + 1) * (e + 1) + j;
  37614. var i2 = i * (e + 1) + (j + 1);
  37615. var i3 = (i + 1) * (e + 1) + (j + 1);
  37616. indices.push(i0, i1, i2);
  37617. indices.push(i3, i2, i1);
  37618. }
  37619. if (arc !== 1 && enclose) {
  37620. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37621. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37622. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37623. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37624. }
  37625. i = (hasRings) ? (i + 2) : (i + 1);
  37626. }
  37627. // Caps
  37628. var createCylinderCap = function (isTop) {
  37629. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37630. if (radius === 0) {
  37631. return;
  37632. }
  37633. // Cap positions, normals & uvs
  37634. var angle;
  37635. var circleVector;
  37636. var i;
  37637. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37638. var c;
  37639. if (faceColors) {
  37640. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37641. }
  37642. // cap center
  37643. var vbase = positions.length / 3;
  37644. var offset = isTop ? height / 2 : -height / 2;
  37645. var center = new BABYLON.Vector3(0, offset, 0);
  37646. positions.push(center.x, center.y, center.z);
  37647. normals.push(0, isTop ? 1 : -1, 0);
  37648. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37649. if (faceColors) {
  37650. colors.push(c.r, c.g, c.b, c.a);
  37651. }
  37652. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37653. for (i = 0; i <= tessellation; i++) {
  37654. angle = Math.PI * 2 * i * arc / tessellation;
  37655. var cos = Math.cos(-angle);
  37656. var sin = Math.sin(-angle);
  37657. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37658. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37659. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37660. normals.push(0, isTop ? 1 : -1, 0);
  37661. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37662. if (faceColors) {
  37663. colors.push(c.r, c.g, c.b, c.a);
  37664. }
  37665. }
  37666. // Cap indices
  37667. for (i = 0; i < tessellation; i++) {
  37668. if (!isTop) {
  37669. indices.push(vbase);
  37670. indices.push(vbase + (i + 1));
  37671. indices.push(vbase + (i + 2));
  37672. }
  37673. else {
  37674. indices.push(vbase);
  37675. indices.push(vbase + (i + 2));
  37676. indices.push(vbase + (i + 1));
  37677. }
  37678. }
  37679. };
  37680. // add caps to geometry
  37681. createCylinderCap(false);
  37682. createCylinderCap(true);
  37683. // Sides
  37684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37685. var vertexData = new VertexData();
  37686. vertexData.indices = indices;
  37687. vertexData.positions = positions;
  37688. vertexData.normals = normals;
  37689. vertexData.uvs = uvs;
  37690. if (faceColors) {
  37691. vertexData.colors = colors;
  37692. }
  37693. return vertexData;
  37694. };
  37695. /**
  37696. * Creates the VertexData of the Torus.
  37697. */
  37698. VertexData.CreateTorus = function (options) {
  37699. var indices = [];
  37700. var positions = [];
  37701. var normals = [];
  37702. var uvs = [];
  37703. var diameter = options.diameter || 1;
  37704. var thickness = options.thickness || 0.5;
  37705. var tessellation = options.tessellation || 16;
  37706. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37707. var stride = tessellation + 1;
  37708. for (var i = 0; i <= tessellation; i++) {
  37709. var u = i / tessellation;
  37710. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37711. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37712. for (var j = 0; j <= tessellation; j++) {
  37713. var v = 1 - j / tessellation;
  37714. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37715. var dx = Math.cos(innerAngle);
  37716. var dy = Math.sin(innerAngle);
  37717. // Create a vertex.
  37718. var normal = new BABYLON.Vector3(dx, dy, 0);
  37719. var position = normal.scale(thickness / 2);
  37720. var textureCoordinate = new BABYLON.Vector2(u, v);
  37721. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37722. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37723. positions.push(position.x, position.y, position.z);
  37724. normals.push(normal.x, normal.y, normal.z);
  37725. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37726. // And create indices for two triangles.
  37727. var nextI = (i + 1) % stride;
  37728. var nextJ = (j + 1) % stride;
  37729. indices.push(i * stride + j);
  37730. indices.push(i * stride + nextJ);
  37731. indices.push(nextI * stride + j);
  37732. indices.push(i * stride + nextJ);
  37733. indices.push(nextI * stride + nextJ);
  37734. indices.push(nextI * stride + j);
  37735. }
  37736. }
  37737. // Sides
  37738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37739. // Result
  37740. var vertexData = new VertexData();
  37741. vertexData.indices = indices;
  37742. vertexData.positions = positions;
  37743. vertexData.normals = normals;
  37744. vertexData.uvs = uvs;
  37745. return vertexData;
  37746. };
  37747. /**
  37748. * Creates the VertexData of the LineSystem.
  37749. */
  37750. VertexData.CreateLineSystem = function (options) {
  37751. var indices = [];
  37752. var positions = [];
  37753. var lines = options.lines;
  37754. var idx = 0;
  37755. for (var l = 0; l < lines.length; l++) {
  37756. var points = lines[l];
  37757. for (var index = 0; index < points.length; index++) {
  37758. positions.push(points[index].x, points[index].y, points[index].z);
  37759. if (index > 0) {
  37760. indices.push(idx - 1);
  37761. indices.push(idx);
  37762. }
  37763. idx++;
  37764. }
  37765. }
  37766. var vertexData = new VertexData();
  37767. vertexData.indices = indices;
  37768. vertexData.positions = positions;
  37769. return vertexData;
  37770. };
  37771. /**
  37772. * Create the VertexData of the DashedLines.
  37773. */
  37774. VertexData.CreateDashedLines = function (options) {
  37775. var dashSize = options.dashSize || 3;
  37776. var gapSize = options.gapSize || 1;
  37777. var dashNb = options.dashNb || 200;
  37778. var points = options.points;
  37779. var positions = new Array();
  37780. var indices = new Array();
  37781. var curvect = BABYLON.Vector3.Zero();
  37782. var lg = 0;
  37783. var nb = 0;
  37784. var shft = 0;
  37785. var dashshft = 0;
  37786. var curshft = 0;
  37787. var idx = 0;
  37788. var i = 0;
  37789. for (i = 0; i < points.length - 1; i++) {
  37790. points[i + 1].subtractToRef(points[i], curvect);
  37791. lg += curvect.length();
  37792. }
  37793. shft = lg / dashNb;
  37794. dashshft = dashSize * shft / (dashSize + gapSize);
  37795. for (i = 0; i < points.length - 1; i++) {
  37796. points[i + 1].subtractToRef(points[i], curvect);
  37797. nb = Math.floor(curvect.length() / shft);
  37798. curvect.normalize();
  37799. for (var j = 0; j < nb; j++) {
  37800. curshft = shft * j;
  37801. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37802. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37803. indices.push(idx, idx + 1);
  37804. idx += 2;
  37805. }
  37806. }
  37807. // Result
  37808. var vertexData = new VertexData();
  37809. vertexData.positions = positions;
  37810. vertexData.indices = indices;
  37811. return vertexData;
  37812. };
  37813. /**
  37814. * Creates the VertexData of the Ground.
  37815. */
  37816. VertexData.CreateGround = function (options) {
  37817. var indices = [];
  37818. var positions = [];
  37819. var normals = [];
  37820. var uvs = [];
  37821. var row, col;
  37822. var width = options.width || 1;
  37823. var height = options.height || 1;
  37824. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37825. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37826. for (row = 0; row <= subdivisionsY; row++) {
  37827. for (col = 0; col <= subdivisionsX; col++) {
  37828. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37829. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37830. positions.push(position.x, position.y, position.z);
  37831. normals.push(normal.x, normal.y, normal.z);
  37832. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37833. }
  37834. }
  37835. for (row = 0; row < subdivisionsY; row++) {
  37836. for (col = 0; col < subdivisionsX; col++) {
  37837. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37838. indices.push(col + 1 + row * (subdivisionsX + 1));
  37839. indices.push(col + row * (subdivisionsX + 1));
  37840. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37841. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37842. indices.push(col + row * (subdivisionsX + 1));
  37843. }
  37844. }
  37845. // Result
  37846. var vertexData = new VertexData();
  37847. vertexData.indices = indices;
  37848. vertexData.positions = positions;
  37849. vertexData.normals = normals;
  37850. vertexData.uvs = uvs;
  37851. return vertexData;
  37852. };
  37853. /**
  37854. * Creates the VertexData of the TiledGround.
  37855. */
  37856. VertexData.CreateTiledGround = function (options) {
  37857. var xmin = options.xmin || -1.0;
  37858. var zmin = options.zmin || -1.0;
  37859. var xmax = options.xmax || 1.0;
  37860. var zmax = options.zmax || 1.0;
  37861. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37862. var precision = options.precision || { w: 1, h: 1 };
  37863. var indices = [];
  37864. var positions = [];
  37865. var normals = [];
  37866. var uvs = [];
  37867. var row, col, tileRow, tileCol;
  37868. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37869. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37870. precision.w = (precision.w < 1) ? 1 : precision.w;
  37871. precision.h = (precision.h < 1) ? 1 : precision.h;
  37872. var tileSize = {
  37873. 'w': (xmax - xmin) / subdivisions.w,
  37874. 'h': (zmax - zmin) / subdivisions.h
  37875. };
  37876. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37877. // Indices
  37878. var base = positions.length / 3;
  37879. var rowLength = precision.w + 1;
  37880. for (row = 0; row < precision.h; row++) {
  37881. for (col = 0; col < precision.w; col++) {
  37882. var square = [
  37883. base + col + row * rowLength,
  37884. base + (col + 1) + row * rowLength,
  37885. base + (col + 1) + (row + 1) * rowLength,
  37886. base + col + (row + 1) * rowLength
  37887. ];
  37888. indices.push(square[1]);
  37889. indices.push(square[2]);
  37890. indices.push(square[3]);
  37891. indices.push(square[0]);
  37892. indices.push(square[1]);
  37893. indices.push(square[3]);
  37894. }
  37895. }
  37896. // Position, normals and uvs
  37897. var position = BABYLON.Vector3.Zero();
  37898. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37899. for (row = 0; row <= precision.h; row++) {
  37900. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37901. for (col = 0; col <= precision.w; col++) {
  37902. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37903. position.y = 0;
  37904. positions.push(position.x, position.y, position.z);
  37905. normals.push(normal.x, normal.y, normal.z);
  37906. uvs.push(col / precision.w, row / precision.h);
  37907. }
  37908. }
  37909. }
  37910. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37911. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37912. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37913. }
  37914. }
  37915. // Result
  37916. var vertexData = new VertexData();
  37917. vertexData.indices = indices;
  37918. vertexData.positions = positions;
  37919. vertexData.normals = normals;
  37920. vertexData.uvs = uvs;
  37921. return vertexData;
  37922. };
  37923. /**
  37924. * Creates the VertexData of the Ground designed from a heightmap.
  37925. */
  37926. VertexData.CreateGroundFromHeightMap = function (options) {
  37927. var indices = [];
  37928. var positions = [];
  37929. var normals = [];
  37930. var uvs = [];
  37931. var row, col;
  37932. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37933. // Vertices
  37934. for (row = 0; row <= options.subdivisions; row++) {
  37935. for (col = 0; col <= options.subdivisions; col++) {
  37936. 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));
  37937. // Compute height
  37938. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37939. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37940. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37941. var r = options.buffer[pos] / 255.0;
  37942. var g = options.buffer[pos + 1] / 255.0;
  37943. var b = options.buffer[pos + 2] / 255.0;
  37944. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37945. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37946. // Add vertex
  37947. positions.push(position.x, position.y, position.z);
  37948. normals.push(0, 0, 0);
  37949. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37950. }
  37951. }
  37952. // Indices
  37953. for (row = 0; row < options.subdivisions; row++) {
  37954. for (col = 0; col < options.subdivisions; col++) {
  37955. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37956. indices.push(col + 1 + row * (options.subdivisions + 1));
  37957. indices.push(col + row * (options.subdivisions + 1));
  37958. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37959. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37960. indices.push(col + row * (options.subdivisions + 1));
  37961. }
  37962. }
  37963. // Normals
  37964. VertexData.ComputeNormals(positions, indices, normals);
  37965. // Result
  37966. var vertexData = new VertexData();
  37967. vertexData.indices = indices;
  37968. vertexData.positions = positions;
  37969. vertexData.normals = normals;
  37970. vertexData.uvs = uvs;
  37971. return vertexData;
  37972. };
  37973. /**
  37974. * Creates the VertexData of the Plane.
  37975. */
  37976. VertexData.CreatePlane = function (options) {
  37977. var indices = [];
  37978. var positions = [];
  37979. var normals = [];
  37980. var uvs = [];
  37981. var width = options.width || options.size || 1;
  37982. var height = options.height || options.size || 1;
  37983. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37984. // Vertices
  37985. var halfWidth = width / 2.0;
  37986. var halfHeight = height / 2.0;
  37987. positions.push(-halfWidth, -halfHeight, 0);
  37988. normals.push(0, 0, -1.0);
  37989. uvs.push(0.0, 0.0);
  37990. positions.push(halfWidth, -halfHeight, 0);
  37991. normals.push(0, 0, -1.0);
  37992. uvs.push(1.0, 0.0);
  37993. positions.push(halfWidth, halfHeight, 0);
  37994. normals.push(0, 0, -1.0);
  37995. uvs.push(1.0, 1.0);
  37996. positions.push(-halfWidth, halfHeight, 0);
  37997. normals.push(0, 0, -1.0);
  37998. uvs.push(0.0, 1.0);
  37999. // Indices
  38000. indices.push(0);
  38001. indices.push(1);
  38002. indices.push(2);
  38003. indices.push(0);
  38004. indices.push(2);
  38005. indices.push(3);
  38006. // Sides
  38007. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38008. // Result
  38009. var vertexData = new VertexData();
  38010. vertexData.indices = indices;
  38011. vertexData.positions = positions;
  38012. vertexData.normals = normals;
  38013. vertexData.uvs = uvs;
  38014. return vertexData;
  38015. };
  38016. /**
  38017. * Creates the VertexData of the Disc or regular Polygon.
  38018. */
  38019. VertexData.CreateDisc = function (options) {
  38020. var positions = [];
  38021. var indices = [];
  38022. var normals = [];
  38023. var uvs = [];
  38024. var radius = options.radius || 0.5;
  38025. var tessellation = options.tessellation || 64;
  38026. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38027. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38028. // positions and uvs
  38029. positions.push(0, 0, 0); // disc center first
  38030. uvs.push(0.5, 0.5);
  38031. var theta = Math.PI * 2 * arc;
  38032. var step = theta / tessellation;
  38033. for (var a = 0; a < theta; a += step) {
  38034. var x = Math.cos(a);
  38035. var y = Math.sin(a);
  38036. var u = (x + 1) / 2;
  38037. var v = (1 - y) / 2;
  38038. positions.push(radius * x, radius * y, 0);
  38039. uvs.push(u, v);
  38040. }
  38041. if (arc === 1) {
  38042. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38043. uvs.push(uvs[2], uvs[3]);
  38044. }
  38045. //indices
  38046. var vertexNb = positions.length / 3;
  38047. for (var i = 1; i < vertexNb - 1; i++) {
  38048. indices.push(i + 1, 0, i);
  38049. }
  38050. // result
  38051. VertexData.ComputeNormals(positions, indices, normals);
  38052. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38053. var vertexData = new VertexData();
  38054. vertexData.indices = indices;
  38055. vertexData.positions = positions;
  38056. vertexData.normals = normals;
  38057. vertexData.uvs = uvs;
  38058. return vertexData;
  38059. };
  38060. /**
  38061. * Creates the VertexData of the IcoSphere.
  38062. */
  38063. VertexData.CreateIcoSphere = function (options) {
  38064. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38065. var radius = options.radius || 1;
  38066. var flat = (options.flat === undefined) ? true : options.flat;
  38067. var subdivisions = options.subdivisions || 4;
  38068. var radiusX = options.radiusX || radius;
  38069. var radiusY = options.radiusY || radius;
  38070. var radiusZ = options.radiusZ || radius;
  38071. var t = (1 + Math.sqrt(5)) / 2;
  38072. // 12 vertex x,y,z
  38073. var ico_vertices = [
  38074. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38075. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38076. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38077. ];
  38078. // index of 3 vertex makes a face of icopshere
  38079. var ico_indices = [
  38080. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38081. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38082. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38083. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38084. ];
  38085. // vertex for uv have aliased position, not for UV
  38086. var vertices_unalias_id = [
  38087. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38088. // vertex alias
  38089. 0,
  38090. 2,
  38091. 3,
  38092. 3,
  38093. 3,
  38094. 4,
  38095. 7,
  38096. 8,
  38097. 9,
  38098. 9,
  38099. 10,
  38100. 11 // 23: B + 12
  38101. ];
  38102. // uv as integer step (not pixels !)
  38103. var ico_vertexuv = [
  38104. 5, 1, 3, 1, 6, 4, 0, 0,
  38105. 5, 3, 4, 2, 2, 2, 4, 0,
  38106. 2, 0, 1, 1, 6, 0, 6, 2,
  38107. // vertex alias (for same vertex on different faces)
  38108. 0, 4,
  38109. 3, 3,
  38110. 4, 4,
  38111. 3, 1,
  38112. 4, 2,
  38113. 4, 4,
  38114. 0, 2,
  38115. 1, 1,
  38116. 2, 2,
  38117. 3, 3,
  38118. 1, 3,
  38119. 2, 4 // 23: B + 12
  38120. ];
  38121. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38122. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38123. // First island of uv mapping
  38124. // v = 4h 3+ 2
  38125. // v = 3h 9+ 4
  38126. // v = 2h 9+ 5 B
  38127. // v = 1h 9 1 0
  38128. // v = 0h 3 8 7 A
  38129. // u = 0 1 2 3 4 5 6 *a
  38130. // Second island of uv mapping
  38131. // v = 4h 0+ B+ 4+
  38132. // v = 3h A+ 2+
  38133. // v = 2h 7+ 6 3+
  38134. // v = 1h 8+ 3+
  38135. // v = 0h
  38136. // u = 0 1 2 3 4 5 6 *a
  38137. // Face layout on texture UV mapping
  38138. // ============
  38139. // \ 4 /\ 16 / ======
  38140. // \ / \ / /\ 11 /
  38141. // \/ 7 \/ / \ /
  38142. // ======= / 10 \/
  38143. // /\ 17 /\ =======
  38144. // / \ / \ \ 15 /\
  38145. // / 8 \/ 12 \ \ / \
  38146. // ============ \/ 6 \
  38147. // \ 18 /\ ============
  38148. // \ / \ \ 5 /\ 0 /
  38149. // \/ 13 \ \ / \ /
  38150. // ======= \/ 1 \/
  38151. // =============
  38152. // /\ 19 /\ 2 /\
  38153. // / \ / \ / \
  38154. // / 14 \/ 9 \/ 3 \
  38155. // ===================
  38156. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38157. var ustep = 138 / 1024;
  38158. var vstep = 239 / 1024;
  38159. var uoffset = 60 / 1024;
  38160. var voffset = 26 / 1024;
  38161. // Second island should have margin, not to touch the first island
  38162. // avoid any borderline artefact in pixel rounding
  38163. var island_u_offset = -40 / 1024;
  38164. var island_v_offset = +20 / 1024;
  38165. // face is either island 0 or 1 :
  38166. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38167. var island = [
  38168. 0, 0, 0, 0, 1,
  38169. 0, 0, 1, 1, 0,
  38170. 0, 0, 1, 1, 0,
  38171. 0, 1, 1, 1, 0 // 15 - 19
  38172. ];
  38173. var indices = [];
  38174. var positions = [];
  38175. var normals = [];
  38176. var uvs = [];
  38177. var current_indice = 0;
  38178. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38179. var face_vertex_pos = new Array(3);
  38180. var face_vertex_uv = new Array(3);
  38181. var v012;
  38182. for (v012 = 0; v012 < 3; v012++) {
  38183. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38184. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38185. }
  38186. // create all with normals
  38187. for (var face = 0; face < 20; face++) {
  38188. // 3 vertex per face
  38189. for (v012 = 0; v012 < 3; v012++) {
  38190. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38191. var v_id = ico_indices[3 * face + v012];
  38192. // vertex have 3D position (x,y,z)
  38193. 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]);
  38194. // Normalize to get normal, then scale to radius
  38195. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38196. // uv Coordinates from vertex ID
  38197. 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);
  38198. }
  38199. // Subdivide the face (interpolate pos, norm, uv)
  38200. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38201. // - norm is linear interpolation of vertex corner normal
  38202. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38203. // - uv is linear interpolation
  38204. //
  38205. // Topology is as below for sub-divide by 2
  38206. // vertex shown as v0,v1,v2
  38207. // interp index is i1 to progress in range [v0,v1[
  38208. // interp index is i2 to progress in range [v0,v2[
  38209. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38210. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38211. //
  38212. //
  38213. // i2 v2
  38214. // ^ ^
  38215. // / / \
  38216. // / / \
  38217. // / / \
  38218. // / / (0,1) \
  38219. // / #---------\
  38220. // / / \ (0,0)'/ \
  38221. // / / \ / \
  38222. // / / \ / \
  38223. // / / (0,0) \ / (1,0) \
  38224. // / #---------#---------\
  38225. // v0 v1
  38226. //
  38227. // --------------------> i1
  38228. //
  38229. // interp of (i1,i2):
  38230. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38231. // along i1 : lerp(x0,x1, i1/(S-i2))
  38232. //
  38233. // centroid of triangle is needed to get help normal computation
  38234. // (c1,c2) are used for centroid location
  38235. var interp_vertex = function (i1, i2, c1, c2) {
  38236. // vertex is interpolated from
  38237. // - face_vertex_pos[0..2]
  38238. // - face_vertex_uv[0..2]
  38239. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38240. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38241. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38242. pos_interp.normalize();
  38243. var vertex_normal;
  38244. if (flat) {
  38245. // in flat mode, recalculate normal as face centroid normal
  38246. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38247. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38248. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38249. }
  38250. else {
  38251. // in smooth mode, recalculate normal from each single vertex position
  38252. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38253. }
  38254. // Vertex normal need correction due to X,Y,Z radius scaling
  38255. vertex_normal.x /= radiusX;
  38256. vertex_normal.y /= radiusY;
  38257. vertex_normal.z /= radiusZ;
  38258. vertex_normal.normalize();
  38259. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38260. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38261. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38262. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38263. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38264. uvs.push(uv_interp.x, uv_interp.y);
  38265. // push each vertex has member of a face
  38266. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38267. indices.push(current_indice);
  38268. current_indice++;
  38269. };
  38270. for (var i2 = 0; i2 < subdivisions; i2++) {
  38271. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38272. // face : (i1,i2) for /\ :
  38273. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38274. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38275. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38276. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38277. if (i1 + i2 + 1 < subdivisions) {
  38278. // face : (i1,i2)' for \/ :
  38279. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38280. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38281. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38282. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38283. }
  38284. }
  38285. }
  38286. }
  38287. // Sides
  38288. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38289. // Result
  38290. var vertexData = new VertexData();
  38291. vertexData.indices = indices;
  38292. vertexData.positions = positions;
  38293. vertexData.normals = normals;
  38294. vertexData.uvs = uvs;
  38295. return vertexData;
  38296. };
  38297. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38298. /**
  38299. * Creates the VertexData of the Polyhedron.
  38300. */
  38301. VertexData.CreatePolyhedron = function (options) {
  38302. // provided polyhedron types :
  38303. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38304. // 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)
  38305. var polyhedra = [];
  38306. 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]] };
  38307. 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]] };
  38308. polyhedra[2] = {
  38309. 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]],
  38310. 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]]
  38311. };
  38312. polyhedra[3] = {
  38313. 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]],
  38314. 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]]
  38315. };
  38316. polyhedra[4] = {
  38317. 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]],
  38318. 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]]
  38319. };
  38320. 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]] };
  38321. 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]] };
  38322. 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]] };
  38323. 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]] };
  38324. 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]] };
  38325. 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]] };
  38326. 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]] };
  38327. 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]] };
  38328. 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]] };
  38329. polyhedra[14] = {
  38330. 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]],
  38331. 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]]
  38332. };
  38333. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38334. var size = options.size;
  38335. var sizeX = options.sizeX || size || 1;
  38336. var sizeY = options.sizeY || size || 1;
  38337. var sizeZ = options.sizeZ || size || 1;
  38338. var data = options.custom || polyhedra[type];
  38339. var nbfaces = data.face.length;
  38340. var faceUV = options.faceUV || new Array(nbfaces);
  38341. var faceColors = options.faceColors;
  38342. var flat = (options.flat === undefined) ? true : options.flat;
  38343. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38344. var positions = [];
  38345. var indices = [];
  38346. var normals = [];
  38347. var uvs = [];
  38348. var colors = [];
  38349. var index = 0;
  38350. var faceIdx = 0; // face cursor in the array "indexes"
  38351. var indexes = [];
  38352. var i = 0;
  38353. var f = 0;
  38354. var u, v, ang, x, y, tmp;
  38355. // default face colors and UV if undefined
  38356. if (flat) {
  38357. for (f = 0; f < nbfaces; f++) {
  38358. if (faceColors && faceColors[f] === undefined) {
  38359. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38360. }
  38361. if (faceUV && faceUV[f] === undefined) {
  38362. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38363. }
  38364. }
  38365. }
  38366. if (!flat) {
  38367. for (i = 0; i < data.vertex.length; i++) {
  38368. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38369. uvs.push(0, 0);
  38370. }
  38371. for (f = 0; f < nbfaces; f++) {
  38372. for (i = 0; i < data.face[f].length - 2; i++) {
  38373. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38374. }
  38375. }
  38376. }
  38377. else {
  38378. for (f = 0; f < nbfaces; f++) {
  38379. var fl = data.face[f].length; // number of vertices of the current face
  38380. ang = 2 * Math.PI / fl;
  38381. x = 0.5 * Math.tan(ang / 2);
  38382. y = 0.5;
  38383. // positions, uvs, colors
  38384. for (i = 0; i < fl; i++) {
  38385. // positions
  38386. 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);
  38387. indexes.push(index);
  38388. index++;
  38389. // uvs
  38390. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38391. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38392. uvs.push(u, v);
  38393. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38394. y = x * Math.sin(ang) + y * Math.cos(ang);
  38395. x = tmp;
  38396. // colors
  38397. if (faceColors) {
  38398. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38399. }
  38400. }
  38401. // indices from indexes
  38402. for (i = 0; i < fl - 2; i++) {
  38403. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38404. }
  38405. faceIdx += fl;
  38406. }
  38407. }
  38408. VertexData.ComputeNormals(positions, indices, normals);
  38409. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38410. var vertexData = new VertexData();
  38411. vertexData.positions = positions;
  38412. vertexData.indices = indices;
  38413. vertexData.normals = normals;
  38414. vertexData.uvs = uvs;
  38415. if (faceColors && flat) {
  38416. vertexData.colors = colors;
  38417. }
  38418. return vertexData;
  38419. };
  38420. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38421. /**
  38422. * Creates the VertexData of the Torus Knot.
  38423. */
  38424. VertexData.CreateTorusKnot = function (options) {
  38425. var indices = [];
  38426. var positions = [];
  38427. var normals = [];
  38428. var uvs = [];
  38429. var radius = options.radius || 2;
  38430. var tube = options.tube || 0.5;
  38431. var radialSegments = options.radialSegments || 32;
  38432. var tubularSegments = options.tubularSegments || 32;
  38433. var p = options.p || 2;
  38434. var q = options.q || 3;
  38435. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38436. // Helper
  38437. var getPos = function (angle) {
  38438. var cu = Math.cos(angle);
  38439. var su = Math.sin(angle);
  38440. var quOverP = q / p * angle;
  38441. var cs = Math.cos(quOverP);
  38442. var tx = radius * (2 + cs) * 0.5 * cu;
  38443. var ty = radius * (2 + cs) * su * 0.5;
  38444. var tz = radius * Math.sin(quOverP) * 0.5;
  38445. return new BABYLON.Vector3(tx, ty, tz);
  38446. };
  38447. // Vertices
  38448. var i;
  38449. var j;
  38450. for (i = 0; i <= radialSegments; i++) {
  38451. var modI = i % radialSegments;
  38452. var u = modI / radialSegments * 2 * p * Math.PI;
  38453. var p1 = getPos(u);
  38454. var p2 = getPos(u + 0.01);
  38455. var tang = p2.subtract(p1);
  38456. var n = p2.add(p1);
  38457. var bitan = BABYLON.Vector3.Cross(tang, n);
  38458. n = BABYLON.Vector3.Cross(bitan, tang);
  38459. bitan.normalize();
  38460. n.normalize();
  38461. for (j = 0; j < tubularSegments; j++) {
  38462. var modJ = j % tubularSegments;
  38463. var v = modJ / tubularSegments * 2 * Math.PI;
  38464. var cx = -tube * Math.cos(v);
  38465. var cy = tube * Math.sin(v);
  38466. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38467. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38468. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38469. uvs.push(i / radialSegments);
  38470. uvs.push(j / tubularSegments);
  38471. }
  38472. }
  38473. for (i = 0; i < radialSegments; i++) {
  38474. for (j = 0; j < tubularSegments; j++) {
  38475. var jNext = (j + 1) % tubularSegments;
  38476. var a = i * tubularSegments + j;
  38477. var b = (i + 1) * tubularSegments + j;
  38478. var c = (i + 1) * tubularSegments + jNext;
  38479. var d = i * tubularSegments + jNext;
  38480. indices.push(d);
  38481. indices.push(b);
  38482. indices.push(a);
  38483. indices.push(d);
  38484. indices.push(c);
  38485. indices.push(b);
  38486. }
  38487. }
  38488. // Normals
  38489. VertexData.ComputeNormals(positions, indices, normals);
  38490. // Sides
  38491. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38492. // Result
  38493. var vertexData = new VertexData();
  38494. vertexData.indices = indices;
  38495. vertexData.positions = positions;
  38496. vertexData.normals = normals;
  38497. vertexData.uvs = uvs;
  38498. return vertexData;
  38499. };
  38500. // Tools
  38501. /**
  38502. * @param {any} - positions (number[] or Float32Array)
  38503. * @param {any} - indices (number[] or Uint16Array)
  38504. * @param {any} - normals (number[] or Float32Array)
  38505. * options (optional) :
  38506. * facetPositions : optional array of facet positions (vector3)
  38507. * facetNormals : optional array of facet normals (vector3)
  38508. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38509. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38510. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38511. * bbSize : optional bounding box size data, required for facetPartitioning computation
  38512. * bInfo : optional bounding info, required for facetPartitioning computation
  38513. */
  38514. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38515. // temporary scalar variables
  38516. var index = 0; // facet index
  38517. var p1p2x = 0.0; // p1p2 vector x coordinate
  38518. var p1p2y = 0.0; // p1p2 vector y coordinate
  38519. var p1p2z = 0.0; // p1p2 vector z coordinate
  38520. var p3p2x = 0.0; // p3p2 vector x coordinate
  38521. var p3p2y = 0.0; // p3p2 vector y coordinate
  38522. var p3p2z = 0.0; // p3p2 vector z coordinate
  38523. var faceNormalx = 0.0; // facet normal x coordinate
  38524. var faceNormaly = 0.0; // facet normal y coordinate
  38525. var faceNormalz = 0.0; // facet normal z coordinate
  38526. var length = 0.0; // facet normal length before normalization
  38527. var v1x = 0; // vector1 x index in the positions array
  38528. var v1y = 0; // vector1 y index in the positions array
  38529. var v1z = 0; // vector1 z index in the positions array
  38530. var v2x = 0; // vector2 x index in the positions array
  38531. var v2y = 0; // vector2 y index in the positions array
  38532. var v2z = 0; // vector2 z index in the positions array
  38533. var v3x = 0; // vector3 x index in the positions array
  38534. var v3y = 0; // vector3 y index in the positions array
  38535. var v3z = 0; // vector3 z index in the positions array
  38536. var computeFacetNormals = false;
  38537. var computeFacetPositions = false;
  38538. var computeFacetPartitioning = false;
  38539. if (options) {
  38540. computeFacetNormals = (options.facetNormals) ? true : false;
  38541. computeFacetPositions = (options.facetPositions) ? true : false;
  38542. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38543. }
  38544. // facetPartitioning reinit if needed
  38545. if (computeFacetPartitioning) {
  38546. var ox = 0; // X partitioning index for facet position
  38547. var oy = 0; // Y partinioning index for facet position
  38548. var oz = 0; // Z partinioning index for facet position
  38549. var b1x = 0; // X partitioning index for facet v1 vertex
  38550. var b1y = 0; // Y partitioning index for facet v1 vertex
  38551. var b1z = 0; // z partitioning index for facet v1 vertex
  38552. var b2x = 0; // X partitioning index for facet v2 vertex
  38553. var b2y = 0; // Y partitioning index for facet v2 vertex
  38554. var b2z = 0; // Z partitioning index for facet v2 vertex
  38555. var b3x = 0; // X partitioning index for facet v3 vertex
  38556. var b3y = 0; // Y partitioning index for facet v3 vertex
  38557. var b3z = 0; // Z partitioning index for facet v3 vertex
  38558. var block_idx_o = 0; // facet barycenter block index
  38559. var block_idx_v1 = 0; // v1 vertex block index
  38560. var block_idx_v2 = 0; // v2 vertex block index
  38561. var block_idx_v3 = 0; // v3 vertex block index
  38562. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38563. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38564. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  38565. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  38566. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  38567. var subSq = options.subDiv.max * options.subDiv.max;
  38568. options.facetPartitioning.length = 0;
  38569. }
  38570. // reset the normals
  38571. for (index = 0; index < positions.length; index++) {
  38572. normals[index] = 0.0;
  38573. }
  38574. // Loop : 1 indice triplet = 1 facet
  38575. var nbFaces = indices.length / 3;
  38576. for (index = 0; index < nbFaces; index++) {
  38577. // get the indexes of the coordinates of each vertex of the facet
  38578. v1x = indices[index * 3] * 3;
  38579. v1y = v1x + 1;
  38580. v1z = v1x + 2;
  38581. v2x = indices[index * 3 + 1] * 3;
  38582. v2y = v2x + 1;
  38583. v2z = v2x + 2;
  38584. v3x = indices[index * 3 + 2] * 3;
  38585. v3y = v3x + 1;
  38586. v3z = v3x + 2;
  38587. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38588. p1p2y = positions[v1y] - positions[v2y];
  38589. p1p2z = positions[v1z] - positions[v2z];
  38590. p3p2x = positions[v3x] - positions[v2x];
  38591. p3p2y = positions[v3y] - positions[v2y];
  38592. p3p2z = positions[v3z] - positions[v2z];
  38593. // compute the face normal with the cross product
  38594. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  38595. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  38596. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  38597. // normalize this normal and store it in the array facetData
  38598. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38599. length = (length === 0) ? 1.0 : length;
  38600. faceNormalx /= length;
  38601. faceNormaly /= length;
  38602. faceNormalz /= length;
  38603. if (computeFacetNormals) {
  38604. options.facetNormals[index].x = faceNormalx;
  38605. options.facetNormals[index].y = faceNormaly;
  38606. options.facetNormals[index].z = faceNormalz;
  38607. }
  38608. if (computeFacetPositions) {
  38609. // compute and the facet barycenter coordinates in the array facetPositions
  38610. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38611. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38612. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38613. }
  38614. if (computeFacetPartitioning) {
  38615. // store the facet indexes in arrays in the main facetPartitioning array :
  38616. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38617. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38618. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38619. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38620. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38621. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38622. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38623. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38624. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38625. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38626. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38627. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38628. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38629. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38630. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38631. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38632. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38633. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38634. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38635. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38636. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38637. // push each facet index in each block containing the vertex
  38638. options.facetPartitioning[block_idx_v1].push(index);
  38639. if (block_idx_v2 != block_idx_v1) {
  38640. options.facetPartitioning[block_idx_v2].push(index);
  38641. }
  38642. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38643. options.facetPartitioning[block_idx_v3].push(index);
  38644. }
  38645. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38646. options.facetPartitioning[block_idx_o].push(index);
  38647. }
  38648. }
  38649. // compute the normals anyway
  38650. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38651. normals[v1y] += faceNormaly;
  38652. normals[v1z] += faceNormalz;
  38653. normals[v2x] += faceNormalx;
  38654. normals[v2y] += faceNormaly;
  38655. normals[v2z] += faceNormalz;
  38656. normals[v3x] += faceNormalx;
  38657. normals[v3y] += faceNormaly;
  38658. normals[v3z] += faceNormalz;
  38659. }
  38660. // last normalization of each normal
  38661. for (index = 0; index < normals.length / 3; index++) {
  38662. faceNormalx = normals[index * 3];
  38663. faceNormaly = normals[index * 3 + 1];
  38664. faceNormalz = normals[index * 3 + 2];
  38665. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38666. length = (length === 0) ? 1.0 : length;
  38667. faceNormalx /= length;
  38668. faceNormaly /= length;
  38669. faceNormalz /= length;
  38670. normals[index * 3] = faceNormalx;
  38671. normals[index * 3 + 1] = faceNormaly;
  38672. normals[index * 3 + 2] = faceNormalz;
  38673. }
  38674. };
  38675. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  38676. var li = indices.length;
  38677. var ln = normals.length;
  38678. var i;
  38679. var n;
  38680. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38681. switch (sideOrientation) {
  38682. case BABYLON.Mesh.FRONTSIDE:
  38683. // nothing changed
  38684. break;
  38685. case BABYLON.Mesh.BACKSIDE:
  38686. var tmp;
  38687. // indices
  38688. for (i = 0; i < li; i += 3) {
  38689. tmp = indices[i];
  38690. indices[i] = indices[i + 2];
  38691. indices[i + 2] = tmp;
  38692. }
  38693. // normals
  38694. for (n = 0; n < ln; n++) {
  38695. normals[n] = -normals[n];
  38696. }
  38697. break;
  38698. case BABYLON.Mesh.DOUBLESIDE:
  38699. // positions
  38700. var lp = positions.length;
  38701. var l = lp / 3;
  38702. for (var p = 0; p < lp; p++) {
  38703. positions[lp + p] = positions[p];
  38704. }
  38705. // indices
  38706. for (i = 0; i < li; i += 3) {
  38707. indices[i + li] = indices[i + 2] + l;
  38708. indices[i + 1 + li] = indices[i + 1] + l;
  38709. indices[i + 2 + li] = indices[i] + l;
  38710. }
  38711. // normals
  38712. for (n = 0; n < ln; n++) {
  38713. normals[ln + n] = -normals[n];
  38714. }
  38715. // uvs
  38716. var lu = uvs.length;
  38717. for (var u = 0; u < lu; u++) {
  38718. uvs[u + lu] = uvs[u];
  38719. }
  38720. break;
  38721. }
  38722. };
  38723. /**
  38724. * Creates a new VertexData from the imported parameters.
  38725. */
  38726. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38727. var vertexData = new VertexData();
  38728. // positions
  38729. var positions = parsedVertexData.positions;
  38730. if (positions) {
  38731. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38732. }
  38733. // normals
  38734. var normals = parsedVertexData.normals;
  38735. if (normals) {
  38736. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38737. }
  38738. // tangents
  38739. var tangents = parsedVertexData.tangents;
  38740. if (tangents) {
  38741. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38742. }
  38743. // uvs
  38744. var uvs = parsedVertexData.uvs;
  38745. if (uvs) {
  38746. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38747. }
  38748. // uv2s
  38749. var uv2s = parsedVertexData.uv2s;
  38750. if (uv2s) {
  38751. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38752. }
  38753. // uv3s
  38754. var uv3s = parsedVertexData.uv3s;
  38755. if (uv3s) {
  38756. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38757. }
  38758. // uv4s
  38759. var uv4s = parsedVertexData.uv4s;
  38760. if (uv4s) {
  38761. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38762. }
  38763. // uv5s
  38764. var uv5s = parsedVertexData.uv5s;
  38765. if (uv5s) {
  38766. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38767. }
  38768. // uv6s
  38769. var uv6s = parsedVertexData.uv6s;
  38770. if (uv6s) {
  38771. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38772. }
  38773. // colors
  38774. var colors = parsedVertexData.colors;
  38775. if (colors) {
  38776. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38777. }
  38778. // matricesIndices
  38779. var matricesIndices = parsedVertexData.matricesIndices;
  38780. if (matricesIndices) {
  38781. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38782. }
  38783. // matricesWeights
  38784. var matricesWeights = parsedVertexData.matricesWeights;
  38785. if (matricesWeights) {
  38786. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38787. }
  38788. // indices
  38789. var indices = parsedVertexData.indices;
  38790. if (indices) {
  38791. vertexData.indices = indices;
  38792. }
  38793. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38794. };
  38795. return VertexData;
  38796. }());
  38797. BABYLON.VertexData = VertexData;
  38798. })(BABYLON || (BABYLON = {}));
  38799. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38800. var BABYLON;
  38801. (function (BABYLON) {
  38802. var Tags = (function () {
  38803. function Tags() {
  38804. }
  38805. Tags.EnableFor = function (obj) {
  38806. obj._tags = obj._tags || {};
  38807. obj.hasTags = function () {
  38808. return Tags.HasTags(obj);
  38809. };
  38810. obj.addTags = function (tagsString) {
  38811. return Tags.AddTagsTo(obj, tagsString);
  38812. };
  38813. obj.removeTags = function (tagsString) {
  38814. return Tags.RemoveTagsFrom(obj, tagsString);
  38815. };
  38816. obj.matchesTagsQuery = function (tagsQuery) {
  38817. return Tags.MatchesQuery(obj, tagsQuery);
  38818. };
  38819. };
  38820. Tags.DisableFor = function (obj) {
  38821. delete obj._tags;
  38822. delete obj.hasTags;
  38823. delete obj.addTags;
  38824. delete obj.removeTags;
  38825. delete obj.matchesTagsQuery;
  38826. };
  38827. Tags.HasTags = function (obj) {
  38828. if (!obj._tags) {
  38829. return false;
  38830. }
  38831. return !BABYLON.Tools.IsEmpty(obj._tags);
  38832. };
  38833. Tags.GetTags = function (obj, asString) {
  38834. if (asString === void 0) { asString = true; }
  38835. if (!obj._tags) {
  38836. return null;
  38837. }
  38838. if (asString) {
  38839. var tagsArray = [];
  38840. for (var tag in obj._tags) {
  38841. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  38842. tagsArray.push(tag);
  38843. }
  38844. }
  38845. return tagsArray.join(" ");
  38846. }
  38847. else {
  38848. return obj._tags;
  38849. }
  38850. };
  38851. // the tags 'true' and 'false' are reserved and cannot be used as tags
  38852. // a tag cannot start with '||', '&&', and '!'
  38853. // it cannot contain whitespaces
  38854. Tags.AddTagsTo = function (obj, tagsString) {
  38855. if (!tagsString) {
  38856. return;
  38857. }
  38858. if (typeof tagsString !== "string") {
  38859. return;
  38860. }
  38861. var tags = tagsString.split(" ");
  38862. tags.forEach(function (tag, index, array) {
  38863. Tags._AddTagTo(obj, tag);
  38864. });
  38865. };
  38866. Tags._AddTagTo = function (obj, tag) {
  38867. tag = tag.trim();
  38868. if (tag === "" || tag === "true" || tag === "false") {
  38869. return;
  38870. }
  38871. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  38872. return;
  38873. }
  38874. Tags.EnableFor(obj);
  38875. obj._tags[tag] = true;
  38876. };
  38877. Tags.RemoveTagsFrom = function (obj, tagsString) {
  38878. if (!Tags.HasTags(obj)) {
  38879. return;
  38880. }
  38881. var tags = tagsString.split(" ");
  38882. for (var t in tags) {
  38883. Tags._RemoveTagFrom(obj, tags[t]);
  38884. }
  38885. };
  38886. Tags._RemoveTagFrom = function (obj, tag) {
  38887. delete obj._tags[tag];
  38888. };
  38889. Tags.MatchesQuery = function (obj, tagsQuery) {
  38890. if (tagsQuery === undefined) {
  38891. return true;
  38892. }
  38893. if (tagsQuery === "") {
  38894. return Tags.HasTags(obj);
  38895. }
  38896. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  38897. };
  38898. return Tags;
  38899. }());
  38900. BABYLON.Tags = Tags;
  38901. })(BABYLON || (BABYLON = {}));
  38902. //# sourceMappingURL=babylon.tags.js.map
  38903. var BABYLON;
  38904. (function (BABYLON) {
  38905. var Internals;
  38906. (function (Internals) {
  38907. var AndOrNotEvaluator = (function () {
  38908. function AndOrNotEvaluator() {
  38909. }
  38910. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  38911. if (!query.match(/\([^\(\)]*\)/g)) {
  38912. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  38913. }
  38914. else {
  38915. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  38916. // remove parenthesis
  38917. r = r.slice(1, r.length - 1);
  38918. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  38919. });
  38920. }
  38921. if (query === "true") {
  38922. return true;
  38923. }
  38924. if (query === "false") {
  38925. return false;
  38926. }
  38927. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  38928. };
  38929. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  38930. evaluateCallback = evaluateCallback || (function (r) {
  38931. return r === "true" ? true : false;
  38932. });
  38933. var result;
  38934. var or = parenthesisContent.split("||");
  38935. for (var i in or) {
  38936. if (or.hasOwnProperty(i)) {
  38937. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  38938. var and = ori.split("&&");
  38939. if (and.length > 1) {
  38940. for (var j = 0; j < and.length; ++j) {
  38941. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  38942. if (andj !== "true" && andj !== "false") {
  38943. if (andj[0] === "!") {
  38944. result = !evaluateCallback(andj.substring(1));
  38945. }
  38946. else {
  38947. result = evaluateCallback(andj);
  38948. }
  38949. }
  38950. else {
  38951. result = andj === "true" ? true : false;
  38952. }
  38953. if (!result) {
  38954. ori = "false";
  38955. break;
  38956. }
  38957. }
  38958. }
  38959. if (result || ori === "true") {
  38960. result = true;
  38961. break;
  38962. }
  38963. // result equals false (or undefined)
  38964. if (ori !== "true" && ori !== "false") {
  38965. if (ori[0] === "!") {
  38966. result = !evaluateCallback(ori.substring(1));
  38967. }
  38968. else {
  38969. result = evaluateCallback(ori);
  38970. }
  38971. }
  38972. else {
  38973. result = ori === "true" ? true : false;
  38974. }
  38975. }
  38976. }
  38977. // the whole parenthesis scope is replaced by 'true' or 'false'
  38978. return result ? "true" : "false";
  38979. };
  38980. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  38981. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  38982. // remove whitespaces
  38983. r = r.replace(/[\s]/g, function () { return ""; });
  38984. return r.length % 2 ? "!" : "";
  38985. });
  38986. booleanString = booleanString.trim();
  38987. if (booleanString === "!true") {
  38988. booleanString = "false";
  38989. }
  38990. else if (booleanString === "!false") {
  38991. booleanString = "true";
  38992. }
  38993. return booleanString;
  38994. };
  38995. return AndOrNotEvaluator;
  38996. }());
  38997. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  38998. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38999. })(BABYLON || (BABYLON = {}));
  39000. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  39001. var BABYLON;
  39002. (function (BABYLON) {
  39003. var PostProcessRenderPass = (function () {
  39004. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39005. this._enabled = true;
  39006. this._refCount = 0;
  39007. this._name = name;
  39008. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39009. this.setRenderList(renderList);
  39010. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39011. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39012. this._scene = scene;
  39013. this._renderList = renderList;
  39014. }
  39015. // private
  39016. PostProcessRenderPass.prototype._incRefCount = function () {
  39017. if (this._refCount === 0) {
  39018. this._scene.customRenderTargets.push(this._renderTexture);
  39019. }
  39020. return ++this._refCount;
  39021. };
  39022. PostProcessRenderPass.prototype._decRefCount = function () {
  39023. this._refCount--;
  39024. if (this._refCount <= 0) {
  39025. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39026. }
  39027. return this._refCount;
  39028. };
  39029. PostProcessRenderPass.prototype._update = function () {
  39030. this.setRenderList(this._renderList);
  39031. };
  39032. // public
  39033. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39034. this._renderTexture.renderList = renderList;
  39035. };
  39036. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39037. return this._renderTexture;
  39038. };
  39039. return PostProcessRenderPass;
  39040. }());
  39041. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39042. })(BABYLON || (BABYLON = {}));
  39043. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39044. var BABYLON;
  39045. (function (BABYLON) {
  39046. var PostProcessRenderEffect = (function () {
  39047. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39048. this._engine = engine;
  39049. this._name = name;
  39050. this._singleInstance = singleInstance || true;
  39051. this._getPostProcess = getPostProcess;
  39052. this._cameras = [];
  39053. this._indicesForCamera = [];
  39054. this._postProcesses = {};
  39055. this._renderPasses = {};
  39056. this._renderEffectAsPasses = {};
  39057. }
  39058. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39059. get: function () {
  39060. for (var index in this._postProcesses) {
  39061. if (!this._postProcesses[index].isSupported) {
  39062. return false;
  39063. }
  39064. }
  39065. return true;
  39066. },
  39067. enumerable: true,
  39068. configurable: true
  39069. });
  39070. PostProcessRenderEffect.prototype._update = function () {
  39071. for (var renderPassName in this._renderPasses) {
  39072. this._renderPasses[renderPassName]._update();
  39073. }
  39074. };
  39075. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39076. this._renderPasses[renderPass._name] = renderPass;
  39077. this._linkParameters();
  39078. };
  39079. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39080. delete this._renderPasses[renderPass._name];
  39081. this._linkParameters();
  39082. };
  39083. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39084. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39085. this._linkParameters();
  39086. };
  39087. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39088. for (var renderPassName in this._renderPasses) {
  39089. if (renderPassName === passName) {
  39090. return this._renderPasses[passName];
  39091. }
  39092. }
  39093. };
  39094. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39095. this._renderPasses = {};
  39096. this._linkParameters();
  39097. };
  39098. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39099. var cameraKey;
  39100. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39101. for (var i = 0; i < _cam.length; i++) {
  39102. var camera = _cam[i];
  39103. var cameraName = camera.name;
  39104. if (this._singleInstance) {
  39105. cameraKey = 0;
  39106. }
  39107. else {
  39108. cameraKey = cameraName;
  39109. }
  39110. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39111. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39112. if (!this._indicesForCamera[cameraName]) {
  39113. this._indicesForCamera[cameraName] = [];
  39114. }
  39115. this._indicesForCamera[cameraName].push(index);
  39116. if (this._cameras.indexOf(camera) === -1) {
  39117. this._cameras[cameraName] = camera;
  39118. }
  39119. for (var passName in this._renderPasses) {
  39120. this._renderPasses[passName]._incRefCount();
  39121. }
  39122. }
  39123. this._linkParameters();
  39124. };
  39125. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39126. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39127. for (var i = 0; i < _cam.length; i++) {
  39128. var camera = _cam[i];
  39129. var cameraName = camera.name;
  39130. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39131. var index = this._cameras.indexOf(cameraName);
  39132. this._indicesForCamera.splice(index, 1);
  39133. this._cameras.splice(index, 1);
  39134. for (var passName in this._renderPasses) {
  39135. this._renderPasses[passName]._decRefCount();
  39136. }
  39137. }
  39138. };
  39139. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39140. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39141. for (var i = 0; i < _cam.length; i++) {
  39142. var camera = _cam[i];
  39143. var cameraName = camera.name;
  39144. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39145. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39146. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39147. }
  39148. }
  39149. for (var passName in this._renderPasses) {
  39150. this._renderPasses[passName]._incRefCount();
  39151. }
  39152. }
  39153. };
  39154. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39155. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39156. for (var i = 0; i < _cam.length; i++) {
  39157. var camera = _cam[i];
  39158. var cameraName = camera.Name;
  39159. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39160. for (var passName in this._renderPasses) {
  39161. this._renderPasses[passName]._decRefCount();
  39162. }
  39163. }
  39164. };
  39165. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39166. if (this._singleInstance) {
  39167. return this._postProcesses[0];
  39168. }
  39169. else {
  39170. return this._postProcesses[camera.name];
  39171. }
  39172. };
  39173. PostProcessRenderEffect.prototype._linkParameters = function () {
  39174. var _this = this;
  39175. for (var index in this._postProcesses) {
  39176. if (this.applyParameters) {
  39177. this.applyParameters(this._postProcesses[index]);
  39178. }
  39179. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39180. _this._linkTextures(effect);
  39181. });
  39182. }
  39183. };
  39184. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39185. for (var renderPassName in this._renderPasses) {
  39186. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39187. }
  39188. for (var renderEffectName in this._renderEffectAsPasses) {
  39189. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39190. }
  39191. };
  39192. return PostProcessRenderEffect;
  39193. }());
  39194. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39195. })(BABYLON || (BABYLON = {}));
  39196. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39197. var BABYLON;
  39198. (function (BABYLON) {
  39199. var PostProcessRenderPipeline = (function () {
  39200. function PostProcessRenderPipeline(engine, name) {
  39201. this._engine = engine;
  39202. this._name = name;
  39203. this._renderEffects = {};
  39204. this._renderEffectsForIsolatedPass = {};
  39205. this._cameras = [];
  39206. }
  39207. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39208. get: function () {
  39209. for (var renderEffectName in this._renderEffects) {
  39210. if (!this._renderEffects[renderEffectName].isSupported) {
  39211. return false;
  39212. }
  39213. }
  39214. return true;
  39215. },
  39216. enumerable: true,
  39217. configurable: true
  39218. });
  39219. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39220. this._renderEffects[renderEffect._name] = renderEffect;
  39221. };
  39222. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39223. var renderEffects = this._renderEffects[renderEffectName];
  39224. if (!renderEffects) {
  39225. return;
  39226. }
  39227. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39228. };
  39229. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39230. var renderEffects = this._renderEffects[renderEffectName];
  39231. if (!renderEffects) {
  39232. return;
  39233. }
  39234. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39235. };
  39236. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39237. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39238. var indicesToDelete = [];
  39239. var i;
  39240. for (i = 0; i < _cam.length; i++) {
  39241. var camera = _cam[i];
  39242. var cameraName = camera.name;
  39243. if (this._cameras.indexOf(camera) === -1) {
  39244. this._cameras[cameraName] = camera;
  39245. }
  39246. else if (unique) {
  39247. indicesToDelete.push(i);
  39248. }
  39249. }
  39250. for (i = 0; i < indicesToDelete.length; i++) {
  39251. cameras.splice(indicesToDelete[i], 1);
  39252. }
  39253. for (var renderEffectName in this._renderEffects) {
  39254. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39255. }
  39256. };
  39257. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39258. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39259. for (var renderEffectName in this._renderEffects) {
  39260. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39261. }
  39262. for (var i = 0; i < _cam.length; i++) {
  39263. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39264. }
  39265. };
  39266. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39267. var _this = this;
  39268. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39269. var pass = null;
  39270. var renderEffectName;
  39271. for (renderEffectName in this._renderEffects) {
  39272. pass = this._renderEffects[renderEffectName].getPass(passName);
  39273. if (pass != null) {
  39274. break;
  39275. }
  39276. }
  39277. if (pass === null) {
  39278. return;
  39279. }
  39280. for (renderEffectName in this._renderEffects) {
  39281. this._renderEffects[renderEffectName]._disable(_cam);
  39282. }
  39283. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39284. for (var i = 0; i < _cam.length; i++) {
  39285. var camera = _cam[i];
  39286. var cameraName = camera.name;
  39287. 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); });
  39288. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39289. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39290. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39291. }
  39292. };
  39293. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39294. var _this = this;
  39295. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39296. for (var i = 0; i < _cam.length; i++) {
  39297. var camera = _cam[i];
  39298. var cameraName = camera.name;
  39299. 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); });
  39300. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39301. }
  39302. for (var renderEffectName in this._renderEffects) {
  39303. this._renderEffects[renderEffectName]._enable(_cam);
  39304. }
  39305. };
  39306. PostProcessRenderPipeline.prototype._update = function () {
  39307. for (var renderEffectName in this._renderEffects) {
  39308. this._renderEffects[renderEffectName]._update();
  39309. }
  39310. for (var i = 0; i < this._cameras.length; i++) {
  39311. var cameraName = this._cameras[i].name;
  39312. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39313. this._renderEffectsForIsolatedPass[cameraName]._update();
  39314. }
  39315. }
  39316. };
  39317. PostProcessRenderPipeline.prototype.dispose = function () {
  39318. // Must be implemented by children
  39319. };
  39320. return PostProcessRenderPipeline;
  39321. }());
  39322. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39323. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39324. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39325. })(BABYLON || (BABYLON = {}));
  39326. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39327. var BABYLON;
  39328. (function (BABYLON) {
  39329. var PostProcessRenderPipelineManager = (function () {
  39330. function PostProcessRenderPipelineManager() {
  39331. this._renderPipelines = {};
  39332. }
  39333. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39334. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39335. };
  39336. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39337. var renderPipeline = this._renderPipelines[renderPipelineName];
  39338. if (!renderPipeline) {
  39339. return;
  39340. }
  39341. renderPipeline._attachCameras(cameras, unique);
  39342. };
  39343. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39344. var renderPipeline = this._renderPipelines[renderPipelineName];
  39345. if (!renderPipeline) {
  39346. return;
  39347. }
  39348. renderPipeline._detachCameras(cameras);
  39349. };
  39350. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39351. var renderPipeline = this._renderPipelines[renderPipelineName];
  39352. if (!renderPipeline) {
  39353. return;
  39354. }
  39355. renderPipeline._enableEffect(renderEffectName, cameras);
  39356. };
  39357. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39358. var renderPipeline = this._renderPipelines[renderPipelineName];
  39359. if (!renderPipeline) {
  39360. return;
  39361. }
  39362. renderPipeline._disableEffect(renderEffectName, cameras);
  39363. };
  39364. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39365. var renderPipeline = this._renderPipelines[renderPipelineName];
  39366. if (!renderPipeline) {
  39367. return;
  39368. }
  39369. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39370. };
  39371. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39372. var renderPipeline = this._renderPipelines[renderPipelineName];
  39373. if (!renderPipeline) {
  39374. return;
  39375. }
  39376. renderPipeline._disableDisplayOnlyPass(cameras);
  39377. };
  39378. PostProcessRenderPipelineManager.prototype.update = function () {
  39379. for (var renderPipelineName in this._renderPipelines) {
  39380. var pipeline = this._renderPipelines[renderPipelineName];
  39381. if (!pipeline.isSupported) {
  39382. pipeline.dispose();
  39383. delete this._renderPipelines[renderPipelineName];
  39384. }
  39385. else {
  39386. pipeline._update();
  39387. }
  39388. }
  39389. };
  39390. return PostProcessRenderPipelineManager;
  39391. }());
  39392. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39393. })(BABYLON || (BABYLON = {}));
  39394. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39395. var BABYLON;
  39396. (function (BABYLON) {
  39397. var BoundingBoxRenderer = (function () {
  39398. function BoundingBoxRenderer(scene) {
  39399. this.frontColor = new BABYLON.Color3(1, 1, 1);
  39400. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  39401. this.showBackLines = true;
  39402. this.renderList = new BABYLON.SmartArray(32);
  39403. this._vertexBuffers = {};
  39404. this._scene = scene;
  39405. }
  39406. BoundingBoxRenderer.prototype._prepareRessources = function () {
  39407. if (this._colorShader) {
  39408. return;
  39409. }
  39410. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  39411. attributes: [BABYLON.VertexBuffer.PositionKind],
  39412. uniforms: ["worldViewProjection", "color"]
  39413. });
  39414. var engine = this._scene.getEngine();
  39415. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  39416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  39417. 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]);
  39418. };
  39419. BoundingBoxRenderer.prototype.reset = function () {
  39420. this.renderList.reset();
  39421. };
  39422. BoundingBoxRenderer.prototype.render = function () {
  39423. if (this.renderList.length === 0) {
  39424. return;
  39425. }
  39426. this._prepareRessources();
  39427. if (!this._colorShader.isReady()) {
  39428. return;
  39429. }
  39430. var engine = this._scene.getEngine();
  39431. engine.setDepthWrite(false);
  39432. this._colorShader._preBind();
  39433. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  39434. var boundingBox = this.renderList.data[boundingBoxIndex];
  39435. var min = boundingBox.minimum;
  39436. var max = boundingBox.maximum;
  39437. var diff = max.subtract(min);
  39438. var median = min.add(diff.scale(0.5));
  39439. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  39440. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  39441. .multiply(boundingBox.getWorldMatrix());
  39442. // VBOs
  39443. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  39444. if (this.showBackLines) {
  39445. // Back
  39446. engine.setDepthFunctionToGreaterOrEqual();
  39447. this._scene.resetCachedMaterial();
  39448. this._colorShader.setColor4("color", this.backColor.toColor4());
  39449. this._colorShader.bind(worldMatrix);
  39450. // Draw order
  39451. engine.draw(false, 0, 24);
  39452. }
  39453. // Front
  39454. engine.setDepthFunctionToLess();
  39455. this._scene.resetCachedMaterial();
  39456. this._colorShader.setColor4("color", this.frontColor.toColor4());
  39457. this._colorShader.bind(worldMatrix);
  39458. // Draw order
  39459. engine.draw(false, 0, 24);
  39460. }
  39461. this._colorShader.unbind();
  39462. engine.setDepthFunctionToLessOrEqual();
  39463. engine.setDepthWrite(true);
  39464. };
  39465. BoundingBoxRenderer.prototype.dispose = function () {
  39466. if (!this._colorShader) {
  39467. return;
  39468. }
  39469. this.renderList.dispose();
  39470. this._colorShader.dispose();
  39471. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39472. if (buffer) {
  39473. buffer.dispose();
  39474. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39475. }
  39476. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39477. };
  39478. return BoundingBoxRenderer;
  39479. }());
  39480. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  39481. })(BABYLON || (BABYLON = {}));
  39482. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  39483. var BABYLON;
  39484. (function (BABYLON) {
  39485. var Condition = (function () {
  39486. function Condition(actionManager) {
  39487. this._actionManager = actionManager;
  39488. }
  39489. Condition.prototype.isValid = function () {
  39490. return true;
  39491. };
  39492. Condition.prototype._getProperty = function (propertyPath) {
  39493. return this._actionManager._getProperty(propertyPath);
  39494. };
  39495. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39496. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39497. };
  39498. Condition.prototype.serialize = function () {
  39499. };
  39500. Condition.prototype._serialize = function (serializedCondition) {
  39501. return {
  39502. type: 2,
  39503. children: [],
  39504. name: serializedCondition.name,
  39505. properties: serializedCondition.properties
  39506. };
  39507. };
  39508. return Condition;
  39509. }());
  39510. BABYLON.Condition = Condition;
  39511. var ValueCondition = (function (_super) {
  39512. __extends(ValueCondition, _super);
  39513. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39514. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39515. var _this = _super.call(this, actionManager) || this;
  39516. _this.propertyPath = propertyPath;
  39517. _this.value = value;
  39518. _this.operator = operator;
  39519. _this._target = target;
  39520. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39521. _this._property = _this._getProperty(_this.propertyPath);
  39522. return _this;
  39523. }
  39524. Object.defineProperty(ValueCondition, "IsEqual", {
  39525. get: function () {
  39526. return ValueCondition._IsEqual;
  39527. },
  39528. enumerable: true,
  39529. configurable: true
  39530. });
  39531. Object.defineProperty(ValueCondition, "IsDifferent", {
  39532. get: function () {
  39533. return ValueCondition._IsDifferent;
  39534. },
  39535. enumerable: true,
  39536. configurable: true
  39537. });
  39538. Object.defineProperty(ValueCondition, "IsGreater", {
  39539. get: function () {
  39540. return ValueCondition._IsGreater;
  39541. },
  39542. enumerable: true,
  39543. configurable: true
  39544. });
  39545. Object.defineProperty(ValueCondition, "IsLesser", {
  39546. get: function () {
  39547. return ValueCondition._IsLesser;
  39548. },
  39549. enumerable: true,
  39550. configurable: true
  39551. });
  39552. // Methods
  39553. ValueCondition.prototype.isValid = function () {
  39554. switch (this.operator) {
  39555. case ValueCondition.IsGreater:
  39556. return this._effectiveTarget[this._property] > this.value;
  39557. case ValueCondition.IsLesser:
  39558. return this._effectiveTarget[this._property] < this.value;
  39559. case ValueCondition.IsEqual:
  39560. case ValueCondition.IsDifferent:
  39561. var check;
  39562. if (this.value.equals) {
  39563. check = this.value.equals(this._effectiveTarget[this._property]);
  39564. }
  39565. else {
  39566. check = this.value === this._effectiveTarget[this._property];
  39567. }
  39568. return this.operator === ValueCondition.IsEqual ? check : !check;
  39569. }
  39570. return false;
  39571. };
  39572. ValueCondition.prototype.serialize = function () {
  39573. return this._serialize({
  39574. name: "ValueCondition",
  39575. properties: [
  39576. BABYLON.Action._GetTargetProperty(this._target),
  39577. { name: "propertyPath", value: this.propertyPath },
  39578. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39579. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39580. ]
  39581. });
  39582. };
  39583. ValueCondition.GetOperatorName = function (operator) {
  39584. switch (operator) {
  39585. case ValueCondition._IsEqual: return "IsEqual";
  39586. case ValueCondition._IsDifferent: return "IsDifferent";
  39587. case ValueCondition._IsGreater: return "IsGreater";
  39588. case ValueCondition._IsLesser: return "IsLesser";
  39589. default: return "";
  39590. }
  39591. };
  39592. return ValueCondition;
  39593. }(Condition));
  39594. // Statics
  39595. ValueCondition._IsEqual = 0;
  39596. ValueCondition._IsDifferent = 1;
  39597. ValueCondition._IsGreater = 2;
  39598. ValueCondition._IsLesser = 3;
  39599. BABYLON.ValueCondition = ValueCondition;
  39600. var PredicateCondition = (function (_super) {
  39601. __extends(PredicateCondition, _super);
  39602. function PredicateCondition(actionManager, predicate) {
  39603. var _this = _super.call(this, actionManager) || this;
  39604. _this.predicate = predicate;
  39605. return _this;
  39606. }
  39607. PredicateCondition.prototype.isValid = function () {
  39608. return this.predicate();
  39609. };
  39610. return PredicateCondition;
  39611. }(Condition));
  39612. BABYLON.PredicateCondition = PredicateCondition;
  39613. var StateCondition = (function (_super) {
  39614. __extends(StateCondition, _super);
  39615. function StateCondition(actionManager, target, value) {
  39616. var _this = _super.call(this, actionManager) || this;
  39617. _this.value = value;
  39618. _this._target = target;
  39619. return _this;
  39620. }
  39621. // Methods
  39622. StateCondition.prototype.isValid = function () {
  39623. return this._target.state === this.value;
  39624. };
  39625. StateCondition.prototype.serialize = function () {
  39626. return this._serialize({
  39627. name: "StateCondition",
  39628. properties: [
  39629. BABYLON.Action._GetTargetProperty(this._target),
  39630. { name: "value", value: this.value }
  39631. ]
  39632. });
  39633. };
  39634. return StateCondition;
  39635. }(Condition));
  39636. BABYLON.StateCondition = StateCondition;
  39637. })(BABYLON || (BABYLON = {}));
  39638. //# sourceMappingURL=babylon.condition.js.map
  39639. var BABYLON;
  39640. (function (BABYLON) {
  39641. var Action = (function () {
  39642. function Action(triggerOptions, condition) {
  39643. this.triggerOptions = triggerOptions;
  39644. if (triggerOptions.parameter) {
  39645. this.trigger = triggerOptions.trigger;
  39646. this._triggerParameter = triggerOptions.parameter;
  39647. }
  39648. else {
  39649. this.trigger = triggerOptions;
  39650. }
  39651. this._nextActiveAction = this;
  39652. this._condition = condition;
  39653. }
  39654. // Methods
  39655. Action.prototype._prepare = function () {
  39656. };
  39657. Action.prototype.getTriggerParameter = function () {
  39658. return this._triggerParameter;
  39659. };
  39660. Action.prototype._executeCurrent = function (evt) {
  39661. if (this._nextActiveAction._condition) {
  39662. var condition = this._nextActiveAction._condition;
  39663. var currentRenderId = this._actionManager.getScene().getRenderId();
  39664. // We cache the current evaluation for the current frame
  39665. if (condition._evaluationId === currentRenderId) {
  39666. if (!condition._currentResult) {
  39667. return;
  39668. }
  39669. }
  39670. else {
  39671. condition._evaluationId = currentRenderId;
  39672. if (!condition.isValid()) {
  39673. condition._currentResult = false;
  39674. return;
  39675. }
  39676. condition._currentResult = true;
  39677. }
  39678. }
  39679. this._nextActiveAction.execute(evt);
  39680. this.skipToNextActiveAction();
  39681. };
  39682. Action.prototype.execute = function (evt) {
  39683. };
  39684. Action.prototype.skipToNextActiveAction = function () {
  39685. if (this._nextActiveAction._child) {
  39686. if (!this._nextActiveAction._child._actionManager) {
  39687. this._nextActiveAction._child._actionManager = this._actionManager;
  39688. }
  39689. this._nextActiveAction = this._nextActiveAction._child;
  39690. }
  39691. else {
  39692. this._nextActiveAction = this;
  39693. }
  39694. };
  39695. Action.prototype.then = function (action) {
  39696. this._child = action;
  39697. action._actionManager = this._actionManager;
  39698. action._prepare();
  39699. return action;
  39700. };
  39701. Action.prototype._getProperty = function (propertyPath) {
  39702. return this._actionManager._getProperty(propertyPath);
  39703. };
  39704. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  39705. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39706. };
  39707. Action.prototype.serialize = function (parent) {
  39708. };
  39709. // Called by BABYLON.Action objects in serialize(...). Internal use
  39710. Action.prototype._serialize = function (serializedAction, parent) {
  39711. var serializationObject = {
  39712. type: 1,
  39713. children: [],
  39714. name: serializedAction.name,
  39715. properties: serializedAction.properties || []
  39716. };
  39717. // Serialize child
  39718. if (this._child) {
  39719. this._child.serialize(serializationObject);
  39720. }
  39721. // Check if "this" has a condition
  39722. if (this._condition) {
  39723. var serializedCondition = this._condition.serialize();
  39724. serializedCondition.children.push(serializationObject);
  39725. if (parent) {
  39726. parent.children.push(serializedCondition);
  39727. }
  39728. return serializedCondition;
  39729. }
  39730. if (parent) {
  39731. parent.children.push(serializationObject);
  39732. }
  39733. return serializationObject;
  39734. };
  39735. return Action;
  39736. }());
  39737. Action._SerializeValueAsString = function (value) {
  39738. if (typeof value === "number") {
  39739. return value.toString();
  39740. }
  39741. if (typeof value === "boolean") {
  39742. return value ? "true" : "false";
  39743. }
  39744. if (value instanceof BABYLON.Vector2) {
  39745. return value.x + ", " + value.y;
  39746. }
  39747. if (value instanceof BABYLON.Vector3) {
  39748. return value.x + ", " + value.y + ", " + value.z;
  39749. }
  39750. if (value instanceof BABYLON.Color3) {
  39751. return value.r + ", " + value.g + ", " + value.b;
  39752. }
  39753. if (value instanceof BABYLON.Color4) {
  39754. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  39755. }
  39756. return value; // string
  39757. };
  39758. Action._GetTargetProperty = function (target) {
  39759. return {
  39760. name: "target",
  39761. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  39762. : target instanceof BABYLON.Light ? "LightProperties"
  39763. : target instanceof BABYLON.Camera ? "CameraProperties"
  39764. : "SceneProperties",
  39765. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  39766. };
  39767. };
  39768. BABYLON.Action = Action;
  39769. })(BABYLON || (BABYLON = {}));
  39770. //# sourceMappingURL=babylon.action.js.map
  39771. var BABYLON;
  39772. (function (BABYLON) {
  39773. /**
  39774. * ActionEvent is the event beint sent when an action is triggered.
  39775. */
  39776. var ActionEvent = (function () {
  39777. /**
  39778. * @constructor
  39779. * @param source The mesh or sprite that triggered the action.
  39780. * @param pointerX The X mouse cursor position at the time of the event
  39781. * @param pointerY The Y mouse cursor position at the time of the event
  39782. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  39783. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  39784. */
  39785. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  39786. this.source = source;
  39787. this.pointerX = pointerX;
  39788. this.pointerY = pointerY;
  39789. this.meshUnderPointer = meshUnderPointer;
  39790. this.sourceEvent = sourceEvent;
  39791. this.additionalData = additionalData;
  39792. }
  39793. /**
  39794. * Helper function to auto-create an ActionEvent from a source mesh.
  39795. * @param source The source mesh that triggered the event
  39796. * @param evt {Event} The original (browser) event
  39797. */
  39798. ActionEvent.CreateNew = function (source, evt, additionalData) {
  39799. var scene = source.getScene();
  39800. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39801. };
  39802. /**
  39803. * Helper function to auto-create an ActionEvent from a source mesh.
  39804. * @param source The source sprite that triggered the event
  39805. * @param scene Scene associated with the sprite
  39806. * @param evt {Event} The original (browser) event
  39807. */
  39808. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  39809. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39810. };
  39811. /**
  39812. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  39813. * @param scene the scene where the event occurred
  39814. * @param evt {Event} The original (browser) event
  39815. */
  39816. ActionEvent.CreateNewFromScene = function (scene, evt) {
  39817. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  39818. };
  39819. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  39820. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  39821. };
  39822. return ActionEvent;
  39823. }());
  39824. BABYLON.ActionEvent = ActionEvent;
  39825. /**
  39826. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  39827. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  39828. */
  39829. var ActionManager = (function () {
  39830. function ActionManager(scene) {
  39831. // Members
  39832. this.actions = new Array();
  39833. this.hoverCursor = '';
  39834. this._scene = scene;
  39835. scene._actionManagers.push(this);
  39836. }
  39837. Object.defineProperty(ActionManager, "NothingTrigger", {
  39838. get: function () {
  39839. return ActionManager._NothingTrigger;
  39840. },
  39841. enumerable: true,
  39842. configurable: true
  39843. });
  39844. Object.defineProperty(ActionManager, "OnPickTrigger", {
  39845. get: function () {
  39846. return ActionManager._OnPickTrigger;
  39847. },
  39848. enumerable: true,
  39849. configurable: true
  39850. });
  39851. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  39852. get: function () {
  39853. return ActionManager._OnLeftPickTrigger;
  39854. },
  39855. enumerable: true,
  39856. configurable: true
  39857. });
  39858. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  39859. get: function () {
  39860. return ActionManager._OnRightPickTrigger;
  39861. },
  39862. enumerable: true,
  39863. configurable: true
  39864. });
  39865. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  39866. get: function () {
  39867. return ActionManager._OnCenterPickTrigger;
  39868. },
  39869. enumerable: true,
  39870. configurable: true
  39871. });
  39872. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  39873. get: function () {
  39874. return ActionManager._OnPickDownTrigger;
  39875. },
  39876. enumerable: true,
  39877. configurable: true
  39878. });
  39879. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  39880. get: function () {
  39881. return ActionManager._OnDoublePickTrigger;
  39882. },
  39883. enumerable: true,
  39884. configurable: true
  39885. });
  39886. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  39887. get: function () {
  39888. return ActionManager._OnPickUpTrigger;
  39889. },
  39890. enumerable: true,
  39891. configurable: true
  39892. });
  39893. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  39894. /// This trigger will only be raised if you also declared a OnPickDown
  39895. get: function () {
  39896. return ActionManager._OnPickOutTrigger;
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  39902. get: function () {
  39903. return ActionManager._OnLongPressTrigger;
  39904. },
  39905. enumerable: true,
  39906. configurable: true
  39907. });
  39908. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  39909. get: function () {
  39910. return ActionManager._OnPointerOverTrigger;
  39911. },
  39912. enumerable: true,
  39913. configurable: true
  39914. });
  39915. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  39916. get: function () {
  39917. return ActionManager._OnPointerOutTrigger;
  39918. },
  39919. enumerable: true,
  39920. configurable: true
  39921. });
  39922. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  39923. get: function () {
  39924. return ActionManager._OnEveryFrameTrigger;
  39925. },
  39926. enumerable: true,
  39927. configurable: true
  39928. });
  39929. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  39930. get: function () {
  39931. return ActionManager._OnIntersectionEnterTrigger;
  39932. },
  39933. enumerable: true,
  39934. configurable: true
  39935. });
  39936. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  39937. get: function () {
  39938. return ActionManager._OnIntersectionExitTrigger;
  39939. },
  39940. enumerable: true,
  39941. configurable: true
  39942. });
  39943. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  39944. get: function () {
  39945. return ActionManager._OnKeyDownTrigger;
  39946. },
  39947. enumerable: true,
  39948. configurable: true
  39949. });
  39950. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  39951. get: function () {
  39952. return ActionManager._OnKeyUpTrigger;
  39953. },
  39954. enumerable: true,
  39955. configurable: true
  39956. });
  39957. // Methods
  39958. ActionManager.prototype.dispose = function () {
  39959. var index = this._scene._actionManagers.indexOf(this);
  39960. for (var i = 0; i < this.actions.length; i++) {
  39961. var action = this.actions[i];
  39962. ActionManager.Triggers[action.trigger]--;
  39963. if (ActionManager.Triggers[action.trigger] === 0) {
  39964. delete ActionManager.Triggers[action.trigger];
  39965. }
  39966. }
  39967. if (index > -1) {
  39968. this._scene._actionManagers.splice(index, 1);
  39969. }
  39970. };
  39971. ActionManager.prototype.getScene = function () {
  39972. return this._scene;
  39973. };
  39974. /**
  39975. * Does this action manager handles actions of any of the given triggers
  39976. * @param {number[]} triggers - the triggers to be tested
  39977. * @return {boolean} whether one (or more) of the triggers is handeled
  39978. */
  39979. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  39980. for (var index = 0; index < this.actions.length; index++) {
  39981. var action = this.actions[index];
  39982. if (triggers.indexOf(action.trigger) > -1) {
  39983. return true;
  39984. }
  39985. }
  39986. return false;
  39987. };
  39988. /**
  39989. * Does this action manager handles actions of a given trigger
  39990. * @param {number} trigger - the trigger to be tested
  39991. * @return {boolean} whether the trigger is handeled
  39992. */
  39993. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  39994. for (var index = 0; index < this.actions.length; index++) {
  39995. var action = this.actions[index];
  39996. if (action.trigger === trigger) {
  39997. return true;
  39998. }
  39999. }
  40000. return false;
  40001. };
  40002. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  40003. /**
  40004. * Does this action manager has pointer triggers
  40005. * @return {boolean} whether or not it has pointer triggers
  40006. */
  40007. get: function () {
  40008. for (var index = 0; index < this.actions.length; index++) {
  40009. var action = this.actions[index];
  40010. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  40011. return true;
  40012. }
  40013. }
  40014. return false;
  40015. },
  40016. enumerable: true,
  40017. configurable: true
  40018. });
  40019. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  40020. /**
  40021. * Does this action manager has pick triggers
  40022. * @return {boolean} whether or not it has pick triggers
  40023. */
  40024. get: function () {
  40025. for (var index = 0; index < this.actions.length; index++) {
  40026. var action = this.actions[index];
  40027. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  40028. return true;
  40029. }
  40030. }
  40031. return false;
  40032. },
  40033. enumerable: true,
  40034. configurable: true
  40035. });
  40036. Object.defineProperty(ActionManager, "HasTriggers", {
  40037. /**
  40038. * Does exist one action manager with at least one trigger
  40039. * @return {boolean} whether or not it exists one action manager with one trigger
  40040. **/
  40041. get: function () {
  40042. for (var t in ActionManager.Triggers) {
  40043. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40044. return true;
  40045. }
  40046. }
  40047. return false;
  40048. },
  40049. enumerable: true,
  40050. configurable: true
  40051. });
  40052. Object.defineProperty(ActionManager, "HasPickTriggers", {
  40053. /**
  40054. * Does exist one action manager with at least one pick trigger
  40055. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40056. **/
  40057. get: function () {
  40058. for (var t in ActionManager.Triggers) {
  40059. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40060. var t_int = parseInt(t);
  40061. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40062. return true;
  40063. }
  40064. }
  40065. }
  40066. return false;
  40067. },
  40068. enumerable: true,
  40069. configurable: true
  40070. });
  40071. /**
  40072. * Does exist one action manager that handles actions of a given trigger
  40073. * @param {number} trigger - the trigger to be tested
  40074. * @return {boolean} whether the trigger is handeled by at least one action manager
  40075. **/
  40076. ActionManager.HasSpecificTrigger = function (trigger) {
  40077. for (var t in ActionManager.Triggers) {
  40078. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40079. var t_int = parseInt(t);
  40080. if (t_int === trigger) {
  40081. return true;
  40082. }
  40083. }
  40084. }
  40085. return false;
  40086. };
  40087. /**
  40088. * Registers an action to this action manager
  40089. * @param {BABYLON.Action} action - the action to be registered
  40090. * @return {BABYLON.Action} the action amended (prepared) after registration
  40091. */
  40092. ActionManager.prototype.registerAction = function (action) {
  40093. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40094. if (this.getScene().actionManager !== this) {
  40095. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40096. return null;
  40097. }
  40098. }
  40099. this.actions.push(action);
  40100. if (ActionManager.Triggers[action.trigger]) {
  40101. ActionManager.Triggers[action.trigger]++;
  40102. }
  40103. else {
  40104. ActionManager.Triggers[action.trigger] = 1;
  40105. }
  40106. action._actionManager = this;
  40107. action._prepare();
  40108. return action;
  40109. };
  40110. /**
  40111. * Process a specific trigger
  40112. * @param {number} trigger - the trigger to process
  40113. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40114. */
  40115. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40116. for (var index = 0; index < this.actions.length; index++) {
  40117. var action = this.actions[index];
  40118. if (action.trigger === trigger) {
  40119. if (trigger === ActionManager.OnKeyUpTrigger
  40120. || trigger === ActionManager.OnKeyDownTrigger) {
  40121. var parameter = action.getTriggerParameter();
  40122. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40123. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40124. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40125. if (actualkey !== parameter.toLowerCase()) {
  40126. continue;
  40127. }
  40128. }
  40129. }
  40130. action._executeCurrent(evt);
  40131. }
  40132. }
  40133. };
  40134. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40135. var properties = propertyPath.split(".");
  40136. for (var index = 0; index < properties.length - 1; index++) {
  40137. target = target[properties[index]];
  40138. }
  40139. return target;
  40140. };
  40141. ActionManager.prototype._getProperty = function (propertyPath) {
  40142. var properties = propertyPath.split(".");
  40143. return properties[properties.length - 1];
  40144. };
  40145. ActionManager.prototype.serialize = function (name) {
  40146. var root = {
  40147. children: [],
  40148. name: name,
  40149. type: 3,
  40150. properties: [] // Empty for root but required
  40151. };
  40152. for (var i = 0; i < this.actions.length; i++) {
  40153. var triggerObject = {
  40154. type: 0,
  40155. children: [],
  40156. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40157. properties: []
  40158. };
  40159. var triggerOptions = this.actions[i].triggerOptions;
  40160. if (triggerOptions && typeof triggerOptions !== "number") {
  40161. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40162. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40163. }
  40164. else {
  40165. var parameter = {};
  40166. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40167. if (triggerOptions.parameter.mesh) {
  40168. parameter._meshId = triggerOptions.parameter.mesh.id;
  40169. }
  40170. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40171. }
  40172. }
  40173. // Serialize child action, recursively
  40174. this.actions[i].serialize(triggerObject);
  40175. // Add serialized trigger
  40176. root.children.push(triggerObject);
  40177. }
  40178. return root;
  40179. };
  40180. ActionManager.Parse = function (parsedActions, object, scene) {
  40181. var actionManager = new BABYLON.ActionManager(scene);
  40182. if (object === null)
  40183. scene.actionManager = actionManager;
  40184. else
  40185. object.actionManager = actionManager;
  40186. // instanciate a new object
  40187. var instanciate = function (name, params) {
  40188. var newInstance = Object.create(BABYLON[name].prototype);
  40189. newInstance.constructor.apply(newInstance, params);
  40190. return newInstance;
  40191. };
  40192. var parseParameter = function (name, value, target, propertyPath) {
  40193. if (propertyPath === null) {
  40194. // String, boolean or float
  40195. var floatValue = parseFloat(value);
  40196. if (value === "true" || value === "false")
  40197. return value === "true";
  40198. else
  40199. return isNaN(floatValue) ? value : floatValue;
  40200. }
  40201. var effectiveTarget = propertyPath.split(".");
  40202. var values = value.split(",");
  40203. // Get effective Target
  40204. for (var i = 0; i < effectiveTarget.length; i++) {
  40205. target = target[effectiveTarget[i]];
  40206. }
  40207. // Return appropriate value with its type
  40208. if (typeof (target) === "boolean")
  40209. return values[0] === "true";
  40210. if (typeof (target) === "string")
  40211. return values[0];
  40212. // Parameters with multiple values such as Vector3 etc.
  40213. var split = new Array();
  40214. for (var i = 0; i < values.length; i++)
  40215. split.push(parseFloat(values[i]));
  40216. if (target instanceof BABYLON.Vector3)
  40217. return BABYLON.Vector3.FromArray(split);
  40218. if (target instanceof BABYLON.Vector4)
  40219. return BABYLON.Vector4.FromArray(split);
  40220. if (target instanceof BABYLON.Color3)
  40221. return BABYLON.Color3.FromArray(split);
  40222. if (target instanceof BABYLON.Color4)
  40223. return BABYLON.Color4.FromArray(split);
  40224. return parseFloat(values[0]);
  40225. };
  40226. // traverse graph per trigger
  40227. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40228. if (combineArray === void 0) { combineArray = null; }
  40229. if (parsedAction.detached)
  40230. return;
  40231. var parameters = new Array();
  40232. var target = null;
  40233. var propertyPath = null;
  40234. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40235. // Parameters
  40236. if (parsedAction.type === 2)
  40237. parameters.push(actionManager);
  40238. else
  40239. parameters.push(trigger);
  40240. if (combine) {
  40241. var actions = new Array();
  40242. for (var j = 0; j < parsedAction.combine.length; j++) {
  40243. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40244. }
  40245. parameters.push(actions);
  40246. }
  40247. else {
  40248. for (var i = 0; i < parsedAction.properties.length; i++) {
  40249. var value = parsedAction.properties[i].value;
  40250. var name = parsedAction.properties[i].name;
  40251. var targetType = parsedAction.properties[i].targetType;
  40252. if (name === "target")
  40253. if (targetType !== null && targetType === "SceneProperties")
  40254. value = target = scene;
  40255. else
  40256. value = target = scene.getNodeByName(value);
  40257. else if (name === "parent")
  40258. value = scene.getNodeByName(value);
  40259. else if (name === "sound")
  40260. value = scene.getSoundByName(value);
  40261. else if (name !== "propertyPath") {
  40262. if (parsedAction.type === 2 && name === "operator")
  40263. value = BABYLON.ValueCondition[value];
  40264. else
  40265. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40266. }
  40267. else {
  40268. propertyPath = value;
  40269. }
  40270. parameters.push(value);
  40271. }
  40272. }
  40273. if (combineArray === null) {
  40274. parameters.push(condition);
  40275. }
  40276. else {
  40277. parameters.push(null);
  40278. }
  40279. // If interpolate value action
  40280. if (parsedAction.name === "InterpolateValueAction") {
  40281. var param = parameters[parameters.length - 2];
  40282. parameters[parameters.length - 1] = param;
  40283. parameters[parameters.length - 2] = condition;
  40284. }
  40285. // Action or condition(s) and not CombineAction
  40286. var newAction = instanciate(parsedAction.name, parameters);
  40287. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40288. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40289. if (action)
  40290. action.then(nothing);
  40291. else
  40292. actionManager.registerAction(nothing);
  40293. action = nothing;
  40294. }
  40295. if (combineArray === null) {
  40296. if (newAction instanceof BABYLON.Condition) {
  40297. condition = newAction;
  40298. newAction = action;
  40299. }
  40300. else {
  40301. condition = null;
  40302. if (action)
  40303. action.then(newAction);
  40304. else
  40305. actionManager.registerAction(newAction);
  40306. }
  40307. }
  40308. else {
  40309. combineArray.push(newAction);
  40310. }
  40311. for (var i = 0; i < parsedAction.children.length; i++)
  40312. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40313. };
  40314. // triggers
  40315. for (var i = 0; i < parsedActions.children.length; i++) {
  40316. var triggerParams;
  40317. var trigger = parsedActions.children[i];
  40318. if (trigger.properties.length > 0) {
  40319. var param = trigger.properties[0].value;
  40320. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40321. if (value._meshId) {
  40322. value.mesh = scene.getMeshByID(value._meshId);
  40323. }
  40324. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  40325. }
  40326. else
  40327. triggerParams = BABYLON.ActionManager[trigger.name];
  40328. for (var j = 0; j < trigger.children.length; j++) {
  40329. if (!trigger.detached)
  40330. traverse(trigger.children[j], triggerParams, null, null);
  40331. }
  40332. }
  40333. };
  40334. ActionManager.GetTriggerName = function (trigger) {
  40335. switch (trigger) {
  40336. case 0: return "NothingTrigger";
  40337. case 1: return "OnPickTrigger";
  40338. case 2: return "OnLeftPickTrigger";
  40339. case 3: return "OnRightPickTrigger";
  40340. case 4: return "OnCenterPickTrigger";
  40341. case 5: return "OnPickDownTrigger";
  40342. case 6: return "OnPickUpTrigger";
  40343. case 7: return "OnLongPressTrigger";
  40344. case 8: return "OnPointerOverTrigger";
  40345. case 9: return "OnPointerOutTrigger";
  40346. case 10: return "OnEveryFrameTrigger";
  40347. case 11: return "OnIntersectionEnterTrigger";
  40348. case 12: return "OnIntersectionExitTrigger";
  40349. case 13: return "OnKeyDownTrigger";
  40350. case 14: return "OnKeyUpTrigger";
  40351. case 15: return "OnPickOutTrigger";
  40352. default: return "";
  40353. }
  40354. };
  40355. return ActionManager;
  40356. }());
  40357. // Statics
  40358. ActionManager._NothingTrigger = 0;
  40359. ActionManager._OnPickTrigger = 1;
  40360. ActionManager._OnLeftPickTrigger = 2;
  40361. ActionManager._OnRightPickTrigger = 3;
  40362. ActionManager._OnCenterPickTrigger = 4;
  40363. ActionManager._OnPickDownTrigger = 5;
  40364. ActionManager._OnDoublePickTrigger = 6;
  40365. ActionManager._OnPickUpTrigger = 7;
  40366. ActionManager._OnLongPressTrigger = 8;
  40367. ActionManager._OnPointerOverTrigger = 9;
  40368. ActionManager._OnPointerOutTrigger = 10;
  40369. ActionManager._OnEveryFrameTrigger = 11;
  40370. ActionManager._OnIntersectionEnterTrigger = 12;
  40371. ActionManager._OnIntersectionExitTrigger = 13;
  40372. ActionManager._OnKeyDownTrigger = 14;
  40373. ActionManager._OnKeyUpTrigger = 15;
  40374. ActionManager._OnPickOutTrigger = 16;
  40375. ActionManager.Triggers = {};
  40376. BABYLON.ActionManager = ActionManager;
  40377. })(BABYLON || (BABYLON = {}));
  40378. //# sourceMappingURL=babylon.actionManager.js.map
  40379. var BABYLON;
  40380. (function (BABYLON) {
  40381. var InterpolateValueAction = (function (_super) {
  40382. __extends(InterpolateValueAction, _super);
  40383. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40384. if (duration === void 0) { duration = 1000; }
  40385. var _this = _super.call(this, triggerOptions, condition) || this;
  40386. _this.propertyPath = propertyPath;
  40387. _this.value = value;
  40388. _this.duration = duration;
  40389. _this.stopOtherAnimations = stopOtherAnimations;
  40390. _this.onInterpolationDone = onInterpolationDone;
  40391. _this._target = _this._effectiveTarget = target;
  40392. return _this;
  40393. }
  40394. InterpolateValueAction.prototype._prepare = function () {
  40395. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40396. this._property = this._getProperty(this.propertyPath);
  40397. };
  40398. InterpolateValueAction.prototype.execute = function () {
  40399. var scene = this._actionManager.getScene();
  40400. var keys = [
  40401. {
  40402. frame: 0,
  40403. value: this._effectiveTarget[this._property]
  40404. }, {
  40405. frame: 100,
  40406. value: this.value
  40407. }
  40408. ];
  40409. var dataType;
  40410. if (typeof this.value === "number") {
  40411. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40412. }
  40413. else if (this.value instanceof BABYLON.Color3) {
  40414. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40415. }
  40416. else if (this.value instanceof BABYLON.Vector3) {
  40417. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40418. }
  40419. else if (this.value instanceof BABYLON.Matrix) {
  40420. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40421. }
  40422. else if (this.value instanceof BABYLON.Quaternion) {
  40423. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40424. }
  40425. else {
  40426. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40427. return;
  40428. }
  40429. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40430. animation.setKeys(keys);
  40431. if (this.stopOtherAnimations) {
  40432. scene.stopAnimation(this._effectiveTarget);
  40433. }
  40434. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  40435. };
  40436. InterpolateValueAction.prototype.serialize = function (parent) {
  40437. return _super.prototype._serialize.call(this, {
  40438. name: "InterpolateValueAction",
  40439. properties: [
  40440. BABYLON.Action._GetTargetProperty(this._target),
  40441. { name: "propertyPath", value: this.propertyPath },
  40442. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40443. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40444. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40445. ]
  40446. }, parent);
  40447. };
  40448. return InterpolateValueAction;
  40449. }(BABYLON.Action));
  40450. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40451. })(BABYLON || (BABYLON = {}));
  40452. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40453. var BABYLON;
  40454. (function (BABYLON) {
  40455. var SwitchBooleanAction = (function (_super) {
  40456. __extends(SwitchBooleanAction, _super);
  40457. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40458. var _this = _super.call(this, triggerOptions, condition) || this;
  40459. _this.propertyPath = propertyPath;
  40460. _this._target = _this._effectiveTarget = target;
  40461. return _this;
  40462. }
  40463. SwitchBooleanAction.prototype._prepare = function () {
  40464. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40465. this._property = this._getProperty(this.propertyPath);
  40466. };
  40467. SwitchBooleanAction.prototype.execute = function () {
  40468. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40469. };
  40470. SwitchBooleanAction.prototype.serialize = function (parent) {
  40471. return _super.prototype._serialize.call(this, {
  40472. name: "SwitchBooleanAction",
  40473. properties: [
  40474. BABYLON.Action._GetTargetProperty(this._target),
  40475. { name: "propertyPath", value: this.propertyPath }
  40476. ]
  40477. }, parent);
  40478. };
  40479. return SwitchBooleanAction;
  40480. }(BABYLON.Action));
  40481. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40482. var SetStateAction = (function (_super) {
  40483. __extends(SetStateAction, _super);
  40484. function SetStateAction(triggerOptions, target, value, condition) {
  40485. var _this = _super.call(this, triggerOptions, condition) || this;
  40486. _this.value = value;
  40487. _this._target = target;
  40488. return _this;
  40489. }
  40490. SetStateAction.prototype.execute = function () {
  40491. this._target.state = this.value;
  40492. };
  40493. SetStateAction.prototype.serialize = function (parent) {
  40494. return _super.prototype._serialize.call(this, {
  40495. name: "SetStateAction",
  40496. properties: [
  40497. BABYLON.Action._GetTargetProperty(this._target),
  40498. { name: "value", value: this.value }
  40499. ]
  40500. }, parent);
  40501. };
  40502. return SetStateAction;
  40503. }(BABYLON.Action));
  40504. BABYLON.SetStateAction = SetStateAction;
  40505. var SetValueAction = (function (_super) {
  40506. __extends(SetValueAction, _super);
  40507. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40508. var _this = _super.call(this, triggerOptions, condition) || this;
  40509. _this.propertyPath = propertyPath;
  40510. _this.value = value;
  40511. _this._target = _this._effectiveTarget = target;
  40512. return _this;
  40513. }
  40514. SetValueAction.prototype._prepare = function () {
  40515. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40516. this._property = this._getProperty(this.propertyPath);
  40517. };
  40518. SetValueAction.prototype.execute = function () {
  40519. this._effectiveTarget[this._property] = this.value;
  40520. if (this._target.markAsDirty) {
  40521. this._target.markAsDirty(this._property);
  40522. }
  40523. };
  40524. SetValueAction.prototype.serialize = function (parent) {
  40525. return _super.prototype._serialize.call(this, {
  40526. name: "SetValueAction",
  40527. properties: [
  40528. BABYLON.Action._GetTargetProperty(this._target),
  40529. { name: "propertyPath", value: this.propertyPath },
  40530. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40531. ]
  40532. }, parent);
  40533. };
  40534. return SetValueAction;
  40535. }(BABYLON.Action));
  40536. BABYLON.SetValueAction = SetValueAction;
  40537. var IncrementValueAction = (function (_super) {
  40538. __extends(IncrementValueAction, _super);
  40539. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40540. var _this = _super.call(this, triggerOptions, condition) || this;
  40541. _this.propertyPath = propertyPath;
  40542. _this.value = value;
  40543. _this._target = _this._effectiveTarget = target;
  40544. return _this;
  40545. }
  40546. IncrementValueAction.prototype._prepare = function () {
  40547. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40548. this._property = this._getProperty(this.propertyPath);
  40549. if (typeof this._effectiveTarget[this._property] !== "number") {
  40550. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40551. }
  40552. };
  40553. IncrementValueAction.prototype.execute = function () {
  40554. this._effectiveTarget[this._property] += this.value;
  40555. if (this._target.markAsDirty) {
  40556. this._target.markAsDirty(this._property);
  40557. }
  40558. };
  40559. IncrementValueAction.prototype.serialize = function (parent) {
  40560. return _super.prototype._serialize.call(this, {
  40561. name: "IncrementValueAction",
  40562. properties: [
  40563. BABYLON.Action._GetTargetProperty(this._target),
  40564. { name: "propertyPath", value: this.propertyPath },
  40565. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40566. ]
  40567. }, parent);
  40568. };
  40569. return IncrementValueAction;
  40570. }(BABYLON.Action));
  40571. BABYLON.IncrementValueAction = IncrementValueAction;
  40572. var PlayAnimationAction = (function (_super) {
  40573. __extends(PlayAnimationAction, _super);
  40574. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40575. var _this = _super.call(this, triggerOptions, condition) || this;
  40576. _this.from = from;
  40577. _this.to = to;
  40578. _this.loop = loop;
  40579. _this._target = target;
  40580. return _this;
  40581. }
  40582. PlayAnimationAction.prototype._prepare = function () {
  40583. };
  40584. PlayAnimationAction.prototype.execute = function () {
  40585. var scene = this._actionManager.getScene();
  40586. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  40587. };
  40588. PlayAnimationAction.prototype.serialize = function (parent) {
  40589. return _super.prototype._serialize.call(this, {
  40590. name: "PlayAnimationAction",
  40591. properties: [
  40592. BABYLON.Action._GetTargetProperty(this._target),
  40593. { name: "from", value: String(this.from) },
  40594. { name: "to", value: String(this.to) },
  40595. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  40596. ]
  40597. }, parent);
  40598. };
  40599. return PlayAnimationAction;
  40600. }(BABYLON.Action));
  40601. BABYLON.PlayAnimationAction = PlayAnimationAction;
  40602. var StopAnimationAction = (function (_super) {
  40603. __extends(StopAnimationAction, _super);
  40604. function StopAnimationAction(triggerOptions, target, condition) {
  40605. var _this = _super.call(this, triggerOptions, condition) || this;
  40606. _this._target = target;
  40607. return _this;
  40608. }
  40609. StopAnimationAction.prototype._prepare = function () {
  40610. };
  40611. StopAnimationAction.prototype.execute = function () {
  40612. var scene = this._actionManager.getScene();
  40613. scene.stopAnimation(this._target);
  40614. };
  40615. StopAnimationAction.prototype.serialize = function (parent) {
  40616. return _super.prototype._serialize.call(this, {
  40617. name: "StopAnimationAction",
  40618. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  40619. }, parent);
  40620. };
  40621. return StopAnimationAction;
  40622. }(BABYLON.Action));
  40623. BABYLON.StopAnimationAction = StopAnimationAction;
  40624. var DoNothingAction = (function (_super) {
  40625. __extends(DoNothingAction, _super);
  40626. function DoNothingAction(triggerOptions, condition) {
  40627. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  40628. return _super.call(this, triggerOptions, condition) || this;
  40629. }
  40630. DoNothingAction.prototype.execute = function () {
  40631. };
  40632. DoNothingAction.prototype.serialize = function (parent) {
  40633. return _super.prototype._serialize.call(this, {
  40634. name: "DoNothingAction",
  40635. properties: []
  40636. }, parent);
  40637. };
  40638. return DoNothingAction;
  40639. }(BABYLON.Action));
  40640. BABYLON.DoNothingAction = DoNothingAction;
  40641. var CombineAction = (function (_super) {
  40642. __extends(CombineAction, _super);
  40643. function CombineAction(triggerOptions, children, condition) {
  40644. var _this = _super.call(this, triggerOptions, condition) || this;
  40645. _this.children = children;
  40646. return _this;
  40647. }
  40648. CombineAction.prototype._prepare = function () {
  40649. for (var index = 0; index < this.children.length; index++) {
  40650. this.children[index]._actionManager = this._actionManager;
  40651. this.children[index]._prepare();
  40652. }
  40653. };
  40654. CombineAction.prototype.execute = function (evt) {
  40655. for (var index = 0; index < this.children.length; index++) {
  40656. this.children[index].execute(evt);
  40657. }
  40658. };
  40659. CombineAction.prototype.serialize = function (parent) {
  40660. var serializationObject = _super.prototype._serialize.call(this, {
  40661. name: "CombineAction",
  40662. properties: [],
  40663. combine: []
  40664. }, parent);
  40665. for (var i = 0; i < this.children.length; i++) {
  40666. serializationObject.combine.push(this.children[i].serialize(null));
  40667. }
  40668. return serializationObject;
  40669. };
  40670. return CombineAction;
  40671. }(BABYLON.Action));
  40672. BABYLON.CombineAction = CombineAction;
  40673. var ExecuteCodeAction = (function (_super) {
  40674. __extends(ExecuteCodeAction, _super);
  40675. function ExecuteCodeAction(triggerOptions, func, condition) {
  40676. var _this = _super.call(this, triggerOptions, condition) || this;
  40677. _this.func = func;
  40678. return _this;
  40679. }
  40680. ExecuteCodeAction.prototype.execute = function (evt) {
  40681. this.func(evt);
  40682. };
  40683. return ExecuteCodeAction;
  40684. }(BABYLON.Action));
  40685. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  40686. var SetParentAction = (function (_super) {
  40687. __extends(SetParentAction, _super);
  40688. function SetParentAction(triggerOptions, target, parent, condition) {
  40689. var _this = _super.call(this, triggerOptions, condition) || this;
  40690. _this._target = target;
  40691. _this._parent = parent;
  40692. return _this;
  40693. }
  40694. SetParentAction.prototype._prepare = function () {
  40695. };
  40696. SetParentAction.prototype.execute = function () {
  40697. if (this._target.parent === this._parent) {
  40698. return;
  40699. }
  40700. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  40701. invertParentWorldMatrix.invert();
  40702. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  40703. this._target.parent = this._parent;
  40704. };
  40705. SetParentAction.prototype.serialize = function (parent) {
  40706. return _super.prototype._serialize.call(this, {
  40707. name: "SetParentAction",
  40708. properties: [
  40709. BABYLON.Action._GetTargetProperty(this._target),
  40710. BABYLON.Action._GetTargetProperty(this._parent),
  40711. ]
  40712. }, parent);
  40713. };
  40714. return SetParentAction;
  40715. }(BABYLON.Action));
  40716. BABYLON.SetParentAction = SetParentAction;
  40717. var PlaySoundAction = (function (_super) {
  40718. __extends(PlaySoundAction, _super);
  40719. function PlaySoundAction(triggerOptions, sound, condition) {
  40720. var _this = _super.call(this, triggerOptions, condition) || this;
  40721. _this._sound = sound;
  40722. return _this;
  40723. }
  40724. PlaySoundAction.prototype._prepare = function () {
  40725. };
  40726. PlaySoundAction.prototype.execute = function () {
  40727. if (this._sound !== undefined)
  40728. this._sound.play();
  40729. };
  40730. PlaySoundAction.prototype.serialize = function (parent) {
  40731. return _super.prototype._serialize.call(this, {
  40732. name: "PlaySoundAction",
  40733. properties: [{ name: "sound", value: this._sound.name }]
  40734. }, parent);
  40735. };
  40736. return PlaySoundAction;
  40737. }(BABYLON.Action));
  40738. BABYLON.PlaySoundAction = PlaySoundAction;
  40739. var StopSoundAction = (function (_super) {
  40740. __extends(StopSoundAction, _super);
  40741. function StopSoundAction(triggerOptions, sound, condition) {
  40742. var _this = _super.call(this, triggerOptions, condition) || this;
  40743. _this._sound = sound;
  40744. return _this;
  40745. }
  40746. StopSoundAction.prototype._prepare = function () {
  40747. };
  40748. StopSoundAction.prototype.execute = function () {
  40749. if (this._sound !== undefined)
  40750. this._sound.stop();
  40751. };
  40752. StopSoundAction.prototype.serialize = function (parent) {
  40753. return _super.prototype._serialize.call(this, {
  40754. name: "StopSoundAction",
  40755. properties: [{ name: "sound", value: this._sound.name }]
  40756. }, parent);
  40757. };
  40758. return StopSoundAction;
  40759. }(BABYLON.Action));
  40760. BABYLON.StopSoundAction = StopSoundAction;
  40761. })(BABYLON || (BABYLON = {}));
  40762. //# sourceMappingURL=babylon.directActions.js.map
  40763. var BABYLON;
  40764. (function (BABYLON) {
  40765. var Geometry = (function () {
  40766. function Geometry(id, scene, vertexData, updatable, mesh) {
  40767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40768. this._totalVertices = 0;
  40769. this._isDisposed = false;
  40770. this.id = id;
  40771. this._engine = scene.getEngine();
  40772. this._meshes = [];
  40773. this._scene = scene;
  40774. //Init vertex buffer cache
  40775. this._vertexBuffers = {};
  40776. this._indices = [];
  40777. // vertexData
  40778. if (vertexData) {
  40779. this.setAllVerticesData(vertexData, updatable);
  40780. }
  40781. else {
  40782. this._totalVertices = 0;
  40783. this._indices = [];
  40784. }
  40785. if (this._engine.getCaps().vertexArrayObject) {
  40786. this._vertexArrayObjects = {};
  40787. }
  40788. // applyToMesh
  40789. if (mesh) {
  40790. if (mesh instanceof BABYLON.LinesMesh) {
  40791. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40792. this.updateExtend();
  40793. }
  40794. this.applyToMesh(mesh);
  40795. mesh.computeWorldMatrix(true);
  40796. }
  40797. }
  40798. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40799. /**
  40800. * 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
  40801. * @returns The Bias Vector
  40802. */
  40803. get: function () {
  40804. return this._boundingBias;
  40805. },
  40806. set: function (value) {
  40807. if (this._boundingBias && this._boundingBias.equals(value)) {
  40808. return;
  40809. }
  40810. this._boundingBias = value.clone();
  40811. this.updateBoundingInfo(true, null);
  40812. },
  40813. enumerable: true,
  40814. configurable: true
  40815. });
  40816. Object.defineProperty(Geometry.prototype, "extend", {
  40817. get: function () {
  40818. return this._extend;
  40819. },
  40820. enumerable: true,
  40821. configurable: true
  40822. });
  40823. Geometry.prototype.getScene = function () {
  40824. return this._scene;
  40825. };
  40826. Geometry.prototype.getEngine = function () {
  40827. return this._engine;
  40828. };
  40829. Geometry.prototype.isReady = function () {
  40830. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40831. };
  40832. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40833. get: function () {
  40834. for (var index = 0; index < this._meshes.length; index++) {
  40835. if (!this._meshes[index].doNotSerialize) {
  40836. return false;
  40837. }
  40838. }
  40839. return true;
  40840. },
  40841. enumerable: true,
  40842. configurable: true
  40843. });
  40844. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40845. vertexData.applyToGeometry(this, updatable);
  40846. this.notifyUpdate();
  40847. };
  40848. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40849. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40850. this.setVerticesBuffer(buffer);
  40851. };
  40852. Geometry.prototype.setVerticesBuffer = function (buffer) {
  40853. var kind = buffer.getKind();
  40854. if (this._vertexBuffers[kind]) {
  40855. this._vertexBuffers[kind].dispose();
  40856. }
  40857. this._vertexBuffers[kind] = buffer;
  40858. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40859. var data = buffer.getData();
  40860. var stride = buffer.getStrideSize();
  40861. this._totalVertices = data.length / stride;
  40862. this.updateExtend(data, stride);
  40863. var meshes = this._meshes;
  40864. var numOfMeshes = meshes.length;
  40865. for (var index = 0; index < numOfMeshes; index++) {
  40866. var mesh = meshes[index];
  40867. mesh._resetPointsArrayCache();
  40868. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40869. mesh._createGlobalSubMesh();
  40870. mesh.computeWorldMatrix(true);
  40871. }
  40872. }
  40873. this.notifyUpdate(kind);
  40874. if (this._vertexArrayObjects) {
  40875. this._disposeVertexArrayObjects();
  40876. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40877. }
  40878. };
  40879. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  40880. var vertexBuffer = this.getVertexBuffer(kind);
  40881. if (!vertexBuffer) {
  40882. return;
  40883. }
  40884. vertexBuffer.updateDirectly(data, offset);
  40885. this.notifyUpdate(kind);
  40886. };
  40887. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40888. var vertexBuffer = this.getVertexBuffer(kind);
  40889. if (!vertexBuffer) {
  40890. return;
  40891. }
  40892. vertexBuffer.update(data);
  40893. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40894. var stride = vertexBuffer.getStrideSize();
  40895. this._totalVertices = data.length / stride;
  40896. this.updateBoundingInfo(updateExtends, data);
  40897. }
  40898. this.notifyUpdate(kind);
  40899. };
  40900. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  40901. if (updateExtends) {
  40902. this.updateExtend(data);
  40903. }
  40904. var meshes = this._meshes;
  40905. var numOfMeshes = meshes.length;
  40906. for (var index = 0; index < numOfMeshes; index++) {
  40907. var mesh = meshes[index];
  40908. mesh._resetPointsArrayCache();
  40909. if (updateExtends) {
  40910. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40911. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40912. var subMesh = mesh.subMeshes[subIndex];
  40913. subMesh.refreshBoundingInfo();
  40914. }
  40915. }
  40916. }
  40917. };
  40918. Geometry.prototype._bind = function (effect, indexToBind) {
  40919. if (indexToBind === void 0) { indexToBind = undefined; }
  40920. if (indexToBind === undefined) {
  40921. indexToBind = this._indexBuffer;
  40922. }
  40923. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40924. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  40925. return;
  40926. }
  40927. // Using VAO
  40928. if (!this._vertexArrayObjects[effect.key]) {
  40929. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  40930. }
  40931. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40932. };
  40933. Geometry.prototype.getTotalVertices = function () {
  40934. if (!this.isReady()) {
  40935. return 0;
  40936. }
  40937. return this._totalVertices;
  40938. };
  40939. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  40940. var vertexBuffer = this.getVertexBuffer(kind);
  40941. if (!vertexBuffer) {
  40942. return null;
  40943. }
  40944. var orig = vertexBuffer.getData();
  40945. if (!copyWhenShared || this._meshes.length === 1) {
  40946. return orig;
  40947. }
  40948. else {
  40949. var len = orig.length;
  40950. var copy = [];
  40951. for (var i = 0; i < len; i++) {
  40952. copy.push(orig[i]);
  40953. }
  40954. return copy;
  40955. }
  40956. };
  40957. Geometry.prototype.getVertexBuffer = function (kind) {
  40958. if (!this.isReady()) {
  40959. return null;
  40960. }
  40961. return this._vertexBuffers[kind];
  40962. };
  40963. Geometry.prototype.getVertexBuffers = function () {
  40964. if (!this.isReady()) {
  40965. return null;
  40966. }
  40967. return this._vertexBuffers;
  40968. };
  40969. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40970. if (!this._vertexBuffers) {
  40971. if (this._delayInfo) {
  40972. return this._delayInfo.indexOf(kind) !== -1;
  40973. }
  40974. return false;
  40975. }
  40976. return this._vertexBuffers[kind] !== undefined;
  40977. };
  40978. Geometry.prototype.getVerticesDataKinds = function () {
  40979. var result = [];
  40980. var kind;
  40981. if (!this._vertexBuffers && this._delayInfo) {
  40982. for (kind in this._delayInfo) {
  40983. result.push(kind);
  40984. }
  40985. }
  40986. else {
  40987. for (kind in this._vertexBuffers) {
  40988. result.push(kind);
  40989. }
  40990. }
  40991. return result;
  40992. };
  40993. Geometry.prototype.setIndices = function (indices, totalVertices) {
  40994. if (this._indexBuffer) {
  40995. this._engine._releaseBuffer(this._indexBuffer);
  40996. }
  40997. this._disposeVertexArrayObjects();
  40998. this._indices = indices;
  40999. if (this._meshes.length !== 0 && this._indices) {
  41000. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41001. }
  41002. if (totalVertices !== undefined) {
  41003. this._totalVertices = totalVertices;
  41004. }
  41005. var meshes = this._meshes;
  41006. var numOfMeshes = meshes.length;
  41007. for (var index = 0; index < numOfMeshes; index++) {
  41008. meshes[index]._createGlobalSubMesh();
  41009. }
  41010. this.notifyUpdate();
  41011. };
  41012. Geometry.prototype.getTotalIndices = function () {
  41013. if (!this.isReady()) {
  41014. return 0;
  41015. }
  41016. return this._indices.length;
  41017. };
  41018. Geometry.prototype.getIndices = function (copyWhenShared) {
  41019. if (!this.isReady()) {
  41020. return null;
  41021. }
  41022. var orig = this._indices;
  41023. if (!copyWhenShared || this._meshes.length === 1) {
  41024. return orig;
  41025. }
  41026. else {
  41027. var len = orig.length;
  41028. var copy = [];
  41029. for (var i = 0; i < len; i++) {
  41030. copy.push(orig[i]);
  41031. }
  41032. return copy;
  41033. }
  41034. };
  41035. Geometry.prototype.getIndexBuffer = function () {
  41036. if (!this.isReady()) {
  41037. return null;
  41038. }
  41039. return this._indexBuffer;
  41040. };
  41041. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41042. var meshes = this._meshes;
  41043. var index = meshes.indexOf(mesh);
  41044. if (index === -1) {
  41045. return;
  41046. }
  41047. meshes.splice(index, 1);
  41048. mesh._geometry = null;
  41049. if (meshes.length === 0 && shouldDispose) {
  41050. this.dispose();
  41051. }
  41052. };
  41053. Geometry.prototype.applyToMesh = function (mesh) {
  41054. if (mesh._geometry === this) {
  41055. return;
  41056. }
  41057. var previousGeometry = mesh._geometry;
  41058. if (previousGeometry) {
  41059. previousGeometry.releaseForMesh(mesh);
  41060. }
  41061. var meshes = this._meshes;
  41062. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41063. mesh._geometry = this;
  41064. this._scene.pushGeometry(this);
  41065. meshes.push(mesh);
  41066. if (this.isReady()) {
  41067. this._applyToMesh(mesh);
  41068. }
  41069. else {
  41070. mesh._boundingInfo = this._boundingInfo;
  41071. }
  41072. };
  41073. Geometry.prototype.updateExtend = function (data, stride) {
  41074. if (data === void 0) { data = null; }
  41075. if (!data) {
  41076. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  41077. }
  41078. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  41079. };
  41080. Geometry.prototype._applyToMesh = function (mesh) {
  41081. var numOfMeshes = this._meshes.length;
  41082. // vertexBuffers
  41083. for (var kind in this._vertexBuffers) {
  41084. if (numOfMeshes === 1) {
  41085. this._vertexBuffers[kind].create();
  41086. }
  41087. var buffer = this._vertexBuffers[kind].getBuffer();
  41088. if (buffer)
  41089. buffer.references = numOfMeshes;
  41090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41091. mesh._resetPointsArrayCache();
  41092. if (!this._extend) {
  41093. this.updateExtend(this._vertexBuffers[kind].getData());
  41094. }
  41095. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41096. mesh._createGlobalSubMesh();
  41097. //bounding info was just created again, world matrix should be applied again.
  41098. mesh._updateBoundingInfo();
  41099. }
  41100. }
  41101. // indexBuffer
  41102. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41103. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41104. }
  41105. if (this._indexBuffer) {
  41106. this._indexBuffer.references = numOfMeshes;
  41107. }
  41108. };
  41109. Geometry.prototype.notifyUpdate = function (kind) {
  41110. if (this.onGeometryUpdated) {
  41111. this.onGeometryUpdated(this, kind);
  41112. }
  41113. };
  41114. Geometry.prototype.load = function (scene, onLoaded) {
  41115. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41116. return;
  41117. }
  41118. if (this.isReady()) {
  41119. if (onLoaded) {
  41120. onLoaded();
  41121. }
  41122. return;
  41123. }
  41124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41125. this._queueLoad(scene, onLoaded);
  41126. };
  41127. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41128. var _this = this;
  41129. scene._addPendingData(this);
  41130. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  41131. _this._delayLoadingFunction(JSON.parse(data), _this);
  41132. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41133. _this._delayInfo = [];
  41134. scene._removePendingData(_this);
  41135. var meshes = _this._meshes;
  41136. var numOfMeshes = meshes.length;
  41137. for (var index = 0; index < numOfMeshes; index++) {
  41138. _this._applyToMesh(meshes[index]);
  41139. }
  41140. if (onLoaded) {
  41141. onLoaded();
  41142. }
  41143. }, function () { }, scene.database);
  41144. };
  41145. /**
  41146. * Invert the geometry to move from a right handed system to a left handed one.
  41147. */
  41148. Geometry.prototype.toLeftHanded = function () {
  41149. // Flip faces
  41150. var tIndices = this.getIndices(false);
  41151. if (tIndices != null && tIndices.length > 0) {
  41152. for (var i = 0; i < tIndices.length; i += 3) {
  41153. var tTemp = tIndices[i + 0];
  41154. tIndices[i + 0] = tIndices[i + 2];
  41155. tIndices[i + 2] = tTemp;
  41156. }
  41157. this.setIndices(tIndices);
  41158. }
  41159. // Negate position.z
  41160. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41161. if (tPositions != null && tPositions.length > 0) {
  41162. for (var i = 0; i < tPositions.length; i += 3) {
  41163. tPositions[i + 2] = -tPositions[i + 2];
  41164. }
  41165. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41166. }
  41167. // Negate normal.z
  41168. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41169. if (tNormals != null && tNormals.length > 0) {
  41170. for (var i = 0; i < tNormals.length; i += 3) {
  41171. tNormals[i + 2] = -tNormals[i + 2];
  41172. }
  41173. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41174. }
  41175. };
  41176. Geometry.prototype.isDisposed = function () {
  41177. return this._isDisposed;
  41178. };
  41179. Geometry.prototype._disposeVertexArrayObjects = function () {
  41180. if (this._vertexArrayObjects) {
  41181. for (var kind in this._vertexArrayObjects) {
  41182. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41183. }
  41184. this._vertexArrayObjects = {};
  41185. }
  41186. };
  41187. Geometry.prototype.dispose = function () {
  41188. var meshes = this._meshes;
  41189. var numOfMeshes = meshes.length;
  41190. var index;
  41191. for (index = 0; index < numOfMeshes; index++) {
  41192. this.releaseForMesh(meshes[index]);
  41193. }
  41194. this._meshes = [];
  41195. this._disposeVertexArrayObjects();
  41196. for (var kind in this._vertexBuffers) {
  41197. this._vertexBuffers[kind].dispose();
  41198. }
  41199. this._vertexBuffers = {};
  41200. this._totalVertices = 0;
  41201. if (this._indexBuffer) {
  41202. this._engine._releaseBuffer(this._indexBuffer);
  41203. }
  41204. this._indexBuffer = null;
  41205. this._indices = [];
  41206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41207. this.delayLoadingFile = null;
  41208. this._delayLoadingFunction = null;
  41209. this._delayInfo = [];
  41210. this._boundingInfo = null;
  41211. this._scene.removeGeometry(this);
  41212. this._isDisposed = true;
  41213. };
  41214. Geometry.prototype.copy = function (id) {
  41215. var vertexData = new BABYLON.VertexData();
  41216. vertexData.indices = [];
  41217. var indices = this.getIndices();
  41218. for (var index = 0; index < indices.length; index++) {
  41219. vertexData.indices.push(indices[index]);
  41220. }
  41221. var updatable = false;
  41222. var stopChecking = false;
  41223. var kind;
  41224. for (kind in this._vertexBuffers) {
  41225. // using slice() to make a copy of the array and not just reference it
  41226. var data = this.getVerticesData(kind);
  41227. if (data instanceof Float32Array) {
  41228. vertexData.set(new Float32Array(data), kind);
  41229. }
  41230. else {
  41231. vertexData.set(data.slice(0), kind);
  41232. }
  41233. if (!stopChecking) {
  41234. updatable = this.getVertexBuffer(kind).isUpdatable();
  41235. stopChecking = !updatable;
  41236. }
  41237. }
  41238. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  41239. geometry.delayLoadState = this.delayLoadState;
  41240. geometry.delayLoadingFile = this.delayLoadingFile;
  41241. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41242. for (kind in this._delayInfo) {
  41243. geometry._delayInfo = geometry._delayInfo || [];
  41244. geometry._delayInfo.push(kind);
  41245. }
  41246. // Bounding info
  41247. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41248. return geometry;
  41249. };
  41250. Geometry.prototype.serialize = function () {
  41251. var serializationObject = {};
  41252. serializationObject.id = this.id;
  41253. if (BABYLON.Tags.HasTags(this)) {
  41254. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41255. }
  41256. return serializationObject;
  41257. };
  41258. Geometry.prototype.serializeVerticeData = function () {
  41259. var serializationObject = this.serialize();
  41260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41261. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41262. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  41263. serializationObject.positions._updatable = true;
  41264. }
  41265. }
  41266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41267. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41268. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  41269. serializationObject.normals._updatable = true;
  41270. }
  41271. }
  41272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41273. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41274. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  41275. serializationObject.uvs._updatable = true;
  41276. }
  41277. }
  41278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41279. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  41280. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  41281. serializationObject.uv2s._updatable = true;
  41282. }
  41283. }
  41284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41285. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  41286. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  41287. serializationObject.uv3s._updatable = true;
  41288. }
  41289. }
  41290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41291. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  41292. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  41293. serializationObject.uv4s._updatable = true;
  41294. }
  41295. }
  41296. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41297. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  41298. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  41299. serializationObject.uv5s._updatable = true;
  41300. }
  41301. }
  41302. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41303. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  41304. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  41305. serializationObject.uv6s._updatable = true;
  41306. }
  41307. }
  41308. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41309. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41310. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  41311. serializationObject.colors._updatable = true;
  41312. }
  41313. }
  41314. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41315. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41316. serializationObject.matricesIndices._isExpanded = true;
  41317. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  41318. serializationObject.matricesIndices._updatable = true;
  41319. }
  41320. }
  41321. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41322. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  41323. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  41324. serializationObject.matricesWeights._updatable = true;
  41325. }
  41326. }
  41327. serializationObject.indices = this.getIndices();
  41328. return serializationObject;
  41329. };
  41330. // Statics
  41331. Geometry.ExtractFromMesh = function (mesh, id) {
  41332. var geometry = mesh._geometry;
  41333. if (!geometry) {
  41334. return null;
  41335. }
  41336. return geometry.copy(id);
  41337. };
  41338. /**
  41339. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41340. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41341. * Be aware Math.random() could cause collisions, but:
  41342. * "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"
  41343. */
  41344. Geometry.RandomId = function () {
  41345. return BABYLON.Tools.RandomId();
  41346. };
  41347. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  41348. var scene = mesh.getScene();
  41349. // Geometry
  41350. var geometryId = parsedGeometry.geometryId;
  41351. if (geometryId) {
  41352. var geometry = scene.getGeometryByID(geometryId);
  41353. if (geometry) {
  41354. geometry.applyToMesh(mesh);
  41355. }
  41356. }
  41357. else if (parsedGeometry instanceof ArrayBuffer) {
  41358. var binaryInfo = mesh._binaryInfo;
  41359. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41360. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41361. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41362. }
  41363. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41364. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41365. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41366. }
  41367. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41368. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41369. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41370. }
  41371. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41372. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41373. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41374. }
  41375. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41376. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41377. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41378. }
  41379. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41380. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41381. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41382. }
  41383. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41384. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41385. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41386. }
  41387. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41388. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41389. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41390. }
  41391. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41392. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41393. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41394. }
  41395. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41396. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41397. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  41398. }
  41399. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41400. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41401. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41402. }
  41403. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41404. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41405. mesh.setIndices(indicesData);
  41406. }
  41407. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41408. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41409. mesh.subMeshes = [];
  41410. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41411. var materialIndex = subMeshesData[(i * 5) + 0];
  41412. var verticesStart = subMeshesData[(i * 5) + 1];
  41413. var verticesCount = subMeshesData[(i * 5) + 2];
  41414. var indexStart = subMeshesData[(i * 5) + 3];
  41415. var indexCount = subMeshesData[(i * 5) + 4];
  41416. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41417. }
  41418. }
  41419. }
  41420. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41421. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41422. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41423. if (parsedGeometry.uvs) {
  41424. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41425. }
  41426. if (parsedGeometry.uvs2) {
  41427. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41428. }
  41429. if (parsedGeometry.uvs3) {
  41430. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41431. }
  41432. if (parsedGeometry.uvs4) {
  41433. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41434. }
  41435. if (parsedGeometry.uvs5) {
  41436. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41437. }
  41438. if (parsedGeometry.uvs6) {
  41439. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41440. }
  41441. if (parsedGeometry.colors) {
  41442. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41443. }
  41444. if (parsedGeometry.matricesIndices) {
  41445. if (!parsedGeometry.matricesIndices._isExpanded) {
  41446. var floatIndices = [];
  41447. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41448. var matricesIndex = parsedGeometry.matricesIndices[i];
  41449. floatIndices.push(matricesIndex & 0x000000FF);
  41450. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41451. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41452. floatIndices.push(matricesIndex >> 24);
  41453. }
  41454. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41455. }
  41456. else {
  41457. delete parsedGeometry.matricesIndices._isExpanded;
  41458. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41459. }
  41460. }
  41461. if (parsedGeometry.matricesIndicesExtra) {
  41462. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41463. var floatIndices = [];
  41464. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41465. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41466. floatIndices.push(matricesIndex & 0x000000FF);
  41467. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41468. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41469. floatIndices.push(matricesIndex >> 24);
  41470. }
  41471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41472. }
  41473. else {
  41474. delete parsedGeometry.matricesIndices._isExpanded;
  41475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41476. }
  41477. }
  41478. if (parsedGeometry.matricesWeights) {
  41479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41480. }
  41481. if (parsedGeometry.matricesWeightsExtra) {
  41482. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41483. }
  41484. mesh.setIndices(parsedGeometry.indices);
  41485. }
  41486. // SubMeshes
  41487. if (parsedGeometry.subMeshes) {
  41488. mesh.subMeshes = [];
  41489. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41490. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41491. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41492. }
  41493. }
  41494. // Flat shading
  41495. if (mesh._shouldGenerateFlatShading) {
  41496. mesh.convertToFlatShadedMesh();
  41497. delete mesh._shouldGenerateFlatShading;
  41498. }
  41499. // Update
  41500. mesh.computeWorldMatrix(true);
  41501. // Octree
  41502. if (scene['_selectionOctree']) {
  41503. scene['_selectionOctree'].addMesh(mesh);
  41504. }
  41505. };
  41506. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41507. if (scene.getGeometryByID(parsedVertexData.id)) {
  41508. return null; // null since geometry could be something else than a box...
  41509. }
  41510. var geometry = new Geometry(parsedVertexData.id, scene);
  41511. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41512. if (parsedVertexData.delayLoadingFile) {
  41513. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41514. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41515. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41516. geometry._delayInfo = [];
  41517. if (parsedVertexData.hasUVs) {
  41518. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41519. }
  41520. if (parsedVertexData.hasUVs2) {
  41521. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41522. }
  41523. if (parsedVertexData.hasUVs3) {
  41524. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41525. }
  41526. if (parsedVertexData.hasUVs4) {
  41527. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41528. }
  41529. if (parsedVertexData.hasUVs5) {
  41530. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41531. }
  41532. if (parsedVertexData.hasUVs6) {
  41533. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41534. }
  41535. if (parsedVertexData.hasColors) {
  41536. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41537. }
  41538. if (parsedVertexData.hasMatricesIndices) {
  41539. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41540. }
  41541. if (parsedVertexData.hasMatricesWeights) {
  41542. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41543. }
  41544. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41545. }
  41546. else {
  41547. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41548. }
  41549. scene.pushGeometry(geometry, true);
  41550. return geometry;
  41551. };
  41552. return Geometry;
  41553. }());
  41554. BABYLON.Geometry = Geometry;
  41555. /////// Primitives //////////////////////////////////////////////
  41556. (function (Geometry) {
  41557. var Primitives;
  41558. (function (Primitives) {
  41559. /// Abstract class
  41560. var _Primitive = (function (_super) {
  41561. __extends(_Primitive, _super);
  41562. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  41563. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  41564. _this._canBeRegenerated = _canBeRegenerated;
  41565. _this._beingRegenerated = true;
  41566. _this.regenerate();
  41567. _this._beingRegenerated = false;
  41568. return _this;
  41569. }
  41570. _Primitive.prototype.canBeRegenerated = function () {
  41571. return this._canBeRegenerated;
  41572. };
  41573. _Primitive.prototype.regenerate = function () {
  41574. if (!this._canBeRegenerated) {
  41575. return;
  41576. }
  41577. this._beingRegenerated = true;
  41578. this.setAllVerticesData(this._regenerateVertexData(), false);
  41579. this._beingRegenerated = false;
  41580. };
  41581. _Primitive.prototype.asNewGeometry = function (id) {
  41582. return _super.prototype.copy.call(this, id);
  41583. };
  41584. // overrides
  41585. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  41586. if (!this._beingRegenerated) {
  41587. return;
  41588. }
  41589. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41590. };
  41591. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  41592. if (!this._beingRegenerated) {
  41593. return;
  41594. }
  41595. _super.prototype.setVerticesData.call(this, kind, data, false);
  41596. };
  41597. // to override
  41598. // protected
  41599. _Primitive.prototype._regenerateVertexData = function () {
  41600. throw new Error("Abstract method");
  41601. };
  41602. _Primitive.prototype.copy = function (id) {
  41603. throw new Error("Must be overriden in sub-classes.");
  41604. };
  41605. _Primitive.prototype.serialize = function () {
  41606. var serializationObject = _super.prototype.serialize.call(this);
  41607. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41608. return serializationObject;
  41609. };
  41610. return _Primitive;
  41611. }(Geometry));
  41612. Primitives._Primitive = _Primitive;
  41613. var Ribbon = (function (_super) {
  41614. __extends(Ribbon, _super);
  41615. // Members
  41616. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  41617. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41618. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41619. _this.pathArray = pathArray;
  41620. _this.closeArray = closeArray;
  41621. _this.closePath = closePath;
  41622. _this.offset = offset;
  41623. _this.side = side;
  41624. return _this;
  41625. }
  41626. Ribbon.prototype._regenerateVertexData = function () {
  41627. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41628. };
  41629. Ribbon.prototype.copy = function (id) {
  41630. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  41631. };
  41632. return Ribbon;
  41633. }(_Primitive));
  41634. Primitives.Ribbon = Ribbon;
  41635. var Box = (function (_super) {
  41636. __extends(Box, _super);
  41637. // Members
  41638. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  41639. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41640. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41641. _this.size = size;
  41642. _this.side = side;
  41643. return _this;
  41644. }
  41645. Box.prototype._regenerateVertexData = function () {
  41646. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41647. };
  41648. Box.prototype.copy = function (id) {
  41649. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41650. };
  41651. Box.prototype.serialize = function () {
  41652. var serializationObject = _super.prototype.serialize.call(this);
  41653. serializationObject.size = this.size;
  41654. return serializationObject;
  41655. };
  41656. Box.Parse = function (parsedBox, scene) {
  41657. if (scene.getGeometryByID(parsedBox.id)) {
  41658. return null; // null since geometry could be something else than a box...
  41659. }
  41660. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41661. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41662. scene.pushGeometry(box, true);
  41663. return box;
  41664. };
  41665. return Box;
  41666. }(_Primitive));
  41667. Primitives.Box = Box;
  41668. var Sphere = (function (_super) {
  41669. __extends(Sphere, _super);
  41670. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  41671. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41672. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41673. _this.segments = segments;
  41674. _this.diameter = diameter;
  41675. _this.side = side;
  41676. return _this;
  41677. }
  41678. Sphere.prototype._regenerateVertexData = function () {
  41679. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41680. };
  41681. Sphere.prototype.copy = function (id) {
  41682. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41683. };
  41684. Sphere.prototype.serialize = function () {
  41685. var serializationObject = _super.prototype.serialize.call(this);
  41686. serializationObject.segments = this.segments;
  41687. serializationObject.diameter = this.diameter;
  41688. return serializationObject;
  41689. };
  41690. Sphere.Parse = function (parsedSphere, scene) {
  41691. if (scene.getGeometryByID(parsedSphere.id)) {
  41692. return null; // null since geometry could be something else than a sphere...
  41693. }
  41694. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41695. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41696. scene.pushGeometry(sphere, true);
  41697. return sphere;
  41698. };
  41699. return Sphere;
  41700. }(_Primitive));
  41701. Primitives.Sphere = Sphere;
  41702. var Disc = (function (_super) {
  41703. __extends(Disc, _super);
  41704. // Members
  41705. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  41706. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41707. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41708. _this.radius = radius;
  41709. _this.tessellation = tessellation;
  41710. _this.side = side;
  41711. return _this;
  41712. }
  41713. Disc.prototype._regenerateVertexData = function () {
  41714. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41715. };
  41716. Disc.prototype.copy = function (id) {
  41717. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41718. };
  41719. return Disc;
  41720. }(_Primitive));
  41721. Primitives.Disc = Disc;
  41722. var Cylinder = (function (_super) {
  41723. __extends(Cylinder, _super);
  41724. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  41725. if (subdivisions === void 0) { subdivisions = 1; }
  41726. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41727. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41728. _this.height = height;
  41729. _this.diameterTop = diameterTop;
  41730. _this.diameterBottom = diameterBottom;
  41731. _this.tessellation = tessellation;
  41732. _this.subdivisions = subdivisions;
  41733. _this.side = side;
  41734. return _this;
  41735. }
  41736. Cylinder.prototype._regenerateVertexData = function () {
  41737. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41738. };
  41739. Cylinder.prototype.copy = function (id) {
  41740. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41741. };
  41742. Cylinder.prototype.serialize = function () {
  41743. var serializationObject = _super.prototype.serialize.call(this);
  41744. serializationObject.height = this.height;
  41745. serializationObject.diameterTop = this.diameterTop;
  41746. serializationObject.diameterBottom = this.diameterBottom;
  41747. serializationObject.tessellation = this.tessellation;
  41748. return serializationObject;
  41749. };
  41750. Cylinder.Parse = function (parsedCylinder, scene) {
  41751. if (scene.getGeometryByID(parsedCylinder.id)) {
  41752. return null; // null since geometry could be something else than a cylinder...
  41753. }
  41754. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41755. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41756. scene.pushGeometry(cylinder, true);
  41757. return cylinder;
  41758. };
  41759. return Cylinder;
  41760. }(_Primitive));
  41761. Primitives.Cylinder = Cylinder;
  41762. var Torus = (function (_super) {
  41763. __extends(Torus, _super);
  41764. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  41765. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41766. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41767. _this.diameter = diameter;
  41768. _this.thickness = thickness;
  41769. _this.tessellation = tessellation;
  41770. _this.side = side;
  41771. return _this;
  41772. }
  41773. Torus.prototype._regenerateVertexData = function () {
  41774. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41775. };
  41776. Torus.prototype.copy = function (id) {
  41777. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41778. };
  41779. Torus.prototype.serialize = function () {
  41780. var serializationObject = _super.prototype.serialize.call(this);
  41781. serializationObject.diameter = this.diameter;
  41782. serializationObject.thickness = this.thickness;
  41783. serializationObject.tessellation = this.tessellation;
  41784. return serializationObject;
  41785. };
  41786. Torus.Parse = function (parsedTorus, scene) {
  41787. if (scene.getGeometryByID(parsedTorus.id)) {
  41788. return null; // null since geometry could be something else than a torus...
  41789. }
  41790. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41791. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41792. scene.pushGeometry(torus, true);
  41793. return torus;
  41794. };
  41795. return Torus;
  41796. }(_Primitive));
  41797. Primitives.Torus = Torus;
  41798. var Ground = (function (_super) {
  41799. __extends(Ground, _super);
  41800. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  41801. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41802. _this.width = width;
  41803. _this.height = height;
  41804. _this.subdivisions = subdivisions;
  41805. return _this;
  41806. }
  41807. Ground.prototype._regenerateVertexData = function () {
  41808. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41809. };
  41810. Ground.prototype.copy = function (id) {
  41811. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41812. };
  41813. Ground.prototype.serialize = function () {
  41814. var serializationObject = _super.prototype.serialize.call(this);
  41815. serializationObject.width = this.width;
  41816. serializationObject.height = this.height;
  41817. serializationObject.subdivisions = this.subdivisions;
  41818. return serializationObject;
  41819. };
  41820. Ground.Parse = function (parsedGround, scene) {
  41821. if (scene.getGeometryByID(parsedGround.id)) {
  41822. return null; // null since geometry could be something else than a ground...
  41823. }
  41824. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41825. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41826. scene.pushGeometry(ground, true);
  41827. return ground;
  41828. };
  41829. return Ground;
  41830. }(_Primitive));
  41831. Primitives.Ground = Ground;
  41832. var TiledGround = (function (_super) {
  41833. __extends(TiledGround, _super);
  41834. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  41835. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41836. _this.xmin = xmin;
  41837. _this.zmin = zmin;
  41838. _this.xmax = xmax;
  41839. _this.zmax = zmax;
  41840. _this.subdivisions = subdivisions;
  41841. _this.precision = precision;
  41842. return _this;
  41843. }
  41844. TiledGround.prototype._regenerateVertexData = function () {
  41845. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41846. };
  41847. TiledGround.prototype.copy = function (id) {
  41848. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41849. };
  41850. return TiledGround;
  41851. }(_Primitive));
  41852. Primitives.TiledGround = TiledGround;
  41853. var Plane = (function (_super) {
  41854. __extends(Plane, _super);
  41855. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  41856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41857. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41858. _this.size = size;
  41859. _this.side = side;
  41860. return _this;
  41861. }
  41862. Plane.prototype._regenerateVertexData = function () {
  41863. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41864. };
  41865. Plane.prototype.copy = function (id) {
  41866. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41867. };
  41868. Plane.prototype.serialize = function () {
  41869. var serializationObject = _super.prototype.serialize.call(this);
  41870. serializationObject.size = this.size;
  41871. return serializationObject;
  41872. };
  41873. Plane.Parse = function (parsedPlane, scene) {
  41874. if (scene.getGeometryByID(parsedPlane.id)) {
  41875. return null; // null since geometry could be something else than a ground...
  41876. }
  41877. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41878. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41879. scene.pushGeometry(plane, true);
  41880. return plane;
  41881. };
  41882. return Plane;
  41883. }(_Primitive));
  41884. Primitives.Plane = Plane;
  41885. var TorusKnot = (function (_super) {
  41886. __extends(TorusKnot, _super);
  41887. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  41888. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41889. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41890. _this.radius = radius;
  41891. _this.tube = tube;
  41892. _this.radialSegments = radialSegments;
  41893. _this.tubularSegments = tubularSegments;
  41894. _this.p = p;
  41895. _this.q = q;
  41896. _this.side = side;
  41897. return _this;
  41898. }
  41899. TorusKnot.prototype._regenerateVertexData = function () {
  41900. 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 });
  41901. };
  41902. TorusKnot.prototype.copy = function (id) {
  41903. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41904. };
  41905. TorusKnot.prototype.serialize = function () {
  41906. var serializationObject = _super.prototype.serialize.call(this);
  41907. serializationObject.radius = this.radius;
  41908. serializationObject.tube = this.tube;
  41909. serializationObject.radialSegments = this.radialSegments;
  41910. serializationObject.tubularSegments = this.tubularSegments;
  41911. serializationObject.p = this.p;
  41912. serializationObject.q = this.q;
  41913. return serializationObject;
  41914. };
  41915. ;
  41916. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  41917. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41918. return null; // null since geometry could be something else than a ground...
  41919. }
  41920. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41921. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41922. scene.pushGeometry(torusKnot, true);
  41923. return torusKnot;
  41924. };
  41925. return TorusKnot;
  41926. }(_Primitive));
  41927. Primitives.TorusKnot = TorusKnot;
  41928. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  41929. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  41930. })(BABYLON || (BABYLON = {}));
  41931. //# sourceMappingURL=babylon.geometry.js.map
  41932. /// <reference path="babylon.mesh.ts" />
  41933. var BABYLON;
  41934. (function (BABYLON) {
  41935. var GroundMesh = (function (_super) {
  41936. __extends(GroundMesh, _super);
  41937. function GroundMesh(name, scene) {
  41938. var _this = _super.call(this, name, scene) || this;
  41939. _this.generateOctree = false;
  41940. _this._worldInverse = new BABYLON.Matrix();
  41941. return _this;
  41942. }
  41943. GroundMesh.prototype.getClassName = function () {
  41944. return "GroundMesh";
  41945. };
  41946. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41947. get: function () {
  41948. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41949. },
  41950. enumerable: true,
  41951. configurable: true
  41952. });
  41953. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41954. get: function () {
  41955. return this._subdivisionsX;
  41956. },
  41957. enumerable: true,
  41958. configurable: true
  41959. });
  41960. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41961. get: function () {
  41962. return this._subdivisionsY;
  41963. },
  41964. enumerable: true,
  41965. configurable: true
  41966. });
  41967. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41968. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41969. this._subdivisionsX = chunksCount;
  41970. this._subdivisionsY = chunksCount;
  41971. this.subdivide(chunksCount);
  41972. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41973. };
  41974. /**
  41975. * Returns a height (y) value in the Worl system :
  41976. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41977. * Returns the ground y position if (x, z) are outside the ground surface.
  41978. */
  41979. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41980. var world = this.getWorldMatrix();
  41981. var invMat = BABYLON.Tmp.Matrix[5];
  41982. world.invertToRef(invMat);
  41983. var tmpVect = BABYLON.Tmp.Vector3[8];
  41984. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41985. x = tmpVect.x;
  41986. z = tmpVect.z;
  41987. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41988. return this.position.y;
  41989. }
  41990. if (!this._heightQuads || this._heightQuads.length == 0) {
  41991. this._initHeightQuads();
  41992. this._computeHeightQuads();
  41993. }
  41994. var facet = this._getFacetAt(x, z);
  41995. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41996. // return y in the World system
  41997. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41998. return tmpVect.y;
  41999. };
  42000. /**
  42001. * Returns a normalized vector (Vector3) orthogonal to the ground
  42002. * at the ground coordinates (x, z) expressed in the World system.
  42003. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42004. */
  42005. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42006. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42007. this.getNormalAtCoordinatesToRef(x, z, normal);
  42008. return normal;
  42009. };
  42010. /**
  42011. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42012. * at the ground coordinates (x, z) expressed in the World system.
  42013. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42014. * Returns the GroundMesh.
  42015. */
  42016. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42017. var world = this.getWorldMatrix();
  42018. var tmpMat = BABYLON.Tmp.Matrix[5];
  42019. world.invertToRef(tmpMat);
  42020. var tmpVect = BABYLON.Tmp.Vector3[8];
  42021. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42022. x = tmpVect.x;
  42023. z = tmpVect.z;
  42024. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42025. return this;
  42026. }
  42027. if (!this._heightQuads || this._heightQuads.length == 0) {
  42028. this._initHeightQuads();
  42029. this._computeHeightQuads();
  42030. }
  42031. var facet = this._getFacetAt(x, z);
  42032. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42033. return this;
  42034. };
  42035. /**
  42036. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42037. * if the ground has been updated.
  42038. * This can be used in the render loop.
  42039. * Returns the GroundMesh.
  42040. */
  42041. GroundMesh.prototype.updateCoordinateHeights = function () {
  42042. if (!this._heightQuads || this._heightQuads.length == 0) {
  42043. this._initHeightQuads();
  42044. }
  42045. this._computeHeightQuads();
  42046. return this;
  42047. };
  42048. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42049. GroundMesh.prototype._getFacetAt = function (x, z) {
  42050. // retrieve col and row from x, z coordinates in the ground local system
  42051. var subdivisionsX = this._subdivisionsX;
  42052. var subdivisionsY = this._subdivisionsY;
  42053. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42054. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42055. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42056. var facet;
  42057. if (z < quad.slope.x * x + quad.slope.y) {
  42058. facet = quad.facet1;
  42059. }
  42060. else {
  42061. facet = quad.facet2;
  42062. }
  42063. return facet;
  42064. };
  42065. // Creates and populates the heightMap array with "facet" elements :
  42066. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42067. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42068. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42069. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42070. // Returns the GroundMesh.
  42071. GroundMesh.prototype._initHeightQuads = function () {
  42072. var subdivisionsX = this._subdivisionsX;
  42073. var subdivisionsY = this._subdivisionsY;
  42074. this._heightQuads = new Array();
  42075. for (var row = 0; row < subdivisionsY; row++) {
  42076. for (var col = 0; col < subdivisionsX; col++) {
  42077. 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) };
  42078. this._heightQuads[row * subdivisionsX + col] = quad;
  42079. }
  42080. }
  42081. return this;
  42082. };
  42083. // Compute each quad element values and update the the heightMap array :
  42084. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42085. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42086. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42087. // Returns the GroundMesh.
  42088. GroundMesh.prototype._computeHeightQuads = function () {
  42089. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42090. var v1 = BABYLON.Tmp.Vector3[3];
  42091. var v2 = BABYLON.Tmp.Vector3[2];
  42092. var v3 = BABYLON.Tmp.Vector3[1];
  42093. var v4 = BABYLON.Tmp.Vector3[0];
  42094. var v1v2 = BABYLON.Tmp.Vector3[4];
  42095. var v1v3 = BABYLON.Tmp.Vector3[5];
  42096. var v1v4 = BABYLON.Tmp.Vector3[6];
  42097. var norm1 = BABYLON.Tmp.Vector3[7];
  42098. var norm2 = BABYLON.Tmp.Vector3[8];
  42099. var i = 0;
  42100. var j = 0;
  42101. var k = 0;
  42102. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42103. var h = 0;
  42104. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42105. var d2 = 0;
  42106. var subdivisionsX = this._subdivisionsX;
  42107. var subdivisionsY = this._subdivisionsY;
  42108. for (var row = 0; row < subdivisionsY; row++) {
  42109. for (var col = 0; col < subdivisionsX; col++) {
  42110. i = col * 3;
  42111. j = row * (subdivisionsX + 1) * 3;
  42112. k = (row + 1) * (subdivisionsX + 1) * 3;
  42113. v1.x = positions[j + i];
  42114. v1.y = positions[j + i + 1];
  42115. v1.z = positions[j + i + 2];
  42116. v2.x = positions[j + i + 3];
  42117. v2.y = positions[j + i + 4];
  42118. v2.z = positions[j + i + 5];
  42119. v3.x = positions[k + i];
  42120. v3.y = positions[k + i + 1];
  42121. v3.z = positions[k + i + 2];
  42122. v4.x = positions[k + i + 3];
  42123. v4.y = positions[k + i + 4];
  42124. v4.z = positions[k + i + 5];
  42125. // 2D slope V1V4
  42126. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42127. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42128. // facet equations :
  42129. // we compute each facet normal vector
  42130. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42131. // we compute the value d by applying the equation to v1 which belongs to the plane
  42132. // then we store the facet equation in a Vector4
  42133. v2.subtractToRef(v1, v1v2);
  42134. v3.subtractToRef(v1, v1v3);
  42135. v4.subtractToRef(v1, v1v4);
  42136. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42137. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42138. norm1.normalize();
  42139. norm2.normalize();
  42140. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42141. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42142. var quad = this._heightQuads[row * subdivisionsX + col];
  42143. quad.slope.copyFromFloats(cd, h);
  42144. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42145. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42146. }
  42147. }
  42148. return this;
  42149. };
  42150. GroundMesh.prototype.serialize = function (serializationObject) {
  42151. _super.prototype.serialize.call(this, serializationObject);
  42152. serializationObject.subdivisionsX = this._subdivisionsX;
  42153. serializationObject.subdivisionsY = this._subdivisionsY;
  42154. serializationObject.minX = this._minX;
  42155. serializationObject.maxX = this._maxX;
  42156. serializationObject.minZ = this._minZ;
  42157. serializationObject.maxZ = this._maxZ;
  42158. serializationObject.width = this._width;
  42159. serializationObject.height = this._height;
  42160. };
  42161. GroundMesh.Parse = function (parsedMesh, scene) {
  42162. var result = new GroundMesh(parsedMesh.name, scene);
  42163. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42164. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42165. result._minX = parsedMesh.minX;
  42166. result._maxX = parsedMesh.maxX;
  42167. result._minZ = parsedMesh.minZ;
  42168. result._maxZ = parsedMesh.maxZ;
  42169. result._width = parsedMesh.width;
  42170. result._height = parsedMesh.height;
  42171. return result;
  42172. };
  42173. return GroundMesh;
  42174. }(BABYLON.Mesh));
  42175. BABYLON.GroundMesh = GroundMesh;
  42176. })(BABYLON || (BABYLON = {}));
  42177. //# sourceMappingURL=babylon.groundMesh.js.map
  42178. /// <reference path="babylon.mesh.ts" />
  42179. var BABYLON;
  42180. (function (BABYLON) {
  42181. var LinesMesh = (function (_super) {
  42182. __extends(LinesMesh, _super);
  42183. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  42184. if (parent === void 0) { parent = null; }
  42185. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42186. _this.color = new BABYLON.Color3(1, 1, 1);
  42187. _this.alpha = 1;
  42188. _this._positionBuffer = {};
  42189. if (source) {
  42190. _this.color = source.color.clone();
  42191. _this.alpha = source.alpha;
  42192. }
  42193. _this._intersectionThreshold = 0.1;
  42194. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  42195. attributes: [BABYLON.VertexBuffer.PositionKind],
  42196. uniforms: ["worldViewProjection", "color"],
  42197. needAlphaBlending: true
  42198. });
  42199. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  42200. return _this;
  42201. }
  42202. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42203. /**
  42204. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42205. * This margin is expressed in world space coordinates, so its value may vary.
  42206. * Default value is 0.1
  42207. * @returns the intersection Threshold value.
  42208. */
  42209. get: function () {
  42210. return this._intersectionThreshold;
  42211. },
  42212. /**
  42213. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42214. * This margin is expressed in world space coordinates, so its value may vary.
  42215. * @param value the new threshold to apply
  42216. */
  42217. set: function (value) {
  42218. if (this._intersectionThreshold === value) {
  42219. return;
  42220. }
  42221. this._intersectionThreshold = value;
  42222. if (this.geometry) {
  42223. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42224. }
  42225. },
  42226. enumerable: true,
  42227. configurable: true
  42228. });
  42229. /**
  42230. * Returns the string "LineMesh"
  42231. */
  42232. LinesMesh.prototype.getClassName = function () {
  42233. return "LinesMesh";
  42234. };
  42235. Object.defineProperty(LinesMesh.prototype, "material", {
  42236. get: function () {
  42237. return this._colorShader;
  42238. },
  42239. enumerable: true,
  42240. configurable: true
  42241. });
  42242. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42243. get: function () {
  42244. return false;
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. LinesMesh.prototype.createInstance = function (name) {
  42250. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42251. return null;
  42252. };
  42253. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42254. var engine = this.getScene().getEngine();
  42255. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  42256. // VBOs
  42257. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  42258. // Color
  42259. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42260. return this;
  42261. };
  42262. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42263. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42264. return this;
  42265. }
  42266. var engine = this.getScene().getEngine();
  42267. // Draw order
  42268. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42269. return this;
  42270. };
  42271. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42272. this._colorShader.dispose();
  42273. _super.prototype.dispose.call(this, doNotRecurse);
  42274. };
  42275. /**
  42276. * Returns a new LineMesh object cloned from the current one.
  42277. */
  42278. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42279. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42280. };
  42281. return LinesMesh;
  42282. }(BABYLON.Mesh));
  42283. BABYLON.LinesMesh = LinesMesh;
  42284. })(BABYLON || (BABYLON = {}));
  42285. //# sourceMappingURL=babylon.linesMesh.js.map
  42286. var BABYLON;
  42287. (function (BABYLON) {
  42288. var DefaultLoadingScreen = (function () {
  42289. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42290. if (_loadingText === void 0) { _loadingText = ""; }
  42291. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42292. var _this = this;
  42293. this._renderingCanvas = _renderingCanvas;
  42294. this._loadingText = _loadingText;
  42295. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42296. // Resize
  42297. this._resizeLoadingUI = function () {
  42298. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42299. _this._loadingDiv.style.position = "absolute";
  42300. _this._loadingDiv.style.left = canvasRect.left + "px";
  42301. _this._loadingDiv.style.top = canvasRect.top + "px";
  42302. _this._loadingDiv.style.width = canvasRect.width + "px";
  42303. _this._loadingDiv.style.height = canvasRect.height + "px";
  42304. };
  42305. }
  42306. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42307. var _this = this;
  42308. if (this._loadingDiv) {
  42309. // Do not add a loading screen if there is already one
  42310. return;
  42311. }
  42312. this._loadingDiv = document.createElement("div");
  42313. this._loadingDiv.id = "babylonjsLoadingDiv";
  42314. this._loadingDiv.style.opacity = "0";
  42315. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42316. // Loading text
  42317. this._loadingTextDiv = document.createElement("div");
  42318. this._loadingTextDiv.style.position = "absolute";
  42319. this._loadingTextDiv.style.left = "0";
  42320. this._loadingTextDiv.style.top = "50%";
  42321. this._loadingTextDiv.style.marginTop = "80px";
  42322. this._loadingTextDiv.style.width = "100%";
  42323. this._loadingTextDiv.style.height = "20px";
  42324. this._loadingTextDiv.style.fontFamily = "Arial";
  42325. this._loadingTextDiv.style.fontSize = "14px";
  42326. this._loadingTextDiv.style.color = "white";
  42327. this._loadingTextDiv.style.textAlign = "center";
  42328. this._loadingTextDiv.innerHTML = "Loading";
  42329. this._loadingDiv.appendChild(this._loadingTextDiv);
  42330. //set the predefined text
  42331. this._loadingTextDiv.innerHTML = this._loadingText;
  42332. // Loading img
  42333. var imgBack = new Image();
  42334. 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==";
  42335. imgBack.style.position = "absolute";
  42336. imgBack.style.left = "50%";
  42337. imgBack.style.top = "50%";
  42338. imgBack.style.marginLeft = "-50px";
  42339. imgBack.style.marginTop = "-50px";
  42340. imgBack.style.transition = "transform 1.0s ease";
  42341. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42342. var deg = 360;
  42343. var onTransitionEnd = function () {
  42344. deg += 360;
  42345. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42346. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42347. };
  42348. imgBack.addEventListener("transitionend", onTransitionEnd);
  42349. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42350. this._loadingDiv.appendChild(imgBack);
  42351. // front image
  42352. var imgFront = new Image();
  42353. 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=";
  42354. imgFront.style.position = "absolute";
  42355. imgFront.style.left = "50%";
  42356. imgFront.style.top = "50%";
  42357. imgFront.style.marginLeft = "-50px";
  42358. imgFront.style.marginTop = "-50px";
  42359. this._loadingDiv.appendChild(imgFront);
  42360. this._resizeLoadingUI();
  42361. window.addEventListener("resize", this._resizeLoadingUI);
  42362. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42363. document.body.appendChild(this._loadingDiv);
  42364. setTimeout(function () {
  42365. _this._loadingDiv.style.opacity = "1";
  42366. imgBack.style.transform = "rotateZ(360deg)";
  42367. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42368. }, 0);
  42369. };
  42370. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42371. var _this = this;
  42372. if (!this._loadingDiv) {
  42373. return;
  42374. }
  42375. var onTransitionEnd = function () {
  42376. if (!_this._loadingDiv) {
  42377. return;
  42378. }
  42379. document.body.removeChild(_this._loadingDiv);
  42380. window.removeEventListener("resize", _this._resizeLoadingUI);
  42381. _this._loadingDiv = null;
  42382. };
  42383. this._loadingDiv.style.opacity = "0";
  42384. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42385. };
  42386. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42387. set: function (text) {
  42388. this._loadingText = text;
  42389. if (this._loadingTextDiv) {
  42390. this._loadingTextDiv.innerHTML = this._loadingText;
  42391. }
  42392. },
  42393. enumerable: true,
  42394. configurable: true
  42395. });
  42396. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42397. get: function () {
  42398. return this._loadingDivBackgroundColor;
  42399. },
  42400. set: function (color) {
  42401. this._loadingDivBackgroundColor = color;
  42402. if (!this._loadingDiv) {
  42403. return;
  42404. }
  42405. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42406. },
  42407. enumerable: true,
  42408. configurable: true
  42409. });
  42410. return DefaultLoadingScreen;
  42411. }());
  42412. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42413. })(BABYLON || (BABYLON = {}));
  42414. //# sourceMappingURL=babylon.loadingScreen.js.map
  42415. var BABYLON;
  42416. (function (BABYLON) {
  42417. var AudioEngine = (function () {
  42418. function AudioEngine() {
  42419. this._audioContext = null;
  42420. this._audioContextInitialized = false;
  42421. this.canUseWebAudio = false;
  42422. this.WarnedWebAudioUnsupported = false;
  42423. this.unlocked = false;
  42424. this.isMP3supported = false;
  42425. this.isOGGsupported = false;
  42426. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42427. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42428. this.canUseWebAudio = true;
  42429. }
  42430. var audioElem = document.createElement('audio');
  42431. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42432. this.isMP3supported = true;
  42433. }
  42434. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42435. this.isOGGsupported = true;
  42436. }
  42437. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42438. this._unlockiOSaudio();
  42439. }
  42440. else {
  42441. this.unlocked = true;
  42442. }
  42443. }
  42444. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42445. get: function () {
  42446. if (!this._audioContextInitialized) {
  42447. this._initializeAudioContext();
  42448. }
  42449. return this._audioContext;
  42450. },
  42451. enumerable: true,
  42452. configurable: true
  42453. });
  42454. AudioEngine.prototype._unlockiOSaudio = function () {
  42455. var _this = this;
  42456. var unlockaudio = function () {
  42457. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42458. var source = _this.audioContext.createBufferSource();
  42459. source.buffer = buffer;
  42460. source.connect(_this.audioContext.destination);
  42461. source.start(0);
  42462. setTimeout(function () {
  42463. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42464. _this.unlocked = true;
  42465. window.removeEventListener('touchend', unlockaudio, false);
  42466. if (_this.onAudioUnlocked) {
  42467. _this.onAudioUnlocked();
  42468. }
  42469. }
  42470. }, 0);
  42471. };
  42472. window.addEventListener('touchend', unlockaudio, false);
  42473. };
  42474. AudioEngine.prototype._initializeAudioContext = function () {
  42475. try {
  42476. if (this.canUseWebAudio) {
  42477. this._audioContext = new AudioContext();
  42478. // create a global volume gain node
  42479. this.masterGain = this._audioContext.createGain();
  42480. this.masterGain.gain.value = 1;
  42481. this.masterGain.connect(this._audioContext.destination);
  42482. this._audioContextInitialized = true;
  42483. }
  42484. }
  42485. catch (e) {
  42486. this.canUseWebAudio = false;
  42487. BABYLON.Tools.Error("Web Audio: " + e.message);
  42488. }
  42489. };
  42490. AudioEngine.prototype.dispose = function () {
  42491. if (this.canUseWebAudio && this._audioContextInitialized) {
  42492. if (this._connectedAnalyser) {
  42493. this._connectedAnalyser.stopDebugCanvas();
  42494. this._connectedAnalyser.dispose();
  42495. this.masterGain.disconnect();
  42496. this.masterGain.connect(this._audioContext.destination);
  42497. this._connectedAnalyser = null;
  42498. }
  42499. this.masterGain.gain.value = 1;
  42500. }
  42501. this.WarnedWebAudioUnsupported = false;
  42502. };
  42503. AudioEngine.prototype.getGlobalVolume = function () {
  42504. if (this.canUseWebAudio && this._audioContextInitialized) {
  42505. return this.masterGain.gain.value;
  42506. }
  42507. else {
  42508. return -1;
  42509. }
  42510. };
  42511. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42512. if (this.canUseWebAudio && this._audioContextInitialized) {
  42513. this.masterGain.gain.value = newVolume;
  42514. }
  42515. };
  42516. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42517. if (this._connectedAnalyser) {
  42518. this._connectedAnalyser.stopDebugCanvas();
  42519. }
  42520. if (this.canUseWebAudio && this._audioContextInitialized) {
  42521. this._connectedAnalyser = analyser;
  42522. this.masterGain.disconnect();
  42523. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42524. }
  42525. };
  42526. return AudioEngine;
  42527. }());
  42528. BABYLON.AudioEngine = AudioEngine;
  42529. })(BABYLON || (BABYLON = {}));
  42530. //# sourceMappingURL=babylon.audioEngine.js.map
  42531. var BABYLON;
  42532. (function (BABYLON) {
  42533. var Sound = (function () {
  42534. /**
  42535. * Create a sound and attach it to a scene
  42536. * @param name Name of your sound
  42537. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42538. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42539. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42540. */
  42541. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42542. var _this = this;
  42543. this.autoplay = false;
  42544. this.loop = false;
  42545. this.useCustomAttenuation = false;
  42546. this.spatialSound = false;
  42547. this.refDistance = 1;
  42548. this.rolloffFactor = 1;
  42549. this.maxDistance = 100;
  42550. this.distanceModel = "linear";
  42551. this._panningModel = "equalpower";
  42552. this._playbackRate = 1;
  42553. this._streaming = false;
  42554. this._startTime = 0;
  42555. this._startOffset = 0;
  42556. this._position = BABYLON.Vector3.Zero();
  42557. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42558. this._volume = 1;
  42559. this._isLoaded = false;
  42560. this._isReadyToPlay = false;
  42561. this.isPlaying = false;
  42562. this.isPaused = false;
  42563. this._isDirectional = false;
  42564. // Used if you'd like to create a directional sound.
  42565. // If not set, the sound will be omnidirectional
  42566. this._coneInnerAngle = 360;
  42567. this._coneOuterAngle = 360;
  42568. this._coneOuterGain = 0;
  42569. this._isOutputConnected = false;
  42570. this._urlType = "Unknown";
  42571. this.name = name;
  42572. this._scene = scene;
  42573. this._readyToPlayCallback = readyToPlayCallback;
  42574. // Default custom attenuation function is a linear attenuation
  42575. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42576. if (currentDistance < maxDistance) {
  42577. return currentVolume * (1 - currentDistance / maxDistance);
  42578. }
  42579. else {
  42580. return 0;
  42581. }
  42582. };
  42583. if (options) {
  42584. this.autoplay = options.autoplay || false;
  42585. this.loop = options.loop || false;
  42586. // if volume === 0, we need another way to check this option
  42587. if (options.volume !== undefined) {
  42588. this._volume = options.volume;
  42589. }
  42590. this.spatialSound = options.spatialSound || false;
  42591. this.maxDistance = options.maxDistance || 100;
  42592. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42593. this.rolloffFactor = options.rolloffFactor || 1;
  42594. this.refDistance = options.refDistance || 1;
  42595. this.distanceModel = options.distanceModel || "linear";
  42596. this._playbackRate = options.playbackRate || 1;
  42597. this._streaming = options.streaming || false;
  42598. }
  42599. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42600. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42601. this._soundGain.gain.value = this._volume;
  42602. this._inputAudioNode = this._soundGain;
  42603. this._ouputAudioNode = this._soundGain;
  42604. if (this.spatialSound) {
  42605. this._createSpatialParameters();
  42606. }
  42607. this._scene.mainSoundTrack.AddSound(this);
  42608. var validParameter = true;
  42609. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42610. if (urlOrArrayBuffer) {
  42611. if (typeof (urlOrArrayBuffer) === "string")
  42612. this._urlType = "String";
  42613. if (Array.isArray(urlOrArrayBuffer))
  42614. this._urlType = "Array";
  42615. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42616. this._urlType = "ArrayBuffer";
  42617. var urls = [];
  42618. var codecSupportedFound = false;
  42619. switch (this._urlType) {
  42620. case "ArrayBuffer":
  42621. if (urlOrArrayBuffer.byteLength > 0) {
  42622. codecSupportedFound = true;
  42623. this._soundLoaded(urlOrArrayBuffer);
  42624. }
  42625. break;
  42626. case "String":
  42627. urls.push(urlOrArrayBuffer);
  42628. case "Array":
  42629. if (urls.length === 0)
  42630. urls = urlOrArrayBuffer;
  42631. // If we found a supported format, we load it immediately and stop the loop
  42632. for (var i = 0; i < urls.length; i++) {
  42633. var url = urls[i];
  42634. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42635. codecSupportedFound = true;
  42636. }
  42637. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42638. codecSupportedFound = true;
  42639. }
  42640. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42641. codecSupportedFound = true;
  42642. }
  42643. if (codecSupportedFound) {
  42644. // Loading sound using XHR2
  42645. if (!this._streaming) {
  42646. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42647. }
  42648. else {
  42649. this._htmlAudioElement = new Audio(url);
  42650. this._htmlAudioElement.controls = false;
  42651. this._htmlAudioElement.loop = this.loop;
  42652. this._htmlAudioElement.crossOrigin = "anonymous";
  42653. this._htmlAudioElement.preload = "auto";
  42654. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42655. _this._isReadyToPlay = true;
  42656. if (_this.autoplay) {
  42657. _this.play();
  42658. }
  42659. if (_this._readyToPlayCallback) {
  42660. _this._readyToPlayCallback();
  42661. }
  42662. });
  42663. document.body.appendChild(this._htmlAudioElement);
  42664. }
  42665. break;
  42666. }
  42667. }
  42668. break;
  42669. default:
  42670. validParameter = false;
  42671. break;
  42672. }
  42673. if (!validParameter) {
  42674. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42675. }
  42676. else {
  42677. if (!codecSupportedFound) {
  42678. this._isReadyToPlay = true;
  42679. // Simulating a ready to play event to avoid breaking code path
  42680. if (this._readyToPlayCallback) {
  42681. window.setTimeout(function () {
  42682. _this._readyToPlayCallback();
  42683. }, 1000);
  42684. }
  42685. }
  42686. }
  42687. }
  42688. }
  42689. else {
  42690. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42691. this._scene.mainSoundTrack.AddSound(this);
  42692. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42693. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42694. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42695. }
  42696. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42697. if (this._readyToPlayCallback) {
  42698. window.setTimeout(function () {
  42699. _this._readyToPlayCallback();
  42700. }, 1000);
  42701. }
  42702. }
  42703. }
  42704. Sound.prototype.dispose = function () {
  42705. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42706. if (this.isPlaying) {
  42707. this.stop();
  42708. }
  42709. this._isReadyToPlay = false;
  42710. if (this.soundTrackId === -1) {
  42711. this._scene.mainSoundTrack.RemoveSound(this);
  42712. }
  42713. else {
  42714. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42715. }
  42716. if (this._soundGain) {
  42717. this._soundGain.disconnect();
  42718. this._soundGain = null;
  42719. }
  42720. if (this._soundPanner) {
  42721. this._soundPanner.disconnect();
  42722. this._soundPanner = null;
  42723. }
  42724. if (this._soundSource) {
  42725. this._soundSource.disconnect();
  42726. this._soundSource = null;
  42727. }
  42728. this._audioBuffer = null;
  42729. if (this._htmlAudioElement) {
  42730. this._htmlAudioElement.pause();
  42731. this._htmlAudioElement.src = "";
  42732. document.body.removeChild(this._htmlAudioElement);
  42733. }
  42734. if (this._connectedMesh) {
  42735. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42736. this._connectedMesh = null;
  42737. }
  42738. }
  42739. };
  42740. Sound.prototype.isReady = function () {
  42741. return this._isReadyToPlay;
  42742. };
  42743. Sound.prototype._soundLoaded = function (audioData) {
  42744. var _this = this;
  42745. this._isLoaded = true;
  42746. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42747. _this._audioBuffer = buffer;
  42748. _this._isReadyToPlay = true;
  42749. if (_this.autoplay) {
  42750. _this.play();
  42751. }
  42752. if (_this._readyToPlayCallback) {
  42753. _this._readyToPlayCallback();
  42754. }
  42755. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42756. };
  42757. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42758. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42759. this._audioBuffer = audioBuffer;
  42760. this._isReadyToPlay = true;
  42761. }
  42762. };
  42763. Sound.prototype.updateOptions = function (options) {
  42764. if (options) {
  42765. this.loop = options.loop || this.loop;
  42766. this.maxDistance = options.maxDistance || this.maxDistance;
  42767. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42768. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42769. this.refDistance = options.refDistance || this.refDistance;
  42770. this.distanceModel = options.distanceModel || this.distanceModel;
  42771. this._playbackRate = options.playbackRate || this._playbackRate;
  42772. this._updateSpatialParameters();
  42773. if (this.isPlaying) {
  42774. if (this._streaming) {
  42775. this._htmlAudioElement.playbackRate = this._playbackRate;
  42776. }
  42777. else {
  42778. this._soundSource.playbackRate.value = this._playbackRate;
  42779. }
  42780. }
  42781. }
  42782. };
  42783. Sound.prototype._createSpatialParameters = function () {
  42784. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42785. if (this._scene.headphone) {
  42786. this._panningModel = "HRTF";
  42787. }
  42788. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42789. this._updateSpatialParameters();
  42790. this._soundPanner.connect(this._ouputAudioNode);
  42791. this._inputAudioNode = this._soundPanner;
  42792. }
  42793. };
  42794. Sound.prototype._updateSpatialParameters = function () {
  42795. if (this.spatialSound) {
  42796. if (this.useCustomAttenuation) {
  42797. // Tricks to disable in a way embedded Web Audio attenuation
  42798. this._soundPanner.distanceModel = "linear";
  42799. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42800. this._soundPanner.refDistance = 1;
  42801. this._soundPanner.rolloffFactor = 1;
  42802. this._soundPanner.panningModel = this._panningModel;
  42803. }
  42804. else {
  42805. this._soundPanner.distanceModel = this.distanceModel;
  42806. this._soundPanner.maxDistance = this.maxDistance;
  42807. this._soundPanner.refDistance = this.refDistance;
  42808. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42809. this._soundPanner.panningModel = this._panningModel;
  42810. }
  42811. }
  42812. };
  42813. Sound.prototype.switchPanningModelToHRTF = function () {
  42814. this._panningModel = "HRTF";
  42815. this._switchPanningModel();
  42816. };
  42817. Sound.prototype.switchPanningModelToEqualPower = function () {
  42818. this._panningModel = "equalpower";
  42819. this._switchPanningModel();
  42820. };
  42821. Sound.prototype._switchPanningModel = function () {
  42822. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42823. this._soundPanner.panningModel = this._panningModel;
  42824. }
  42825. };
  42826. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42827. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42828. if (this._isOutputConnected) {
  42829. this._ouputAudioNode.disconnect();
  42830. }
  42831. this._ouputAudioNode.connect(soundTrackAudioNode);
  42832. this._isOutputConnected = true;
  42833. }
  42834. };
  42835. /**
  42836. * Transform this sound into a directional source
  42837. * @param coneInnerAngle Size of the inner cone in degree
  42838. * @param coneOuterAngle Size of the outer cone in degree
  42839. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42840. */
  42841. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42842. if (coneOuterAngle < coneInnerAngle) {
  42843. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42844. return;
  42845. }
  42846. this._coneInnerAngle = coneInnerAngle;
  42847. this._coneOuterAngle = coneOuterAngle;
  42848. this._coneOuterGain = coneOuterGain;
  42849. this._isDirectional = true;
  42850. if (this.isPlaying && this.loop) {
  42851. this.stop();
  42852. this.play();
  42853. }
  42854. };
  42855. Sound.prototype.setPosition = function (newPosition) {
  42856. this._position = newPosition;
  42857. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42858. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42859. }
  42860. };
  42861. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42862. this._localDirection = newLocalDirection;
  42863. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42864. this._updateDirection();
  42865. }
  42866. };
  42867. Sound.prototype._updateDirection = function () {
  42868. var mat = this._connectedMesh.getWorldMatrix();
  42869. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42870. direction.normalize();
  42871. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42872. };
  42873. Sound.prototype.updateDistanceFromListener = function () {
  42874. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42875. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42876. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42877. }
  42878. };
  42879. Sound.prototype.setAttenuationFunction = function (callback) {
  42880. this._customAttenuationFunction = callback;
  42881. };
  42882. /**
  42883. * Play the sound
  42884. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42885. * @param offset (optional) Start the sound setting it at a specific time
  42886. */
  42887. Sound.prototype.play = function (time, offset) {
  42888. var _this = this;
  42889. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42890. try {
  42891. if (this._startOffset < 0) {
  42892. time = -this._startOffset;
  42893. this._startOffset = 0;
  42894. }
  42895. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42896. if (!this._soundSource || !this._streamingSource) {
  42897. if (this.spatialSound) {
  42898. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42899. if (this._isDirectional) {
  42900. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42901. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42902. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42903. if (this._connectedMesh) {
  42904. this._updateDirection();
  42905. }
  42906. else {
  42907. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42908. }
  42909. }
  42910. }
  42911. }
  42912. if (this._streaming) {
  42913. if (!this._streamingSource) {
  42914. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42915. this._htmlAudioElement.onended = function () { _this._onended(); };
  42916. this._htmlAudioElement.playbackRate = this._playbackRate;
  42917. }
  42918. this._streamingSource.disconnect();
  42919. this._streamingSource.connect(this._inputAudioNode);
  42920. this._htmlAudioElement.play();
  42921. }
  42922. else {
  42923. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42924. this._soundSource.buffer = this._audioBuffer;
  42925. this._soundSource.connect(this._inputAudioNode);
  42926. this._soundSource.loop = this.loop;
  42927. this._soundSource.playbackRate.value = this._playbackRate;
  42928. this._soundSource.onended = function () { _this._onended(); };
  42929. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42930. }
  42931. this._startTime = startTime;
  42932. this.isPlaying = true;
  42933. this.isPaused = false;
  42934. }
  42935. catch (ex) {
  42936. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42937. }
  42938. }
  42939. };
  42940. Sound.prototype._onended = function () {
  42941. this.isPlaying = false;
  42942. if (this.onended) {
  42943. this.onended();
  42944. }
  42945. };
  42946. /**
  42947. * Stop the sound
  42948. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42949. */
  42950. Sound.prototype.stop = function (time) {
  42951. if (this.isPlaying) {
  42952. if (this._streaming) {
  42953. this._htmlAudioElement.pause();
  42954. // Test needed for Firefox or it will generate an Invalid State Error
  42955. if (this._htmlAudioElement.currentTime > 0) {
  42956. this._htmlAudioElement.currentTime = 0;
  42957. }
  42958. }
  42959. else {
  42960. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42961. this._soundSource.stop(stopTime);
  42962. this._soundSource.onended = null;
  42963. if (!this.isPaused) {
  42964. this._startOffset = 0;
  42965. }
  42966. }
  42967. this.isPlaying = false;
  42968. }
  42969. };
  42970. Sound.prototype.pause = function () {
  42971. if (this.isPlaying) {
  42972. this.isPaused = true;
  42973. if (this._streaming) {
  42974. this._htmlAudioElement.pause();
  42975. }
  42976. else {
  42977. this.stop(0);
  42978. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42979. }
  42980. }
  42981. };
  42982. Sound.prototype.setVolume = function (newVolume, time) {
  42983. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42984. if (time) {
  42985. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42986. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42987. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42988. }
  42989. else {
  42990. this._soundGain.gain.value = newVolume;
  42991. }
  42992. }
  42993. this._volume = newVolume;
  42994. };
  42995. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42996. this._playbackRate = newPlaybackRate;
  42997. if (this.isPlaying) {
  42998. if (this._streaming) {
  42999. this._htmlAudioElement.playbackRate = this._playbackRate;
  43000. }
  43001. else {
  43002. this._soundSource.playbackRate.value = this._playbackRate;
  43003. }
  43004. }
  43005. };
  43006. Sound.prototype.getVolume = function () {
  43007. return this._volume;
  43008. };
  43009. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  43010. var _this = this;
  43011. if (this._connectedMesh) {
  43012. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43013. this._registerFunc = null;
  43014. }
  43015. this._connectedMesh = meshToConnectTo;
  43016. if (!this.spatialSound) {
  43017. this.spatialSound = true;
  43018. this._createSpatialParameters();
  43019. if (this.isPlaying && this.loop) {
  43020. this.stop();
  43021. this.play();
  43022. }
  43023. }
  43024. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  43025. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  43026. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  43027. };
  43028. Sound.prototype.detachFromMesh = function () {
  43029. if (this._connectedMesh) {
  43030. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43031. this._registerFunc = null;
  43032. this._connectedMesh = null;
  43033. }
  43034. };
  43035. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  43036. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  43037. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  43038. this._updateDirection();
  43039. }
  43040. };
  43041. Sound.prototype.clone = function () {
  43042. var _this = this;
  43043. if (!this._streaming) {
  43044. var setBufferAndRun = function () {
  43045. if (_this._isReadyToPlay) {
  43046. clonedSound._audioBuffer = _this.getAudioBuffer();
  43047. clonedSound._isReadyToPlay = true;
  43048. if (clonedSound.autoplay) {
  43049. clonedSound.play();
  43050. }
  43051. }
  43052. else {
  43053. window.setTimeout(setBufferAndRun, 300);
  43054. }
  43055. };
  43056. var currentOptions = {
  43057. autoplay: this.autoplay, loop: this.loop,
  43058. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43059. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43060. refDistance: this.refDistance, distanceModel: this.distanceModel
  43061. };
  43062. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43063. if (this.useCustomAttenuation) {
  43064. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43065. }
  43066. clonedSound.setPosition(this._position);
  43067. clonedSound.setPlaybackRate(this._playbackRate);
  43068. setBufferAndRun();
  43069. return clonedSound;
  43070. }
  43071. else {
  43072. return null;
  43073. }
  43074. };
  43075. Sound.prototype.getAudioBuffer = function () {
  43076. return this._audioBuffer;
  43077. };
  43078. Sound.prototype.serialize = function () {
  43079. var serializationObject = {
  43080. name: this.name,
  43081. url: this.name,
  43082. autoplay: this.autoplay,
  43083. loop: this.loop,
  43084. volume: this._volume,
  43085. spatialSound: this.spatialSound,
  43086. maxDistance: this.maxDistance,
  43087. rolloffFactor: this.rolloffFactor,
  43088. refDistance: this.refDistance,
  43089. distanceModel: this.distanceModel,
  43090. playbackRate: this._playbackRate,
  43091. panningModel: this._panningModel,
  43092. soundTrackId: this.soundTrackId
  43093. };
  43094. if (this.spatialSound) {
  43095. if (this._connectedMesh)
  43096. serializationObject.connectedMeshId = this._connectedMesh.id;
  43097. serializationObject.position = this._position.asArray();
  43098. serializationObject.refDistance = this.refDistance;
  43099. serializationObject.distanceModel = this.distanceModel;
  43100. serializationObject.isDirectional = this._isDirectional;
  43101. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43102. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43103. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43104. serializationObject.coneOuterGain = this._coneOuterGain;
  43105. }
  43106. return serializationObject;
  43107. };
  43108. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43109. var soundName = parsedSound.name;
  43110. var soundUrl;
  43111. if (parsedSound.url) {
  43112. soundUrl = rootUrl + parsedSound.url;
  43113. }
  43114. else {
  43115. soundUrl = rootUrl + soundName;
  43116. }
  43117. var options = {
  43118. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43119. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43120. rolloffFactor: parsedSound.rolloffFactor,
  43121. refDistance: parsedSound.refDistance,
  43122. distanceModel: parsedSound.distanceModel,
  43123. playbackRate: parsedSound.playbackRate
  43124. };
  43125. var newSound;
  43126. if (!sourceSound) {
  43127. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43128. scene._addPendingData(newSound);
  43129. }
  43130. else {
  43131. var setBufferAndRun = function () {
  43132. if (sourceSound._isReadyToPlay) {
  43133. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43134. newSound._isReadyToPlay = true;
  43135. if (newSound.autoplay) {
  43136. newSound.play();
  43137. }
  43138. }
  43139. else {
  43140. window.setTimeout(setBufferAndRun, 300);
  43141. }
  43142. };
  43143. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43144. setBufferAndRun();
  43145. }
  43146. if (parsedSound.position) {
  43147. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43148. newSound.setPosition(soundPosition);
  43149. }
  43150. if (parsedSound.isDirectional) {
  43151. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43152. if (parsedSound.localDirectionToMesh) {
  43153. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43154. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43155. }
  43156. }
  43157. if (parsedSound.connectedMeshId) {
  43158. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43159. if (connectedMesh) {
  43160. newSound.attachToMesh(connectedMesh);
  43161. }
  43162. }
  43163. return newSound;
  43164. };
  43165. return Sound;
  43166. }());
  43167. BABYLON.Sound = Sound;
  43168. })(BABYLON || (BABYLON = {}));
  43169. //# sourceMappingURL=babylon.sound.js.map
  43170. var BABYLON;
  43171. (function (BABYLON) {
  43172. var SoundTrack = (function () {
  43173. function SoundTrack(scene, options) {
  43174. this.id = -1;
  43175. this._isMainTrack = false;
  43176. this._isInitialized = false;
  43177. this._scene = scene;
  43178. this.soundCollection = new Array();
  43179. this._options = options;
  43180. if (!this._isMainTrack) {
  43181. this._scene.soundTracks.push(this);
  43182. this.id = this._scene.soundTracks.length - 1;
  43183. }
  43184. }
  43185. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43186. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43187. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43188. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43189. if (this._options) {
  43190. if (this._options.volume) {
  43191. this._outputAudioNode.gain.value = this._options.volume;
  43192. }
  43193. if (this._options.mainTrack) {
  43194. this._isMainTrack = this._options.mainTrack;
  43195. }
  43196. }
  43197. this._isInitialized = true;
  43198. }
  43199. };
  43200. SoundTrack.prototype.dispose = function () {
  43201. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43202. if (this._connectedAnalyser) {
  43203. this._connectedAnalyser.stopDebugCanvas();
  43204. }
  43205. while (this.soundCollection.length) {
  43206. this.soundCollection[0].dispose();
  43207. }
  43208. if (this._outputAudioNode) {
  43209. this._outputAudioNode.disconnect();
  43210. }
  43211. this._outputAudioNode = null;
  43212. }
  43213. };
  43214. SoundTrack.prototype.AddSound = function (sound) {
  43215. if (!this._isInitialized) {
  43216. this._initializeSoundTrackAudioGraph();
  43217. }
  43218. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43219. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43220. }
  43221. if (sound.soundTrackId) {
  43222. if (sound.soundTrackId === -1) {
  43223. this._scene.mainSoundTrack.RemoveSound(sound);
  43224. }
  43225. else {
  43226. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  43227. }
  43228. }
  43229. this.soundCollection.push(sound);
  43230. sound.soundTrackId = this.id;
  43231. };
  43232. SoundTrack.prototype.RemoveSound = function (sound) {
  43233. var index = this.soundCollection.indexOf(sound);
  43234. if (index !== -1) {
  43235. this.soundCollection.splice(index, 1);
  43236. }
  43237. };
  43238. SoundTrack.prototype.setVolume = function (newVolume) {
  43239. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43240. this._outputAudioNode.gain.value = newVolume;
  43241. }
  43242. };
  43243. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  43244. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43245. for (var i = 0; i < this.soundCollection.length; i++) {
  43246. this.soundCollection[i].switchPanningModelToHRTF();
  43247. }
  43248. }
  43249. };
  43250. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  43251. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43252. for (var i = 0; i < this.soundCollection.length; i++) {
  43253. this.soundCollection[i].switchPanningModelToEqualPower();
  43254. }
  43255. }
  43256. };
  43257. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  43258. if (this._connectedAnalyser) {
  43259. this._connectedAnalyser.stopDebugCanvas();
  43260. }
  43261. this._connectedAnalyser = analyser;
  43262. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43263. this._outputAudioNode.disconnect();
  43264. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  43265. }
  43266. };
  43267. return SoundTrack;
  43268. }());
  43269. BABYLON.SoundTrack = SoundTrack;
  43270. })(BABYLON || (BABYLON = {}));
  43271. //# sourceMappingURL=babylon.soundtrack.js.map
  43272. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  43273. /// <reference path="..\Math\babylon.math.ts" />
  43274. var BABYLON;
  43275. (function (BABYLON) {
  43276. /**
  43277. * Special Glow Blur post process only blurring the alpha channel
  43278. * It enforces keeping the most luminous color in the color channel.
  43279. */
  43280. var GlowBlurPostProcess = (function (_super) {
  43281. __extends(GlowBlurPostProcess, _super);
  43282. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43284. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  43285. _this.direction = direction;
  43286. _this.blurWidth = blurWidth;
  43287. _this.onApplyObservable.add(function (effect) {
  43288. effect.setFloat2("screenSize", _this.width, _this.height);
  43289. effect.setVector2("direction", _this.direction);
  43290. effect.setFloat("blurWidth", _this.blurWidth);
  43291. });
  43292. return _this;
  43293. }
  43294. return GlowBlurPostProcess;
  43295. }(BABYLON.PostProcess));
  43296. /**
  43297. * The highlight layer Helps adding a glow effect around a mesh.
  43298. *
  43299. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  43300. * glowy meshes to your scene.
  43301. *
  43302. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  43303. */
  43304. var HighlightLayer = (function () {
  43305. /**
  43306. * Instantiates a new highlight Layer and references it to the scene..
  43307. * @param name The name of the layer
  43308. * @param scene The scene to use the layer in
  43309. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  43310. */
  43311. function HighlightLayer(name, scene, options) {
  43312. this.name = name;
  43313. this._vertexBuffers = {};
  43314. this._mainTextureDesiredSize = { width: 0, height: 0 };
  43315. this._meshes = {};
  43316. this._maxSize = 0;
  43317. this._shouldRender = false;
  43318. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  43319. this._excludedMeshes = {};
  43320. /**
  43321. * Specifies whether or not the inner glow is ACTIVE in the layer.
  43322. */
  43323. this.innerGlow = true;
  43324. /**
  43325. * Specifies whether or not the outer glow is ACTIVE in the layer.
  43326. */
  43327. this.outerGlow = true;
  43328. /**
  43329. * Specifies wether the highlight layer is enabled or not.
  43330. */
  43331. this.isEnabled = true;
  43332. /**
  43333. * An event triggered when the highlight layer has been disposed.
  43334. * @type {BABYLON.Observable}
  43335. */
  43336. this.onDisposeObservable = new BABYLON.Observable();
  43337. /**
  43338. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  43339. * @type {BABYLON.Observable}
  43340. */
  43341. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  43342. /**
  43343. * An event triggered when the highlight layer is being blurred.
  43344. * @type {BABYLON.Observable}
  43345. */
  43346. this.onBeforeBlurObservable = new BABYLON.Observable();
  43347. /**
  43348. * An event triggered when the highlight layer has been blurred.
  43349. * @type {BABYLON.Observable}
  43350. */
  43351. this.onAfterBlurObservable = new BABYLON.Observable();
  43352. /**
  43353. * An event triggered when the glowing blurred texture is being merged in the scene.
  43354. * @type {BABYLON.Observable}
  43355. */
  43356. this.onBeforeComposeObservable = new BABYLON.Observable();
  43357. /**
  43358. * An event triggered when the glowing blurred texture has been merged in the scene.
  43359. * @type {BABYLON.Observable}
  43360. */
  43361. this.onAfterComposeObservable = new BABYLON.Observable();
  43362. /**
  43363. * An event triggered when the highlight layer changes its size.
  43364. * @type {BABYLON.Observable}
  43365. */
  43366. this.onSizeChangedObservable = new BABYLON.Observable();
  43367. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43368. var engine = scene.getEngine();
  43369. this._engine = engine;
  43370. this._maxSize = this._engine.getCaps().maxTextureSize;
  43371. this._scene.highlightLayers.push(this);
  43372. // Warn on stencil.
  43373. if (!this._engine.isStencilEnable) {
  43374. 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 }");
  43375. }
  43376. // Adapt options
  43377. this._options = options || {
  43378. mainTextureRatio: 0.25,
  43379. blurTextureSizeRatio: 0.5,
  43380. blurHorizontalSize: 1,
  43381. blurVerticalSize: 1,
  43382. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  43383. };
  43384. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  43385. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  43386. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  43387. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  43388. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  43389. // VBO
  43390. var vertices = [];
  43391. vertices.push(1, 1);
  43392. vertices.push(-1, 1);
  43393. vertices.push(-1, -1);
  43394. vertices.push(1, -1);
  43395. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43396. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  43397. // Indices
  43398. var indices = [];
  43399. indices.push(0);
  43400. indices.push(1);
  43401. indices.push(2);
  43402. indices.push(0);
  43403. indices.push(2);
  43404. indices.push(3);
  43405. this._indexBuffer = engine.createIndexBuffer(indices);
  43406. // Effect
  43407. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  43408. // Render target
  43409. this.setMainTextureSize();
  43410. // Create Textures and post processes
  43411. this.createTextureAndPostProcesses();
  43412. }
  43413. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  43414. /**
  43415. * Gets the horizontal size of the blur.
  43416. */
  43417. get: function () {
  43418. return this._horizontalBlurPostprocess.blurWidth;
  43419. },
  43420. /**
  43421. * Specifies the horizontal size of the blur.
  43422. */
  43423. set: function (value) {
  43424. this._horizontalBlurPostprocess.blurWidth = value;
  43425. },
  43426. enumerable: true,
  43427. configurable: true
  43428. });
  43429. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  43430. /**
  43431. * Gets the vertical size of the blur.
  43432. */
  43433. get: function () {
  43434. return this._verticalBlurPostprocess.blurWidth;
  43435. },
  43436. /**
  43437. * Specifies the vertical size of the blur.
  43438. */
  43439. set: function (value) {
  43440. this._verticalBlurPostprocess.blurWidth = value;
  43441. },
  43442. enumerable: true,
  43443. configurable: true
  43444. });
  43445. Object.defineProperty(HighlightLayer.prototype, "camera", {
  43446. /**
  43447. * Gets the camera attached to the layer.
  43448. */
  43449. get: function () {
  43450. return this._options.camera;
  43451. },
  43452. enumerable: true,
  43453. configurable: true
  43454. });
  43455. /**
  43456. * Creates the render target textures and post processes used in the highlight layer.
  43457. */
  43458. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  43459. var _this = this;
  43460. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  43461. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  43462. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  43463. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  43464. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  43465. width: this._mainTextureDesiredSize.width,
  43466. height: this._mainTextureDesiredSize.height
  43467. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43468. this._mainTexture.activeCamera = this._options.camera;
  43469. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43470. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43471. this._mainTexture.anisotropicFilteringLevel = 1;
  43472. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43473. this._mainTexture.renderParticles = false;
  43474. this._mainTexture.renderList = null;
  43475. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  43476. width: blurTextureWidth,
  43477. height: blurTextureHeight
  43478. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43479. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43480. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43481. this._blurTexture.anisotropicFilteringLevel = 16;
  43482. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  43483. this._blurTexture.renderParticles = false;
  43484. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43485. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43486. effect.setTexture("textureSampler", _this._mainTexture);
  43487. });
  43488. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  43489. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43490. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43491. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43492. });
  43493. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43494. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43495. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43496. });
  43497. }
  43498. else {
  43499. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43500. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43501. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43502. });
  43503. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43504. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43505. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43506. });
  43507. }
  43508. this._mainTexture.onAfterUnbindObservable.add(function () {
  43509. _this.onBeforeBlurObservable.notifyObservers(_this);
  43510. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  43511. _this.onAfterBlurObservable.notifyObservers(_this);
  43512. });
  43513. // Custom render function
  43514. var renderSubMesh = function (subMesh) {
  43515. var mesh = subMesh.getRenderingMesh();
  43516. var scene = _this._scene;
  43517. var engine = scene.getEngine();
  43518. // Culling
  43519. engine.setState(subMesh.getMaterial().backFaceCulling);
  43520. // Managing instances
  43521. var batch = mesh._getInstancesRenderList(subMesh._id);
  43522. if (batch.mustReturn) {
  43523. return;
  43524. }
  43525. // Excluded Mesh
  43526. if (_this._excludedMeshes[mesh.uniqueId]) {
  43527. return;
  43528. }
  43529. ;
  43530. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43531. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  43532. var material = subMesh.getMaterial();
  43533. var emissiveTexture = null;
  43534. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  43535. emissiveTexture = material.emissiveTexture;
  43536. }
  43537. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  43538. engine.enableEffect(_this._glowMapGenerationEffect);
  43539. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  43540. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  43541. if (highlightLayerMesh) {
  43542. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  43543. }
  43544. else {
  43545. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  43546. }
  43547. // Alpha test
  43548. if (material && material.needAlphaTesting()) {
  43549. var alphaTexture = material.getAlphaTestTexture();
  43550. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  43551. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43552. }
  43553. // Glow emissive only
  43554. if (emissiveTexture) {
  43555. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  43556. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  43557. }
  43558. // Bones
  43559. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43560. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43561. }
  43562. // Draw
  43563. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  43564. }
  43565. else {
  43566. // Need to reset refresh rate of the shadowMap
  43567. _this._mainTexture.resetRefreshCounter();
  43568. }
  43569. };
  43570. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43571. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  43572. var index;
  43573. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43574. renderSubMesh(opaqueSubMeshes.data[index]);
  43575. }
  43576. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43577. renderSubMesh(alphaTestSubMeshes.data[index]);
  43578. }
  43579. for (index = 0; index < transparentSubMeshes.length; index++) {
  43580. renderSubMesh(transparentSubMeshes.data[index]);
  43581. }
  43582. };
  43583. this._mainTexture.onClearObservable.add(function (engine) {
  43584. engine.clear(HighlightLayer.neutralColor, true, true, true);
  43585. });
  43586. };
  43587. /**
  43588. * Checks for the readiness of the element composing the layer.
  43589. * @param subMesh the mesh to check for
  43590. * @param useInstances specify wether or not to use instances to render the mesh
  43591. * @param emissiveTexture the associated emissive texture used to generate the glow
  43592. * @return true if ready otherwise, false
  43593. */
  43594. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  43595. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  43596. return false;
  43597. }
  43598. var defines = [];
  43599. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43600. var mesh = subMesh.getMesh();
  43601. var material = subMesh.getMaterial();
  43602. var uv1 = false;
  43603. var uv2 = false;
  43604. // Alpha test
  43605. if (material && material.needAlphaTesting()) {
  43606. var alphaTexture = material.getAlphaTestTexture();
  43607. if (alphaTexture) {
  43608. defines.push("#define ALPHATEST");
  43609. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43610. alphaTexture.coordinatesIndex === 1) {
  43611. defines.push("#define DIFFUSEUV2");
  43612. uv2 = true;
  43613. }
  43614. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43615. defines.push("#define DIFFUSEUV1");
  43616. uv1 = true;
  43617. }
  43618. }
  43619. }
  43620. // Emissive
  43621. if (emissiveTexture) {
  43622. defines.push("#define EMISSIVE");
  43623. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43624. emissiveTexture.coordinatesIndex === 1) {
  43625. defines.push("#define EMISSIVEUV2");
  43626. uv2 = true;
  43627. }
  43628. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43629. defines.push("#define EMISSIVEUV1");
  43630. uv1 = true;
  43631. }
  43632. }
  43633. if (uv1) {
  43634. attribs.push(BABYLON.VertexBuffer.UVKind);
  43635. defines.push("#define UV1");
  43636. }
  43637. if (uv2) {
  43638. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43639. defines.push("#define UV2");
  43640. }
  43641. // Bones
  43642. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43645. if (mesh.numBoneInfluencers > 4) {
  43646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43648. }
  43649. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43650. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43651. }
  43652. else {
  43653. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43654. }
  43655. // Instances
  43656. if (useInstances) {
  43657. defines.push("#define INSTANCES");
  43658. attribs.push("world0");
  43659. attribs.push("world1");
  43660. attribs.push("world2");
  43661. attribs.push("world3");
  43662. }
  43663. // Get correct effect
  43664. var join = defines.join("\n");
  43665. if (this._cachedDefines !== join) {
  43666. this._cachedDefines = join;
  43667. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  43668. }
  43669. return this._glowMapGenerationEffect.isReady();
  43670. };
  43671. /**
  43672. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  43673. */
  43674. HighlightLayer.prototype.render = function () {
  43675. var currentEffect = this._glowMapMergeEffect;
  43676. // Check
  43677. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  43678. return;
  43679. var engine = this._scene.getEngine();
  43680. this.onBeforeComposeObservable.notifyObservers(this);
  43681. // Render
  43682. engine.enableEffect(currentEffect);
  43683. engine.setState(false);
  43684. // Cache
  43685. var previousStencilBuffer = engine.getStencilBuffer();
  43686. var previousStencilFunction = engine.getStencilFunction();
  43687. var previousStencilMask = engine.getStencilMask();
  43688. var previousAlphaMode = engine.getAlphaMode();
  43689. // Texture
  43690. currentEffect.setTexture("textureSampler", this._blurTexture);
  43691. // VBOs
  43692. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  43693. // Draw order
  43694. engine.setAlphaMode(this._options.alphaBlendingMode);
  43695. engine.setStencilMask(0x00);
  43696. engine.setStencilBuffer(true);
  43697. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  43698. if (this.outerGlow) {
  43699. currentEffect.setFloat("offset", 0);
  43700. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  43701. engine.draw(true, 0, 6);
  43702. }
  43703. if (this.innerGlow) {
  43704. currentEffect.setFloat("offset", 1);
  43705. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  43706. engine.draw(true, 0, 6);
  43707. }
  43708. // Restore Cache
  43709. engine.setStencilFunction(previousStencilFunction);
  43710. engine.setStencilMask(previousStencilMask);
  43711. engine.setAlphaMode(previousAlphaMode);
  43712. engine.setStencilBuffer(previousStencilBuffer);
  43713. this.onAfterComposeObservable.notifyObservers(this);
  43714. // Handle size changes.
  43715. var size = this._mainTexture.getSize();
  43716. this.setMainTextureSize();
  43717. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  43718. // Recreate RTT and post processes on size change.
  43719. this.onSizeChangedObservable.notifyObservers(this);
  43720. this.disposeTextureAndPostProcesses();
  43721. this.createTextureAndPostProcesses();
  43722. }
  43723. };
  43724. /**
  43725. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  43726. * @param mesh The mesh to exclude from the highlight layer
  43727. */
  43728. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  43729. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43730. if (!meshExcluded) {
  43731. this._excludedMeshes[mesh.uniqueId] = {
  43732. mesh: mesh,
  43733. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  43734. mesh.getEngine().setStencilBuffer(false);
  43735. }),
  43736. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  43737. mesh.getEngine().setStencilBuffer(true);
  43738. }),
  43739. };
  43740. }
  43741. };
  43742. /**
  43743. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  43744. * @param mesh The mesh to highlight
  43745. */
  43746. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  43747. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43748. if (meshExcluded) {
  43749. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  43750. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  43751. }
  43752. this._excludedMeshes[mesh.uniqueId] = undefined;
  43753. };
  43754. /**
  43755. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  43756. * @param mesh The mesh to highlight
  43757. * @param color The color of the highlight
  43758. * @param glowEmissiveOnly Extract the glow from the emissive texture
  43759. */
  43760. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  43761. var _this = this;
  43762. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  43763. var meshHighlight = this._meshes[mesh.uniqueId];
  43764. if (meshHighlight) {
  43765. meshHighlight.color = color;
  43766. }
  43767. else {
  43768. this._meshes[mesh.uniqueId] = {
  43769. mesh: mesh,
  43770. color: color,
  43771. // Lambda required for capture due to Observable this context
  43772. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  43773. if (_this._excludedMeshes[mesh.uniqueId]) {
  43774. _this.defaultStencilReference(mesh);
  43775. }
  43776. else {
  43777. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  43778. }
  43779. }),
  43780. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  43781. glowEmissiveOnly: glowEmissiveOnly
  43782. };
  43783. }
  43784. this._shouldRender = true;
  43785. };
  43786. /**
  43787. * Remove a mesh from the highlight layer in order to make it stop glowing.
  43788. * @param mesh The mesh to highlight
  43789. */
  43790. HighlightLayer.prototype.removeMesh = function (mesh) {
  43791. var meshHighlight = this._meshes[mesh.uniqueId];
  43792. if (meshHighlight) {
  43793. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43794. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43795. }
  43796. this._meshes[mesh.uniqueId] = undefined;
  43797. this._shouldRender = false;
  43798. for (var meshHighlightToCheck in this._meshes) {
  43799. if (meshHighlightToCheck) {
  43800. this._shouldRender = true;
  43801. break;
  43802. }
  43803. }
  43804. };
  43805. /**
  43806. * Returns true if the layer contains information to display, otherwise false.
  43807. */
  43808. HighlightLayer.prototype.shouldRender = function () {
  43809. return this.isEnabled && this._shouldRender;
  43810. };
  43811. /**
  43812. * Sets the main texture desired size which is the closest power of two
  43813. * of the engine canvas size.
  43814. */
  43815. HighlightLayer.prototype.setMainTextureSize = function () {
  43816. if (this._options.mainTextureFixedSize) {
  43817. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  43818. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  43819. }
  43820. else {
  43821. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  43822. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  43823. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  43824. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  43825. }
  43826. };
  43827. /**
  43828. * Force the stencil to the normal expected value for none glowing parts
  43829. */
  43830. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  43831. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  43832. };
  43833. /**
  43834. * Dispose only the render target textures and post process.
  43835. */
  43836. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  43837. this._blurTexture.dispose();
  43838. this._mainTexture.dispose();
  43839. this._downSamplePostprocess.dispose();
  43840. this._horizontalBlurPostprocess.dispose();
  43841. this._verticalBlurPostprocess.dispose();
  43842. };
  43843. /**
  43844. * Dispose the highlight layer and free resources.
  43845. */
  43846. HighlightLayer.prototype.dispose = function () {
  43847. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43848. if (vertexBuffer) {
  43849. vertexBuffer.dispose();
  43850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43851. }
  43852. if (this._indexBuffer) {
  43853. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43854. this._indexBuffer = null;
  43855. }
  43856. // Clean textures and post processes
  43857. this.disposeTextureAndPostProcesses();
  43858. // Clean mesh references
  43859. for (var id in this._meshes) {
  43860. var meshHighlight = this._meshes[id];
  43861. if (meshHighlight && meshHighlight.mesh) {
  43862. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43863. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43864. }
  43865. }
  43866. this._meshes = null;
  43867. for (var id in this._excludedMeshes) {
  43868. var meshHighlight = this._excludedMeshes[id];
  43869. if (meshHighlight) {
  43870. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  43871. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  43872. }
  43873. }
  43874. this._excludedMeshes = null;
  43875. // Remove from scene
  43876. var index = this._scene.highlightLayers.indexOf(this, 0);
  43877. if (index > -1) {
  43878. this._scene.highlightLayers.splice(index, 1);
  43879. }
  43880. // Callback
  43881. this.onDisposeObservable.notifyObservers(this);
  43882. this.onDisposeObservable.clear();
  43883. this.onBeforeRenderMainTextureObservable.clear();
  43884. this.onBeforeBlurObservable.clear();
  43885. this.onBeforeComposeObservable.clear();
  43886. this.onAfterComposeObservable.clear();
  43887. this.onSizeChangedObservable.clear();
  43888. };
  43889. return HighlightLayer;
  43890. }());
  43891. /**
  43892. * The neutral color used during the preparation of the glow effect.
  43893. * This is black by default as the blend operation is a blend operation.
  43894. */
  43895. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  43896. /**
  43897. * Stencil value used for glowing meshes.
  43898. */
  43899. HighlightLayer.glowingMeshStencilReference = 0x02;
  43900. /**
  43901. * Stencil value used for the other meshes in the scene.
  43902. */
  43903. HighlightLayer.normalMeshStencilReference = 0x01;
  43904. BABYLON.HighlightLayer = HighlightLayer;
  43905. })(BABYLON || (BABYLON = {}));
  43906. //# sourceMappingURL=babylon.highlightlayer.js.map
  43907. var BABYLON;
  43908. (function (BABYLON) {
  43909. var SIMDVector3 = (function () {
  43910. function SIMDVector3() {
  43911. }
  43912. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  43913. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  43914. };
  43915. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  43916. var m = transformation.m;
  43917. var m0 = SIMD.Float32x4.load(m, 0);
  43918. var m1 = SIMD.Float32x4.load(m, 4);
  43919. var m2 = SIMD.Float32x4.load(m, 8);
  43920. var m3 = SIMD.Float32x4.load(m, 12);
  43921. 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));
  43922. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  43923. result.x = SIMD.Float32x4.extractLane(r, 0);
  43924. result.y = SIMD.Float32x4.extractLane(r, 1);
  43925. result.z = SIMD.Float32x4.extractLane(r, 2);
  43926. };
  43927. return SIMDVector3;
  43928. }());
  43929. var SIMDMatrix = (function () {
  43930. function SIMDMatrix() {
  43931. }
  43932. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  43933. var tm = this.m;
  43934. var om = other.m;
  43935. var m0 = SIMD.Float32x4.load(om, 0);
  43936. var m1 = SIMD.Float32x4.load(om, 4);
  43937. var m2 = SIMD.Float32x4.load(om, 8);
  43938. var m3 = SIMD.Float32x4.load(om, 12);
  43939. for (var i = 0; i < 16; i += 4) {
  43940. 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)))));
  43941. }
  43942. return this;
  43943. };
  43944. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  43945. var src = this.m;
  43946. var dest = other.m;
  43947. // Load the 4 rows
  43948. var src0 = SIMD.Float32x4.load(src, 0);
  43949. var src1 = SIMD.Float32x4.load(src, 4);
  43950. var src2 = SIMD.Float32x4.load(src, 8);
  43951. var src3 = SIMD.Float32x4.load(src, 12);
  43952. // Transpose the source matrix. Sort of. Not a true transpose operation
  43953. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  43954. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  43955. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  43956. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  43957. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  43958. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  43959. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  43960. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  43961. // This is a true transposition, but it will lead to an incorrect result
  43962. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  43963. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  43964. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43965. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43966. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  43967. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  43968. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43969. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43970. // ----
  43971. tmp1 = SIMD.Float32x4.mul(row2, row3);
  43972. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43973. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  43974. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  43975. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43976. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  43977. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  43978. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  43979. // ----
  43980. tmp1 = SIMD.Float32x4.mul(row1, row2);
  43981. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43982. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  43983. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  43984. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43985. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  43986. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  43987. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  43988. // ----
  43989. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  43990. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43991. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  43992. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  43993. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  43994. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43995. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  43996. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  43997. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  43998. // ----
  43999. tmp1 = SIMD.Float32x4.mul(row0, row1);
  44000. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44001. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  44002. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  44003. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44004. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  44005. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  44006. // ----
  44007. tmp1 = SIMD.Float32x4.mul(row0, row3);
  44008. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44009. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  44010. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  44011. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44012. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  44013. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  44014. // ----
  44015. tmp1 = SIMD.Float32x4.mul(row0, row2);
  44016. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44017. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  44018. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  44019. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44020. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  44021. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  44022. // Compute determinant
  44023. var det = SIMD.Float32x4.mul(row0, minor0);
  44024. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  44025. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  44026. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  44027. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  44028. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  44029. // These shuffles aren't necessary if the faulty transposition is done
  44030. // up at the top of this function.
  44031. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  44032. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  44033. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  44034. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  44035. // Compute final values by multiplying with 1/det
  44036. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  44037. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  44038. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  44039. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  44040. return this;
  44041. };
  44042. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  44043. var out = result.m;
  44044. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  44045. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  44046. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  44047. // cc.kmVec3Subtract(f, pCenter, pEye);
  44048. var f = SIMD.Float32x4.sub(center, eye);
  44049. // cc.kmVec3Normalize(f, f);
  44050. var tmp = SIMD.Float32x4.mul(f, f);
  44051. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44052. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44053. // cc.kmVec3Assign(up, pUp);
  44054. // cc.kmVec3Normalize(up, up);
  44055. tmp = SIMD.Float32x4.mul(up, up);
  44056. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44057. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44058. // cc.kmVec3Cross(s, f, up);
  44059. 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)));
  44060. // cc.kmVec3Normalize(s, s);
  44061. tmp = SIMD.Float32x4.mul(s, s);
  44062. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44063. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44064. // cc.kmVec3Cross(u, s, f);
  44065. 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)));
  44066. // cc.kmVec3Normalize(s, s);
  44067. tmp = SIMD.Float32x4.mul(s, s);
  44068. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44069. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44070. var zero = SIMD.Float32x4.splat(0.0);
  44071. s = SIMD.Float32x4.neg(s);
  44072. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  44073. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  44074. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  44075. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  44076. 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);
  44077. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  44078. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  44079. 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)))));
  44080. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  44081. 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)))));
  44082. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  44083. 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)))));
  44084. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  44085. 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)))));
  44086. };
  44087. return SIMDMatrix;
  44088. }());
  44089. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  44090. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  44091. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  44092. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  44093. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  44094. var SIMDHelper = (function () {
  44095. function SIMDHelper() {
  44096. }
  44097. Object.defineProperty(SIMDHelper, "IsEnabled", {
  44098. get: function () {
  44099. return SIMDHelper._isEnabled;
  44100. },
  44101. enumerable: true,
  44102. configurable: true
  44103. });
  44104. SIMDHelper.DisableSIMD = function () {
  44105. // Replace functions
  44106. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  44107. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  44108. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  44109. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  44110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  44111. SIMDHelper._isEnabled = false;
  44112. };
  44113. SIMDHelper.EnableSIMD = function () {
  44114. if (self.SIMD === undefined) {
  44115. return;
  44116. }
  44117. // check if polyfills needed
  44118. if (!self.Math.fround) {
  44119. self.Math.fround = (function (array) { return function (x) {
  44120. return array[0] = x, array[0];
  44121. }; })(new Float32Array(1));
  44122. }
  44123. if (!self.Math.imul) {
  44124. self.Math.imul = function (a, b) {
  44125. var ah = (a >>> 16) & 0xffff;
  44126. var al = a & 0xffff;
  44127. var bh = (b >>> 16) & 0xffff;
  44128. var bl = b & 0xffff;
  44129. // the shift by 0 fixes the sign on the high part
  44130. // the final |0 converts the unsigned value into a signed value
  44131. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  44132. };
  44133. }
  44134. // Replace functions
  44135. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  44136. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  44137. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  44138. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  44139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  44140. SIMDHelper._isEnabled = true;
  44141. };
  44142. return SIMDHelper;
  44143. }());
  44144. SIMDHelper._isEnabled = false;
  44145. BABYLON.SIMDHelper = SIMDHelper;
  44146. })(BABYLON || (BABYLON = {}));
  44147. //# sourceMappingURL=babylon.math.SIMD.js.map
  44148. var BABYLON;
  44149. (function (BABYLON) {
  44150. /**
  44151. * This class describe a rectangle that were added to the map.
  44152. * You have access to its coordinates either in pixel or normalized (UV)
  44153. */
  44154. var PackedRect = (function () {
  44155. function PackedRect(root, parent, pos, size) {
  44156. this._pos = pos;
  44157. this._size = size;
  44158. this._root = root;
  44159. this._parent = parent;
  44160. this._contentSize = null;
  44161. this._bottomNode = null;
  44162. this._leftNode = null;
  44163. this._initialSize = null;
  44164. this._rightNode = null;
  44165. }
  44166. Object.defineProperty(PackedRect.prototype, "pos", {
  44167. /**
  44168. * @returns the position of this node into the map
  44169. */
  44170. get: function () {
  44171. return this._pos;
  44172. },
  44173. enumerable: true,
  44174. configurable: true
  44175. });
  44176. Object.defineProperty(PackedRect.prototype, "contentSize", {
  44177. /**
  44178. * @returns the size of the rectangle this node handles
  44179. */
  44180. get: function () {
  44181. return this._contentSize;
  44182. },
  44183. enumerable: true,
  44184. configurable: true
  44185. });
  44186. /**
  44187. * Retrieve the inner position (considering the margin) and stores it into the res object
  44188. * @param res must be a valid Vector2 that will contain the inner position after this call
  44189. */
  44190. PackedRect.prototype.getInnerPosToRef = function (res) {
  44191. var m = this._root._margin;
  44192. res.x = this._pos.x + m;
  44193. res.y = this._pos.y + m;
  44194. };
  44195. /**
  44196. * Retrieve the inner size (considering the margin) and stores it into the res object
  44197. * @param res must be a valid Size that will contain the inner size after this call
  44198. */
  44199. PackedRect.prototype.getInnerSizeToRef = function (res) {
  44200. var m = this._root._margin;
  44201. res.width = this._contentSize.width - (m * 2);
  44202. res.height = this._contentSize.height - (m * 2);
  44203. };
  44204. Object.defineProperty(PackedRect.prototype, "UVs", {
  44205. /**
  44206. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  44207. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  44208. */
  44209. get: function () {
  44210. if (!this._contentSize) {
  44211. throw new Error("Can't compute UVs for this object because it's nor allocated");
  44212. }
  44213. return this.getUVsForCustomSize(this._contentSize);
  44214. },
  44215. enumerable: true,
  44216. configurable: true
  44217. });
  44218. /**
  44219. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  44220. * and then using only a part of the PackRect.
  44221. * This method will return the UVs for this part by given the custom size of what you really use
  44222. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  44223. */
  44224. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  44225. var mainWidth = this._root._size.width;
  44226. var mainHeight = this._root._size.height;
  44227. var margin = this._root._margin;
  44228. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  44229. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  44230. var uvs = new Array();
  44231. uvs.push(topLeft);
  44232. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  44233. uvs.push(rightBottom);
  44234. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  44235. return uvs;
  44236. };
  44237. /**
  44238. * Free this rectangle from the map.
  44239. * Call this method when you no longer need the rectangle to be in the map.
  44240. */
  44241. PackedRect.prototype.freeContent = function () {
  44242. if (!this.contentSize) {
  44243. return;
  44244. }
  44245. this._contentSize = null;
  44246. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  44247. this.attemptDefrag();
  44248. };
  44249. Object.defineProperty(PackedRect.prototype, "isUsed", {
  44250. get: function () {
  44251. return this._contentSize != null || this._leftNode != null;
  44252. },
  44253. enumerable: true,
  44254. configurable: true
  44255. });
  44256. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  44257. var node = this.findNode(contentSize);
  44258. // Not enough space...
  44259. if (!node) {
  44260. return null;
  44261. }
  44262. node.splitNode(contentSize);
  44263. return node;
  44264. };
  44265. PackedRect.prototype.findNode = function (size) {
  44266. var resNode = null;
  44267. var margin = this._root._margin * 2;
  44268. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  44269. if (this.isUsed) {
  44270. if (this._leftNode) {
  44271. resNode = this._leftNode.findNode(size);
  44272. }
  44273. if (!resNode && this._rightNode) {
  44274. resNode = this._rightNode.findNode(size);
  44275. }
  44276. if (!resNode && this._bottomNode) {
  44277. resNode = this._bottomNode.findNode(size);
  44278. }
  44279. }
  44280. else if (this._initialSize) {
  44281. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  44282. resNode = this;
  44283. }
  44284. else {
  44285. return null;
  44286. }
  44287. }
  44288. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  44289. resNode = this;
  44290. }
  44291. return resNode;
  44292. };
  44293. PackedRect.prototype.splitNode = function (contentSize) {
  44294. var cs = PackedRect.TpsSize;
  44295. var margin = this._root._margin * 2;
  44296. cs.copyFrom(contentSize);
  44297. cs.width += margin;
  44298. cs.height += margin;
  44299. // 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)
  44300. if (!this._contentSize && this._initialSize) {
  44301. this._contentSize = cs.clone();
  44302. 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));
  44303. return this._leftNode.splitNode(contentSize);
  44304. }
  44305. else {
  44306. this._contentSize = cs.clone();
  44307. this._initialSize = cs.clone();
  44308. if (cs.width !== this._size.width) {
  44309. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  44310. }
  44311. if (cs.height !== this._size.height) {
  44312. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  44313. }
  44314. return this;
  44315. }
  44316. };
  44317. PackedRect.prototype.attemptDefrag = function () {
  44318. if (!this.isUsed && this.isRecursiveFree) {
  44319. this.clearNode();
  44320. if (this._parent) {
  44321. this._parent.attemptDefrag();
  44322. }
  44323. }
  44324. };
  44325. PackedRect.prototype.clearNode = function () {
  44326. this._initialSize = null;
  44327. this._rightNode = null;
  44328. this._bottomNode = null;
  44329. };
  44330. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  44331. get: function () {
  44332. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  44333. },
  44334. enumerable: true,
  44335. configurable: true
  44336. });
  44337. PackedRect.prototype.evalFreeSize = function (size) {
  44338. var levelSize = 0;
  44339. if (!this.isUsed) {
  44340. var margin = this._root._margin;
  44341. var is = this._initialSize;
  44342. if (is) {
  44343. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  44344. }
  44345. else {
  44346. var size_1 = this._size;
  44347. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  44348. }
  44349. }
  44350. if (this._rightNode) {
  44351. levelSize += this._rightNode.evalFreeSize(0);
  44352. }
  44353. if (this._bottomNode) {
  44354. levelSize += this._bottomNode.evalFreeSize(0);
  44355. }
  44356. return levelSize + size;
  44357. };
  44358. return PackedRect;
  44359. }());
  44360. PackedRect.TpsSize = BABYLON.Size.Zero();
  44361. BABYLON.PackedRect = PackedRect;
  44362. /**
  44363. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  44364. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  44365. * 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.
  44366. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  44367. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  44368. */
  44369. var RectPackingMap = (function (_super) {
  44370. __extends(RectPackingMap, _super);
  44371. /**
  44372. * Create an instance of the object with a dimension using the given size
  44373. * @param size The dimension of the rectangle that will contain all the sub ones.
  44374. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  44375. */
  44376. function RectPackingMap(size, margin) {
  44377. if (margin === void 0) { margin = 0; }
  44378. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  44379. _this._margin = margin;
  44380. _this._root = _this;
  44381. return _this;
  44382. }
  44383. /**
  44384. * Add a rectangle, finding the best location to store it into the map
  44385. * @param size the dimension of the rectangle to store
  44386. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  44387. */
  44388. RectPackingMap.prototype.addRect = function (size) {
  44389. var node = this.findAndSplitNode(size);
  44390. return node;
  44391. };
  44392. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  44393. /**
  44394. * Return the current space free normalized between [0;1]
  44395. * @returns {}
  44396. */
  44397. get: function () {
  44398. var freeSize = 0;
  44399. freeSize = this.evalFreeSize(freeSize);
  44400. return freeSize / (this._size.width * this._size.height);
  44401. },
  44402. enumerable: true,
  44403. configurable: true
  44404. });
  44405. return RectPackingMap;
  44406. }(PackedRect));
  44407. BABYLON.RectPackingMap = RectPackingMap;
  44408. })(BABYLON || (BABYLON = {}));
  44409. //# sourceMappingURL=babylon.rectPackingMap.js.map
  44410. var BABYLON;
  44411. (function (BABYLON) {
  44412. var DynamicFloatArrayElementInfo = (function () {
  44413. function DynamicFloatArrayElementInfo() {
  44414. }
  44415. return DynamicFloatArrayElementInfo;
  44416. }());
  44417. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  44418. /**
  44419. * 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.
  44420. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  44421. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  44422. * 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.
  44423. * 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.
  44424. * 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".
  44425. */
  44426. var DynamicFloatArray = (function () {
  44427. /**
  44428. * Construct an instance of the dynamic float array
  44429. * @param stride size of one element in float (i.e. not bytes!)
  44430. * @param initialElementCount the number of available entries at construction
  44431. */
  44432. function DynamicFloatArray(stride, initialElementCount) {
  44433. this.compareValueOffset = null;
  44434. this.sortingAscending = true;
  44435. this._stride = stride;
  44436. this.buffer = new Float32Array(stride * initialElementCount);
  44437. this._lastUsed = 0;
  44438. this._firstFree = 0;
  44439. this._allEntries = new Array(initialElementCount);
  44440. this._freeEntries = new Array(initialElementCount);
  44441. for (var i = 0; i < initialElementCount; i++) {
  44442. var element = new DynamicFloatArrayElementInfo();
  44443. element.offset = i * stride;
  44444. this._allEntries[i] = element;
  44445. this._freeEntries[initialElementCount - i - 1] = element;
  44446. }
  44447. }
  44448. /**
  44449. * Allocate an element in the array.
  44450. * @return the element info instance that contains the offset into the main buffer of the element's location.
  44451. * Beware, this offset may change when you call pack()
  44452. */
  44453. DynamicFloatArray.prototype.allocElement = function () {
  44454. if (this._freeEntries.length === 0) {
  44455. this._growBuffer();
  44456. }
  44457. var el = this._freeEntries.pop();
  44458. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44459. if (el.offset === this._firstFree) {
  44460. if (this._freeEntries.length > 0) {
  44461. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  44462. }
  44463. else {
  44464. this._firstFree += this._stride;
  44465. }
  44466. }
  44467. return el;
  44468. };
  44469. /**
  44470. * Free the element corresponding to the given element info
  44471. * @param elInfo the element that describe the allocated element
  44472. */
  44473. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  44474. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  44475. this._freeEntries.push(elInfo);
  44476. };
  44477. /**
  44478. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  44479. * 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().
  44480. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  44481. */
  44482. DynamicFloatArray.prototype.pack = function () {
  44483. // no free slot? no need to pack
  44484. if (this._freeEntries.length === 0) {
  44485. return this.buffer;
  44486. }
  44487. // If the buffer is already packed the last used will always be lower than the first free
  44488. // 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.
  44489. if (this._lastUsed < this._firstFree) {
  44490. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  44491. return elementsBuffer_1;
  44492. }
  44493. var s = this._stride;
  44494. // 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
  44495. var lastFree = new DynamicFloatArrayElementInfo();
  44496. lastFree.offset = this.totalElementCount * s;
  44497. this._freeEntries.push(lastFree);
  44498. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  44499. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44500. var firstFreeSlotOffset = sortedFree[0].offset;
  44501. var freeZoneSize = 1;
  44502. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  44503. var prevOffset = sortedFree[0].offset;
  44504. for (var i = 1; i < sortedFree.length; i++) {
  44505. // 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
  44506. if (firstFreeSlotOffset >= occupiedZoneSize) {
  44507. break;
  44508. }
  44509. var curFree = sortedFree[i];
  44510. var curOffset = curFree.offset;
  44511. // Compute the distance between this offset and the previous
  44512. var distance = curOffset - prevOffset;
  44513. // If the distance is the stride size, they are adjacent, it good, move to the next
  44514. if (distance === s) {
  44515. // Free zone is one element bigger
  44516. ++freeZoneSize;
  44517. // as we're about to iterate to the next, the cur becomes the previous...
  44518. prevOffset = curOffset;
  44519. continue;
  44520. }
  44521. // Distance is bigger, which means there's x element between the previous free and this one
  44522. var usedRange = (distance / s) - 1;
  44523. // Two cases the free zone is smaller than the data to move or bigger
  44524. // Copy what can fit in the free zone
  44525. var curMoveOffset = curOffset - s;
  44526. var copyCount = Math.min(freeZoneSize, usedRange);
  44527. for (var j = 0; j < copyCount; j++) {
  44528. var freeI = firstFreeSlotOffset / s;
  44529. var curI = curMoveOffset / s;
  44530. var moveEl = sortedAll[curI];
  44531. this._moveElement(moveEl, firstFreeSlotOffset);
  44532. var replacedEl = sortedAll[freeI];
  44533. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  44534. replacedEl.offset = curMoveOffset;
  44535. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  44536. sortedAll[freeI] = moveEl;
  44537. sortedAll[curI] = replacedEl;
  44538. curMoveOffset -= s;
  44539. firstFreeSlotOffset += s;
  44540. }
  44541. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  44542. if (freeZoneSize <= usedRange) {
  44543. firstFreeSlotOffset = curMoveOffset + s;
  44544. freeZoneSize = 1 + copyCount;
  44545. }
  44546. else {
  44547. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  44548. }
  44549. // as we're about to iterate to the next, the cur becomes the previous...
  44550. prevOffset = curOffset;
  44551. }
  44552. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  44553. this._lastUsed = firstFreeSlotOffset - s;
  44554. this._firstFree = firstFreeSlotOffset;
  44555. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  44556. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  44557. this._allEntries = sortedAll;
  44558. return elementsBuffer;
  44559. };
  44560. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  44561. for (var i = 0; i < this._stride; i++) {
  44562. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  44563. }
  44564. element.offset = destOffset;
  44565. };
  44566. DynamicFloatArray.prototype._growBuffer = function () {
  44567. // Allocate the new buffer with 50% more entries, copy the content of the current one
  44568. var newElCount = Math.floor(this.totalElementCount * 1.5);
  44569. var newBuffer = new Float32Array(newElCount * this._stride);
  44570. newBuffer.set(this.buffer);
  44571. var curCount = this.totalElementCount;
  44572. var addedCount = newElCount - this.totalElementCount;
  44573. for (var i = 0; i < addedCount; i++) {
  44574. var element = new DynamicFloatArrayElementInfo();
  44575. element.offset = (curCount + i) * this.stride;
  44576. this._allEntries.push(element);
  44577. this._freeEntries[addedCount - i - 1] = element;
  44578. }
  44579. this._firstFree = curCount * this.stride;
  44580. this.buffer = newBuffer;
  44581. };
  44582. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  44583. /**
  44584. * Get the total count of entries that can fit in the current buffer
  44585. * @returns the elements count
  44586. */
  44587. get: function () {
  44588. return this._allEntries.length;
  44589. },
  44590. enumerable: true,
  44591. configurable: true
  44592. });
  44593. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  44594. /**
  44595. * Get the count of free entries that can still be allocated without resizing the buffer
  44596. * @returns the free elements count
  44597. */
  44598. get: function () {
  44599. return this._freeEntries.length;
  44600. },
  44601. enumerable: true,
  44602. configurable: true
  44603. });
  44604. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  44605. /**
  44606. * Get the count of allocated elements
  44607. * @returns the allocated elements count
  44608. */
  44609. get: function () {
  44610. return this._allEntries.length - this._freeEntries.length;
  44611. },
  44612. enumerable: true,
  44613. configurable: true
  44614. });
  44615. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  44616. /**
  44617. * Return the size of one element in float
  44618. * @returns the size in float
  44619. */
  44620. get: function () {
  44621. return this._stride;
  44622. },
  44623. enumerable: true,
  44624. configurable: true
  44625. });
  44626. DynamicFloatArray.prototype.sort = function () {
  44627. var _this = this;
  44628. if (!this.compareValueOffset) {
  44629. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  44630. }
  44631. var count = this.usedElementCount;
  44632. // Do we have to (re)create the sort table?
  44633. if (!this._sortTable || this._sortTable.length < count) {
  44634. // 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...
  44635. var newCount = Math.min(this.totalElementCount, count * 2);
  44636. this._sortTable = new Array(newCount);
  44637. }
  44638. if (!this._sortedTable || this._sortedTable.length !== count) {
  44639. this._sortedTable = new Array(count);
  44640. }
  44641. // Because, you know...
  44642. this.pack();
  44643. //let stride = this.stride;
  44644. //for (let i = 0; i < count; i++) {
  44645. // let si = this._sortTable[i];
  44646. // if (!si) {
  44647. // si = new SortInfo();
  44648. // this._sortTable[i] = si;
  44649. // }
  44650. // si.entry = this._allEntries[i];
  44651. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  44652. // si.swapedOffset = null;
  44653. // this._sortedTable[i] = si;
  44654. //}
  44655. var curOffset = 0;
  44656. var stride = this.stride;
  44657. for (var i = 0; i < count; i++, curOffset += stride) {
  44658. var si = this._sortTable[i];
  44659. if (!si) {
  44660. si = new SortInfo();
  44661. this._sortTable[i] = si;
  44662. }
  44663. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  44664. si.offset = curOffset;
  44665. si.swapedOffset = null;
  44666. this._sortedTable[i] = si;
  44667. }
  44668. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  44669. if (this.sortingAscending) {
  44670. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  44671. }
  44672. else {
  44673. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  44674. }
  44675. var swapElements = function (src, dst) {
  44676. for (var i = 0; i < stride; i++) {
  44677. var tps = _this.buffer[dst + i];
  44678. _this.buffer[dst + i] = _this.buffer[src + i];
  44679. _this.buffer[src + i] = tps;
  44680. }
  44681. };
  44682. // 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:
  44683. // 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),
  44684. // and I still want something with a good algorithm complexity.
  44685. // 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,
  44686. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  44687. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  44688. // 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
  44689. // until we find a SortInfo object without a swapedOffset which means we got the right location
  44690. // 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
  44691. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  44692. for (var i = 0; i < count; i++) {
  44693. // Get the element to move
  44694. var sourceSI = this._sortedTable[i];
  44695. var destSI = this._sortTable[i];
  44696. var sourceOff = sourceSI.offset;
  44697. // If the source changed location, find the new one
  44698. if (sourceSI.swapedOffset) {
  44699. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  44700. var curSI = sourceSI;
  44701. while (curSI.swapedOffset) {
  44702. curSI = this._sortTable[curSI.swapedOffset / stride];
  44703. }
  44704. // Finally get the right location
  44705. sourceOff = curSI.offset;
  44706. }
  44707. // Tag the element being replaced with its new location
  44708. destSI.swapedOffset = sourceOff;
  44709. // Swap elements (only if needed)
  44710. if (sourceOff !== destSI.offset) {
  44711. swapElements(sourceOff, destSI.offset);
  44712. }
  44713. // Update the offset in the corresponding DFAE
  44714. //sourceSI.entry.offset = destSI.entry.offset;
  44715. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  44716. }
  44717. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44718. return true;
  44719. };
  44720. return DynamicFloatArray;
  44721. }());
  44722. BABYLON.DynamicFloatArray = DynamicFloatArray;
  44723. var SortInfo = (function () {
  44724. function SortInfo() {
  44725. this.compareData = this.offset = this.swapedOffset = null;
  44726. }
  44727. return SortInfo;
  44728. }());
  44729. })(BABYLON || (BABYLON = {}));
  44730. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  44731. var BABYLON;
  44732. (function (BABYLON) {
  44733. var MapTexture = (function (_super) {
  44734. __extends(MapTexture, _super);
  44735. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  44736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44737. if (useMipMap === void 0) { useMipMap = false; }
  44738. if (margin === void 0) { margin = 0; }
  44739. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  44740. _this.name = name;
  44741. _this._size = size;
  44742. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44743. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44744. // Create the rectPackMap that will allocate portion of the texture
  44745. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  44746. // Create the texture that will store the content
  44747. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  44748. return _this;
  44749. }
  44750. /**
  44751. * Allocate a rectangle of a given size in the texture map
  44752. * @param size the size of the rectangle to allocation
  44753. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  44754. */
  44755. MapTexture.prototype.allocateRect = function (size) {
  44756. return this._rectPackingMap.addRect(size);
  44757. };
  44758. /**
  44759. * Free a given rectangle from the texture map
  44760. * @param rectInfo the instance corresponding to the rect to free.
  44761. */
  44762. MapTexture.prototype.freeRect = function (rectInfo) {
  44763. if (rectInfo) {
  44764. rectInfo.freeContent();
  44765. }
  44766. };
  44767. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  44768. /**
  44769. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  44770. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  44771. * @returns {}
  44772. */
  44773. get: function () {
  44774. return this._rectPackingMap.freeSpace;
  44775. },
  44776. enumerable: true,
  44777. configurable: true
  44778. });
  44779. /**
  44780. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  44781. * 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.
  44782. * Don't forget to call unbindTexture when you're done rendering
  44783. * @param rect the zone to render to
  44784. * @param clear true to clear the portion's color/depth data
  44785. */
  44786. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  44787. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  44788. };
  44789. /**
  44790. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  44791. * 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.
  44792. * Don't forget to call unbindTexture when you're done rendering
  44793. * @param pos the position into the texture
  44794. * @param size the portion to fit the clip space to
  44795. * @param clear true to clear the portion's color/depth data
  44796. */
  44797. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  44798. var engine = this.getScene().getEngine();
  44799. engine.bindFramebuffer(this._texture);
  44800. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  44801. if (clear) {
  44802. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  44803. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  44804. }
  44805. };
  44806. /**
  44807. * Unbind the texture map from the rendering engine.
  44808. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  44809. * @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.
  44810. */
  44811. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  44812. // Dump ?
  44813. if (dumpForDebug) {
  44814. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  44815. }
  44816. var engine = this.getScene().getEngine();
  44817. if (this._replacedViewport) {
  44818. engine.setViewport(this._replacedViewport);
  44819. this._replacedViewport = null;
  44820. }
  44821. engine.unBindFramebuffer(this._texture);
  44822. };
  44823. Object.defineProperty(MapTexture.prototype, "canRescale", {
  44824. get: function () {
  44825. return false;
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  44831. // Anyway, there's not much point to use this method for this kind of texture I guess
  44832. MapTexture.prototype.clone = function () {
  44833. return null;
  44834. };
  44835. return MapTexture;
  44836. }(BABYLON.Texture));
  44837. BABYLON.MapTexture = MapTexture;
  44838. })(BABYLON || (BABYLON = {}));
  44839. //# sourceMappingURL=babylon.mapTexture.js.map
  44840. var BABYLON;
  44841. (function (BABYLON) {
  44842. var ShaderMaterial = (function (_super) {
  44843. __extends(ShaderMaterial, _super);
  44844. function ShaderMaterial(name, scene, shaderPath, options) {
  44845. var _this = _super.call(this, name, scene) || this;
  44846. _this._textures = {};
  44847. _this._textureArrays = {};
  44848. _this._floats = {};
  44849. _this._floatsArrays = {};
  44850. _this._colors3 = {};
  44851. _this._colors4 = {};
  44852. _this._vectors2 = {};
  44853. _this._vectors3 = {};
  44854. _this._vectors4 = {};
  44855. _this._matrices = {};
  44856. _this._matrices3x3 = {};
  44857. _this._matrices2x2 = {};
  44858. _this._vectors3Arrays = {};
  44859. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44860. _this._shaderPath = shaderPath;
  44861. options.needAlphaBlending = options.needAlphaBlending || false;
  44862. options.needAlphaTesting = options.needAlphaTesting || false;
  44863. options.attributes = options.attributes || ["position", "normal", "uv"];
  44864. options.uniforms = options.uniforms || ["worldViewProjection"];
  44865. options.samplers = options.samplers || [];
  44866. options.defines = options.defines || [];
  44867. _this._options = options;
  44868. return _this;
  44869. }
  44870. ShaderMaterial.prototype.getClassName = function () {
  44871. return "ShaderMaterial";
  44872. };
  44873. ShaderMaterial.prototype.needAlphaBlending = function () {
  44874. return this._options.needAlphaBlending;
  44875. };
  44876. ShaderMaterial.prototype.needAlphaTesting = function () {
  44877. return this._options.needAlphaTesting;
  44878. };
  44879. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44880. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44881. this._options.uniforms.push(uniformName);
  44882. }
  44883. };
  44884. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44885. if (this._options.samplers.indexOf(name) === -1) {
  44886. this._options.samplers.push(name);
  44887. }
  44888. this._textures[name] = texture;
  44889. return this;
  44890. };
  44891. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44892. if (this._options.samplers.indexOf(name) === -1) {
  44893. this._options.samplers.push(name);
  44894. }
  44895. this._checkUniform(name);
  44896. this._textureArrays[name] = textures;
  44897. return this;
  44898. };
  44899. ShaderMaterial.prototype.setFloat = function (name, value) {
  44900. this._checkUniform(name);
  44901. this._floats[name] = value;
  44902. return this;
  44903. };
  44904. ShaderMaterial.prototype.setFloats = function (name, value) {
  44905. this._checkUniform(name);
  44906. this._floatsArrays[name] = value;
  44907. return this;
  44908. };
  44909. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44910. this._checkUniform(name);
  44911. this._colors3[name] = value;
  44912. return this;
  44913. };
  44914. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44915. this._checkUniform(name);
  44916. this._colors4[name] = value;
  44917. return this;
  44918. };
  44919. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44920. this._checkUniform(name);
  44921. this._vectors2[name] = value;
  44922. return this;
  44923. };
  44924. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44925. this._checkUniform(name);
  44926. this._vectors3[name] = value;
  44927. return this;
  44928. };
  44929. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44930. this._checkUniform(name);
  44931. this._vectors4[name] = value;
  44932. return this;
  44933. };
  44934. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44935. this._checkUniform(name);
  44936. this._matrices[name] = value;
  44937. return this;
  44938. };
  44939. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44940. this._checkUniform(name);
  44941. this._matrices3x3[name] = value;
  44942. return this;
  44943. };
  44944. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  44945. this._checkUniform(name);
  44946. this._matrices2x2[name] = value;
  44947. return this;
  44948. };
  44949. ShaderMaterial.prototype.setArray3 = function (name, value) {
  44950. this._checkUniform(name);
  44951. this._vectors3Arrays[name] = value;
  44952. return this;
  44953. };
  44954. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44955. if (!mesh) {
  44956. return true;
  44957. }
  44958. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  44959. return false;
  44960. }
  44961. return false;
  44962. };
  44963. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  44964. var scene = this.getScene();
  44965. var engine = scene.getEngine();
  44966. if (!this.checkReadyOnEveryCall) {
  44967. if (this._renderId === scene.getRenderId()) {
  44968. if (this._checkCache(scene, mesh, useInstances)) {
  44969. return true;
  44970. }
  44971. }
  44972. }
  44973. // Instances
  44974. var defines = [];
  44975. var fallbacks = new BABYLON.EffectFallbacks();
  44976. if (useInstances) {
  44977. defines.push("#define INSTANCES");
  44978. }
  44979. for (var index = 0; index < this._options.defines.length; index++) {
  44980. defines.push(this._options.defines[index]);
  44981. }
  44982. // Bones
  44983. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  44984. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44985. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44986. fallbacks.addCPUSkinningFallback(0, mesh);
  44987. }
  44988. // Textures
  44989. for (var name in this._textures) {
  44990. if (!this._textures[name].isReady()) {
  44991. return false;
  44992. }
  44993. }
  44994. // Alpha test
  44995. if (engine.getAlphaTesting()) {
  44996. defines.push("#define ALPHATEST");
  44997. }
  44998. var previousEffect = this._effect;
  44999. var join = defines.join("\n");
  45000. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  45001. if (!this._effect.isReady()) {
  45002. return false;
  45003. }
  45004. if (previousEffect !== this._effect) {
  45005. scene.resetCachedMaterial();
  45006. }
  45007. this._renderId = scene.getRenderId();
  45008. return true;
  45009. };
  45010. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45011. var scene = this.getScene();
  45012. if (this._options.uniforms.indexOf("world") !== -1) {
  45013. this._effect.setMatrix("world", world);
  45014. }
  45015. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45016. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45017. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45018. }
  45019. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45020. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45021. }
  45022. };
  45023. ShaderMaterial.prototype.bind = function (world, mesh) {
  45024. // Std values
  45025. this.bindOnlyWorldMatrix(world);
  45026. if (this.getScene().getCachedMaterial() !== this) {
  45027. if (this._options.uniforms.indexOf("view") !== -1) {
  45028. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45029. }
  45030. if (this._options.uniforms.indexOf("projection") !== -1) {
  45031. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45032. }
  45033. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45034. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45035. }
  45036. // Bones
  45037. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45038. var name;
  45039. // Texture
  45040. for (name in this._textures) {
  45041. this._effect.setTexture(name, this._textures[name]);
  45042. }
  45043. // Texture arrays
  45044. for (name in this._textureArrays) {
  45045. this._effect.setTextureArray(name, this._textureArrays[name]);
  45046. }
  45047. // Float
  45048. for (name in this._floats) {
  45049. this._effect.setFloat(name, this._floats[name]);
  45050. }
  45051. // Float s
  45052. for (name in this._floatsArrays) {
  45053. this._effect.setArray(name, this._floatsArrays[name]);
  45054. }
  45055. // Color3
  45056. for (name in this._colors3) {
  45057. this._effect.setColor3(name, this._colors3[name]);
  45058. }
  45059. // Color4
  45060. for (name in this._colors4) {
  45061. var color = this._colors4[name];
  45062. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45063. }
  45064. // Vector2
  45065. for (name in this._vectors2) {
  45066. this._effect.setVector2(name, this._vectors2[name]);
  45067. }
  45068. // Vector3
  45069. for (name in this._vectors3) {
  45070. this._effect.setVector3(name, this._vectors3[name]);
  45071. }
  45072. // Vector4
  45073. for (name in this._vectors4) {
  45074. this._effect.setVector4(name, this._vectors4[name]);
  45075. }
  45076. // Matrix
  45077. for (name in this._matrices) {
  45078. this._effect.setMatrix(name, this._matrices[name]);
  45079. }
  45080. // Matrix 3x3
  45081. for (name in this._matrices3x3) {
  45082. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45083. }
  45084. // Matrix 2x2
  45085. for (name in this._matrices2x2) {
  45086. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45087. }
  45088. // Vector3Array
  45089. for (name in this._vectors3Arrays) {
  45090. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45091. }
  45092. }
  45093. _super.prototype.bind.call(this, world, mesh);
  45094. };
  45095. ShaderMaterial.prototype.clone = function (name) {
  45096. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45097. return newShaderMaterial;
  45098. };
  45099. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45100. if (forceDisposeTextures) {
  45101. var name;
  45102. for (name in this._textures) {
  45103. this._textures[name].dispose();
  45104. }
  45105. for (name in this._textureArrays) {
  45106. var array = this._textureArrays[name];
  45107. for (var index = 0; index < array.length; index++) {
  45108. array[index].dispose();
  45109. }
  45110. }
  45111. }
  45112. this._textures = {};
  45113. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45114. };
  45115. ShaderMaterial.prototype.serialize = function () {
  45116. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45117. serializationObject.customType = "BABYLON.ShaderMaterial";
  45118. serializationObject.options = this._options;
  45119. serializationObject.shaderPath = this._shaderPath;
  45120. var name;
  45121. // Texture
  45122. serializationObject.textures = {};
  45123. for (name in this._textures) {
  45124. serializationObject.textures[name] = this._textures[name].serialize();
  45125. }
  45126. // Texture arrays
  45127. serializationObject.textureArrays = {};
  45128. for (name in this._textureArrays) {
  45129. serializationObject.textureArrays[name] = [];
  45130. var array = this._textureArrays[name];
  45131. for (var index = 0; index < array.length; index++) {
  45132. serializationObject.textureArrays[name].push(array[index].serialize());
  45133. }
  45134. }
  45135. // Float
  45136. serializationObject.floats = {};
  45137. for (name in this._floats) {
  45138. serializationObject.floats[name] = this._floats[name];
  45139. }
  45140. // Float s
  45141. serializationObject.floatArrays = {};
  45142. for (name in this._floatsArrays) {
  45143. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45144. }
  45145. // Color3
  45146. serializationObject.colors3 = {};
  45147. for (name in this._colors3) {
  45148. serializationObject.colors3[name] = this._colors3[name].asArray();
  45149. }
  45150. // Color4
  45151. serializationObject.colors4 = {};
  45152. for (name in this._colors4) {
  45153. serializationObject.colors4[name] = this._colors4[name].asArray();
  45154. }
  45155. // Vector2
  45156. serializationObject.vectors2 = {};
  45157. for (name in this._vectors2) {
  45158. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45159. }
  45160. // Vector3
  45161. serializationObject.vectors3 = {};
  45162. for (name in this._vectors3) {
  45163. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45164. }
  45165. // Vector4
  45166. serializationObject.vectors4 = {};
  45167. for (name in this._vectors4) {
  45168. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45169. }
  45170. // Matrix
  45171. serializationObject.matrices = {};
  45172. for (name in this._matrices) {
  45173. serializationObject.matrices[name] = this._matrices[name].asArray();
  45174. }
  45175. // Matrix 3x3
  45176. serializationObject.matrices3x3 = {};
  45177. for (name in this._matrices3x3) {
  45178. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45179. }
  45180. // Matrix 2x2
  45181. serializationObject.matrices2x2 = {};
  45182. for (name in this._matrices2x2) {
  45183. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45184. }
  45185. // Vector3Array
  45186. serializationObject.vectors3Arrays = {};
  45187. for (name in this._vectors3Arrays) {
  45188. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45189. }
  45190. return serializationObject;
  45191. };
  45192. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45193. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45194. var name;
  45195. // Texture
  45196. for (name in source.textures) {
  45197. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45198. }
  45199. // Texture arrays
  45200. for (name in source.textureArrays) {
  45201. var array = source.textureArrays[name];
  45202. var textureArray = new Array();
  45203. for (var index = 0; index < array.length; index++) {
  45204. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45205. }
  45206. material.setTextureArray(name, textureArray);
  45207. }
  45208. // Float
  45209. for (name in source.floats) {
  45210. material.setFloat(name, source.floats[name]);
  45211. }
  45212. // Float s
  45213. for (name in source.floatsArrays) {
  45214. material.setFloats(name, source.floatsArrays[name]);
  45215. }
  45216. // Color3
  45217. for (name in source.colors3) {
  45218. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45219. }
  45220. // Color4
  45221. for (name in source.colors4) {
  45222. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45223. }
  45224. // Vector2
  45225. for (name in source.vectors2) {
  45226. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45227. }
  45228. // Vector3
  45229. for (name in source.vectors3) {
  45230. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45231. }
  45232. // Vector4
  45233. for (name in source.vectors4) {
  45234. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45235. }
  45236. // Matrix
  45237. for (name in source.matrices) {
  45238. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45239. }
  45240. // Matrix 3x3
  45241. for (name in source.matrices3x3) {
  45242. material.setMatrix3x3(name, source.matrices3x3[name]);
  45243. }
  45244. // Matrix 2x2
  45245. for (name in source.matrices2x2) {
  45246. material.setMatrix2x2(name, source.matrices2x2[name]);
  45247. }
  45248. // Vector3Array
  45249. for (name in source.vectors3Arrays) {
  45250. material.setArray3(name, source.vectors3Arrays[name]);
  45251. }
  45252. return material;
  45253. };
  45254. return ShaderMaterial;
  45255. }(BABYLON.Material));
  45256. BABYLON.ShaderMaterial = ShaderMaterial;
  45257. })(BABYLON || (BABYLON = {}));
  45258. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45259. var BABYLON;
  45260. (function (BABYLON) {
  45261. var Internals;
  45262. (function (Internals) {
  45263. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  45264. // All values and structures referenced from:
  45265. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  45266. var DDS_MAGIC = 0x20534444;
  45267. 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;
  45268. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  45269. 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;
  45270. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  45271. function FourCCToInt32(value) {
  45272. return value.charCodeAt(0) +
  45273. (value.charCodeAt(1) << 8) +
  45274. (value.charCodeAt(2) << 16) +
  45275. (value.charCodeAt(3) << 24);
  45276. }
  45277. function Int32ToFourCC(value) {
  45278. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  45279. }
  45280. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  45281. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  45282. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  45283. var headerLengthInt = 31; // The header length in 32 bit ints
  45284. // Offsets into the header array
  45285. var off_magic = 0;
  45286. var off_size = 1;
  45287. var off_flags = 2;
  45288. var off_height = 3;
  45289. var off_width = 4;
  45290. var off_mipmapCount = 7;
  45291. var off_pfFlags = 20;
  45292. var off_pfFourCC = 21;
  45293. var off_RGBbpp = 22;
  45294. var off_RMask = 23;
  45295. var off_GMask = 24;
  45296. var off_BMask = 25;
  45297. var off_AMask = 26;
  45298. var off_caps1 = 27;
  45299. var off_caps2 = 28;
  45300. ;
  45301. var DDSTools = (function () {
  45302. function DDSTools() {
  45303. }
  45304. DDSTools.GetDDSInfo = function (arrayBuffer) {
  45305. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  45306. var mipmapCount = 1;
  45307. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  45308. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45309. }
  45310. return {
  45311. width: header[off_width],
  45312. height: header[off_height],
  45313. mipmapCount: mipmapCount,
  45314. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  45315. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  45316. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  45317. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  45318. };
  45319. };
  45320. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45321. var byteArray = new Uint8Array(dataLength);
  45322. var srcData = new Uint8Array(arrayBuffer);
  45323. var index = 0;
  45324. for (var y = height - 1; y >= 0; y--) {
  45325. for (var x = 0; x < width; x++) {
  45326. var srcPos = dataOffset + (x + y * width) * 4;
  45327. byteArray[index + 2] = srcData[srcPos];
  45328. byteArray[index + 1] = srcData[srcPos + 1];
  45329. byteArray[index] = srcData[srcPos + 2];
  45330. byteArray[index + 3] = srcData[srcPos + 3];
  45331. index += 4;
  45332. }
  45333. }
  45334. return byteArray;
  45335. };
  45336. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45337. var byteArray = new Uint8Array(dataLength);
  45338. var srcData = new Uint8Array(arrayBuffer);
  45339. var index = 0;
  45340. for (var y = height - 1; y >= 0; y--) {
  45341. for (var x = 0; x < width; x++) {
  45342. var srcPos = dataOffset + (x + y * width) * 3;
  45343. byteArray[index + 2] = srcData[srcPos];
  45344. byteArray[index + 1] = srcData[srcPos + 1];
  45345. byteArray[index] = srcData[srcPos + 2];
  45346. index += 3;
  45347. }
  45348. }
  45349. return byteArray;
  45350. };
  45351. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45352. var byteArray = new Uint8Array(dataLength);
  45353. var srcData = new Uint8Array(arrayBuffer);
  45354. var index = 0;
  45355. for (var y = height - 1; y >= 0; y--) {
  45356. for (var x = 0; x < width; x++) {
  45357. var srcPos = dataOffset + (x + y * width);
  45358. byteArray[index] = srcData[srcPos];
  45359. index++;
  45360. }
  45361. }
  45362. return byteArray;
  45363. };
  45364. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  45365. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  45366. if (header[off_magic] != DDS_MAGIC) {
  45367. BABYLON.Tools.Error("Invalid magic number in DDS header");
  45368. return;
  45369. }
  45370. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  45371. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  45372. return;
  45373. }
  45374. if (info.isFourCC) {
  45375. fourCC = header[off_pfFourCC];
  45376. switch (fourCC) {
  45377. case FOURCC_DXT1:
  45378. blockBytes = 8;
  45379. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45380. break;
  45381. case FOURCC_DXT3:
  45382. blockBytes = 16;
  45383. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45384. break;
  45385. case FOURCC_DXT5:
  45386. blockBytes = 16;
  45387. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45388. break;
  45389. default:
  45390. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  45391. return;
  45392. }
  45393. }
  45394. mipmapCount = 1;
  45395. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  45396. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45397. }
  45398. var bpp = header[off_RGBbpp];
  45399. for (var face = 0; face < faces; face++) {
  45400. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45401. width = header[off_width];
  45402. height = header[off_height];
  45403. dataOffset = header[off_size] + 4;
  45404. for (i = 0; i < mipmapCount; ++i) {
  45405. if (info.isRGB) {
  45406. if (bpp === 24) {
  45407. dataLength = width * height * 3;
  45408. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45409. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  45410. }
  45411. else {
  45412. dataLength = width * height * 4;
  45413. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45414. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  45415. }
  45416. }
  45417. else if (info.isLuminance) {
  45418. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  45419. var unpaddedRowSize = width;
  45420. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  45421. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  45422. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45423. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  45424. }
  45425. else {
  45426. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  45427. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  45428. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  45429. }
  45430. dataOffset += dataLength;
  45431. width *= 0.5;
  45432. height *= 0.5;
  45433. width = Math.max(1.0, width);
  45434. height = Math.max(1.0, height);
  45435. }
  45436. }
  45437. };
  45438. return DDSTools;
  45439. }());
  45440. Internals.DDSTools = DDSTools;
  45441. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45442. })(BABYLON || (BABYLON = {}));
  45443. //# sourceMappingURL=babylon.tools.dds.js.map
  45444. var BABYLON;
  45445. (function (BABYLON) {
  45446. var Internals;
  45447. (function (Internals) {
  45448. /**
  45449. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  45450. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  45451. */
  45452. var KhronosTextureContainer = (function () {
  45453. /**
  45454. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  45455. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  45456. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  45457. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  45458. */
  45459. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  45460. this.arrayBuffer = arrayBuffer;
  45461. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  45462. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  45463. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  45464. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  45465. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  45466. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  45467. BABYLON.Tools.Error("texture missing KTX identifier");
  45468. return;
  45469. }
  45470. // load the reset of the header in native 32 bit int
  45471. var header = new Int32Array(this.arrayBuffer, 12, 13);
  45472. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  45473. var oppositeEndianess = header[0] === 0x01020304;
  45474. // read all the header elements in order they exist in the file, without modification (sans endainness)
  45475. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  45476. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  45477. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  45478. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  45479. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  45480. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  45481. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  45482. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  45483. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  45484. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  45485. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  45486. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  45487. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  45488. if (this.glType !== 0) {
  45489. BABYLON.Tools.Error("only compressed formats currently supported");
  45490. return;
  45491. }
  45492. else {
  45493. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  45494. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  45495. }
  45496. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  45497. BABYLON.Tools.Error("only 2D textures currently supported");
  45498. return;
  45499. }
  45500. if (this.numberOfArrayElements !== 0) {
  45501. BABYLON.Tools.Error("texture arrays not currently supported");
  45502. return;
  45503. }
  45504. if (this.numberOfFaces !== facesExpected) {
  45505. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  45506. return;
  45507. }
  45508. // we now have a completely validated file, so could use existence of loadType as success
  45509. // would need to make this more elaborate & adjust checks above to support more than one load type
  45510. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  45511. }
  45512. // not as fast hardware based, but will probably never need to use
  45513. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  45514. return ((val & 0xFF) << 24)
  45515. | ((val & 0xFF00) << 8)
  45516. | ((val >> 8) & 0xFF00)
  45517. | ((val >> 24) & 0xFF);
  45518. };
  45519. /**
  45520. * It is assumed that the texture has already been created & is currently bound
  45521. */
  45522. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  45523. switch (this.loadType) {
  45524. case KhronosTextureContainer.COMPRESSED_2D:
  45525. this._upload2DCompressedLevels(gl, loadMipmaps);
  45526. break;
  45527. case KhronosTextureContainer.TEX_2D:
  45528. case KhronosTextureContainer.COMPRESSED_3D:
  45529. case KhronosTextureContainer.TEX_3D:
  45530. }
  45531. };
  45532. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  45533. // initialize width & height for level 1
  45534. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  45535. var width = this.pixelWidth;
  45536. var height = this.pixelHeight;
  45537. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  45538. for (var level = 0; level < mipmapCount; level++) {
  45539. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  45540. for (var face = 0; face < this.numberOfFaces; face++) {
  45541. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45542. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  45543. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  45544. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  45545. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  45546. }
  45547. width = Math.max(1.0, width * 0.5);
  45548. height = Math.max(1.0, height * 0.5);
  45549. }
  45550. };
  45551. return KhronosTextureContainer;
  45552. }());
  45553. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  45554. // load types
  45555. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  45556. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  45557. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  45558. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  45559. Internals.KhronosTextureContainer = KhronosTextureContainer;
  45560. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45561. })(BABYLON || (BABYLON = {}));
  45562. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  45563. var BABYLON;
  45564. (function (BABYLON) {
  45565. var CannonJSPlugin = (function () {
  45566. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  45567. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  45568. if (iterations === void 0) { iterations = 10; }
  45569. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  45570. this.name = "CannonJSPlugin";
  45571. this._physicsMaterials = [];
  45572. this._fixedTimeStep = 1 / 60;
  45573. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45574. this._currentCollisionGroup = 2;
  45575. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  45576. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  45577. this._tmpPosition = BABYLON.Vector3.Zero();
  45578. this._tmpQuaternion = new BABYLON.Quaternion();
  45579. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  45580. this._tmpDeltaRotation = new BABYLON.Quaternion();
  45581. this._tmpUnityRotation = new BABYLON.Quaternion();
  45582. if (!this.isSupported()) {
  45583. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  45584. return;
  45585. }
  45586. this.world = new CANNON.World();
  45587. this.world.broadphase = new CANNON.NaiveBroadphase();
  45588. this.world.solver.iterations = iterations;
  45589. }
  45590. CannonJSPlugin.prototype.setGravity = function (gravity) {
  45591. this.world.gravity.copy(gravity);
  45592. };
  45593. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  45594. this._fixedTimeStep = timeStep;
  45595. };
  45596. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  45597. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  45598. };
  45599. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45600. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45601. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45602. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45603. };
  45604. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45605. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45606. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45607. impostor.physicsBody.applyForce(impulse, worldPoint);
  45608. };
  45609. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45610. //parent-child relationship. Does this impostor has a parent impostor?
  45611. if (impostor.parent) {
  45612. if (impostor.physicsBody) {
  45613. this.removePhysicsBody(impostor);
  45614. //TODO is that needed?
  45615. impostor.forceUpdate();
  45616. }
  45617. return;
  45618. }
  45619. //should a new body be created for this impostor?
  45620. if (impostor.isBodyInitRequired()) {
  45621. var shape = this._createShape(impostor);
  45622. //unregister events, if body is being changed
  45623. var oldBody = impostor.physicsBody;
  45624. if (oldBody) {
  45625. this.removePhysicsBody(impostor);
  45626. }
  45627. //create the body and material
  45628. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  45629. var bodyCreationObject = {
  45630. mass: impostor.getParam("mass"),
  45631. material: material
  45632. };
  45633. // A simple extend, in case native options were used.
  45634. var nativeOptions = impostor.getParam("nativeOptions");
  45635. for (var key in nativeOptions) {
  45636. if (nativeOptions.hasOwnProperty(key)) {
  45637. bodyCreationObject[key] = nativeOptions[key];
  45638. }
  45639. }
  45640. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  45641. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  45642. this.world.addEventListener("preStep", impostor.beforeStep);
  45643. this.world.addEventListener("postStep", impostor.afterStep);
  45644. impostor.physicsBody.addShape(shape);
  45645. this.world.add(impostor.physicsBody);
  45646. //try to keep the body moving in the right direction by taking old properties.
  45647. //Should be tested!
  45648. if (oldBody) {
  45649. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  45650. impostor.physicsBody[param].copy(oldBody[param]);
  45651. });
  45652. }
  45653. this._processChildMeshes(impostor);
  45654. }
  45655. //now update the body's transformation
  45656. this._updatePhysicsBodyTransformation(impostor);
  45657. };
  45658. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  45659. var _this = this;
  45660. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  45661. if (meshChildren.length) {
  45662. var processMesh = function (localPosition, mesh) {
  45663. var childImpostor = mesh.getPhysicsImpostor();
  45664. if (childImpostor) {
  45665. var parent = childImpostor.parent;
  45666. if (parent !== mainImpostor) {
  45667. var localPosition = mesh.position;
  45668. if (childImpostor.physicsBody) {
  45669. _this.removePhysicsBody(childImpostor);
  45670. childImpostor.physicsBody = null;
  45671. }
  45672. childImpostor.parent = mainImpostor;
  45673. childImpostor.resetUpdateFlags();
  45674. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  45675. //Add the mass of the children.
  45676. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  45677. }
  45678. }
  45679. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  45680. };
  45681. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  45682. }
  45683. };
  45684. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45685. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  45686. this.world.removeEventListener("preStep", impostor.beforeStep);
  45687. this.world.removeEventListener("postStep", impostor.afterStep);
  45688. this.world.remove(impostor.physicsBody);
  45689. };
  45690. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45691. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45692. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45693. if (!mainBody || !connectedBody) {
  45694. return;
  45695. }
  45696. var constraint;
  45697. var jointData = impostorJoint.joint.jointData;
  45698. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45699. var constraintData = {
  45700. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  45701. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  45702. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  45703. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  45704. maxForce: jointData.nativeParams.maxForce,
  45705. collideConnected: !!jointData.collision
  45706. };
  45707. switch (impostorJoint.joint.type) {
  45708. case BABYLON.PhysicsJoint.HingeJoint:
  45709. case BABYLON.PhysicsJoint.Hinge2Joint:
  45710. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  45711. break;
  45712. case BABYLON.PhysicsJoint.DistanceJoint:
  45713. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  45714. break;
  45715. case BABYLON.PhysicsJoint.SpringJoint:
  45716. var springData = jointData;
  45717. constraint = new CANNON.Spring(mainBody, connectedBody, {
  45718. restLength: springData.length,
  45719. stiffness: springData.stiffness,
  45720. damping: springData.damping,
  45721. localAnchorA: constraintData.pivotA,
  45722. localAnchorB: constraintData.pivotB
  45723. });
  45724. break;
  45725. case BABYLON.PhysicsJoint.LockJoint:
  45726. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45727. break;
  45728. case BABYLON.PhysicsJoint.PointToPointJoint:
  45729. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45730. default:
  45731. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45732. break;
  45733. }
  45734. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45735. constraint.collideConnected = !!jointData.collision;
  45736. impostorJoint.joint.physicsJoint = constraint;
  45737. //don't add spring as constraint, as it is not one.
  45738. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45739. this.world.addConstraint(constraint);
  45740. }
  45741. else {
  45742. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45743. constraint.applyForce();
  45744. });
  45745. }
  45746. };
  45747. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45748. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45749. };
  45750. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45751. var index;
  45752. var mat;
  45753. for (index = 0; index < this._physicsMaterials.length; index++) {
  45754. mat = this._physicsMaterials[index];
  45755. if (mat.friction === friction && mat.restitution === restitution) {
  45756. return mat;
  45757. }
  45758. }
  45759. var currentMat = new CANNON.Material(name);
  45760. currentMat.friction = friction;
  45761. currentMat.restitution = restitution;
  45762. this._physicsMaterials.push(currentMat);
  45763. return currentMat;
  45764. };
  45765. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45766. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45767. };
  45768. CannonJSPlugin.prototype._createShape = function (impostor) {
  45769. var object = impostor.object;
  45770. var returnValue;
  45771. var extendSize = impostor.getObjectExtendSize();
  45772. switch (impostor.type) {
  45773. case BABYLON.PhysicsImpostor.SphereImpostor:
  45774. var radiusX = extendSize.x;
  45775. var radiusY = extendSize.y;
  45776. var radiusZ = extendSize.z;
  45777. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  45778. break;
  45779. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  45780. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45781. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  45782. break;
  45783. case BABYLON.PhysicsImpostor.BoxImpostor:
  45784. var box = extendSize.scale(0.5);
  45785. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  45786. break;
  45787. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45788. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  45789. returnValue = new CANNON.Plane();
  45790. break;
  45791. case BABYLON.PhysicsImpostor.MeshImpostor:
  45792. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  45793. var rawFaces = object.getIndices ? object.getIndices() : [];
  45794. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  45795. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  45796. break;
  45797. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  45798. returnValue = this._createHeightmap(object);
  45799. break;
  45800. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45801. returnValue = new CANNON.Particle();
  45802. break;
  45803. }
  45804. return returnValue;
  45805. };
  45806. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  45807. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45808. var matrix = [];
  45809. //For now pointDepth will not be used and will be automatically calculated.
  45810. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  45811. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  45812. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  45813. var elementSize = dim * 2 / arraySize;
  45814. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  45815. for (var i = 0; i < pos.length; i = i + 3) {
  45816. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  45817. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  45818. var y = pos[i + 1] + minY;
  45819. if (!matrix[x]) {
  45820. matrix[x] = [];
  45821. }
  45822. if (!matrix[x][z]) {
  45823. matrix[x][z] = y;
  45824. }
  45825. matrix[x][z] = Math.max(y, matrix[x][z]);
  45826. }
  45827. for (var x = 0; x <= arraySize; ++x) {
  45828. if (!matrix[x]) {
  45829. var loc = 1;
  45830. while (!matrix[(x + loc) % arraySize]) {
  45831. loc++;
  45832. }
  45833. matrix[x] = matrix[(x + loc) % arraySize].slice();
  45834. }
  45835. for (var z = 0; z <= arraySize; ++z) {
  45836. if (!matrix[x][z]) {
  45837. var loc = 1;
  45838. var newValue;
  45839. while (newValue === undefined) {
  45840. newValue = matrix[x][(z + loc++) % arraySize];
  45841. }
  45842. matrix[x][z] = newValue;
  45843. }
  45844. }
  45845. }
  45846. var shape = new CANNON.Heightfield(matrix, {
  45847. elementSize: elementSize
  45848. });
  45849. //For future reference, needed for body transformation
  45850. shape.minY = minY;
  45851. return shape;
  45852. };
  45853. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  45854. var object = impostor.object;
  45855. //make sure it is updated...
  45856. object.computeWorldMatrix && object.computeWorldMatrix(true);
  45857. // The delta between the mesh position and the mesh bounding box center
  45858. var center = impostor.getObjectCenter();
  45859. var extendSize = impostor.getObjectExtendSize();
  45860. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  45861. this._tmpPosition.copyFrom(center);
  45862. var quaternion = object.rotationQuaternion;
  45863. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  45864. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  45865. //-90 DEG in X, precalculated
  45866. quaternion = quaternion.multiply(this._minus90X);
  45867. //Invert! (Precalculated, 90 deg in X)
  45868. //No need to clone. this will never change.
  45869. impostor.setDeltaRotation(this._plus90X);
  45870. }
  45871. //If it is a heightfield, if should be centered.
  45872. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  45873. var mesh = object;
  45874. //calculate the correct body position:
  45875. var rotationQuaternion = mesh.rotationQuaternion;
  45876. mesh.rotationQuaternion = this._tmpUnityRotation;
  45877. mesh.computeWorldMatrix(true);
  45878. //get original center with no rotation
  45879. var c = center.clone();
  45880. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  45881. //rotation is back
  45882. mesh.rotationQuaternion = rotationQuaternion;
  45883. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  45884. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  45885. mesh.setPivotMatrix(p);
  45886. mesh.computeWorldMatrix(true);
  45887. //calculate the translation
  45888. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  45889. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  45890. //add it inverted to the delta
  45891. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  45892. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  45893. mesh.setPivotMatrix(oldPivot);
  45894. mesh.computeWorldMatrix(true);
  45895. }
  45896. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  45897. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  45898. this._tmpPosition.copyFrom(object.position);
  45899. }
  45900. impostor.setDeltaPosition(this._tmpDeltaPosition);
  45901. //Now update the impostor object
  45902. impostor.physicsBody.position.copy(this._tmpPosition);
  45903. impostor.physicsBody.quaternion.copy(quaternion);
  45904. };
  45905. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45906. impostor.object.position.copyFrom(impostor.physicsBody.position);
  45907. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  45908. };
  45909. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  45910. impostor.physicsBody.position.copy(newPosition);
  45911. impostor.physicsBody.quaternion.copy(newRotation);
  45912. };
  45913. CannonJSPlugin.prototype.isSupported = function () {
  45914. return window.CANNON !== undefined;
  45915. };
  45916. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  45917. impostor.physicsBody.velocity.copy(velocity);
  45918. };
  45919. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  45920. impostor.physicsBody.angularVelocity.copy(velocity);
  45921. };
  45922. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  45923. var v = impostor.physicsBody.velocity;
  45924. if (!v)
  45925. return null;
  45926. return new BABYLON.Vector3(v.x, v.y, v.z);
  45927. };
  45928. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  45929. var v = impostor.physicsBody.angularVelocity;
  45930. if (!v)
  45931. return null;
  45932. return new BABYLON.Vector3(v.x, v.y, v.z);
  45933. };
  45934. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  45935. impostor.physicsBody.mass = mass;
  45936. impostor.physicsBody.updateMassProperties();
  45937. };
  45938. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  45939. impostor.physicsBody.sleep();
  45940. };
  45941. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  45942. impostor.physicsBody.wakeUp();
  45943. };
  45944. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  45945. joint.physicsJoint.distance = maxDistance;
  45946. };
  45947. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  45948. if (!motorIndex) {
  45949. joint.physicsJoint.enableMotor();
  45950. }
  45951. };
  45952. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  45953. if (!motorIndex) {
  45954. joint.physicsJoint.disableMotor();
  45955. }
  45956. };
  45957. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  45958. if (!motorIndex) {
  45959. joint.physicsJoint.enableMotor();
  45960. joint.physicsJoint.setMotorSpeed(speed);
  45961. if (maxForce) {
  45962. this.setLimit(joint, maxForce);
  45963. }
  45964. }
  45965. };
  45966. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  45967. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  45968. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  45969. };
  45970. CannonJSPlugin.prototype.dispose = function () {
  45971. //nothing to do, actually.
  45972. };
  45973. return CannonJSPlugin;
  45974. }());
  45975. BABYLON.CannonJSPlugin = CannonJSPlugin;
  45976. })(BABYLON || (BABYLON = {}));
  45977. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  45978. var BABYLON;
  45979. (function (BABYLON) {
  45980. var OimoJSPlugin = (function () {
  45981. function OimoJSPlugin(iterations) {
  45982. this.name = "OimoJSPlugin";
  45983. this._tmpImpostorsArray = [];
  45984. this._tmpPositionVector = BABYLON.Vector3.Zero();
  45985. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  45986. this.world.worldscale(1);
  45987. this.world.clear();
  45988. //making sure no stats are calculated
  45989. this.world.isNoStat = true;
  45990. }
  45991. OimoJSPlugin.prototype.setGravity = function (gravity) {
  45992. this.world.gravity.copy(gravity);
  45993. };
  45994. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  45995. this.world.timeStep = timeStep;
  45996. };
  45997. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  45998. var _this = this;
  45999. impostors.forEach(function (impostor) {
  46000. impostor.beforeStep();
  46001. });
  46002. this.world.step();
  46003. impostors.forEach(function (impostor) {
  46004. impostor.afterStep();
  46005. //update the ordered impostors array
  46006. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  46007. });
  46008. //check for collisions
  46009. var contact = this.world.contacts;
  46010. while (contact !== null) {
  46011. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  46012. contact = contact.next;
  46013. continue;
  46014. }
  46015. //is this body colliding with any other? get the impostor
  46016. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  46017. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  46018. if (!mainImpostor || !collidingImpostor) {
  46019. contact = contact.next;
  46020. continue;
  46021. }
  46022. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  46023. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  46024. contact = contact.next;
  46025. }
  46026. };
  46027. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46028. var mass = impostor.physicsBody.massInfo.mass;
  46029. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  46030. };
  46031. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46032. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  46033. this.applyImpulse(impostor, force, contactPoint);
  46034. };
  46035. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46036. var _this = this;
  46037. //parent-child relationship. Does this impostor has a parent impostor?
  46038. if (impostor.parent) {
  46039. if (impostor.physicsBody) {
  46040. this.removePhysicsBody(impostor);
  46041. //TODO is that needed?
  46042. impostor.forceUpdate();
  46043. }
  46044. return;
  46045. }
  46046. if (impostor.isBodyInitRequired()) {
  46047. var bodyConfig = {
  46048. name: impostor.uniqueId,
  46049. //Oimo must have mass, also for static objects.
  46050. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  46051. size: [],
  46052. type: [],
  46053. pos: [],
  46054. rot: [],
  46055. move: impostor.getParam("mass") !== 0,
  46056. //Supporting older versions of Oimo
  46057. world: this.world
  46058. };
  46059. var impostors = [impostor];
  46060. var addToArray = function (parent) {
  46061. if (!parent.getChildMeshes)
  46062. return;
  46063. parent.getChildMeshes().forEach(function (m) {
  46064. if (m.physicsImpostor) {
  46065. impostors.push(m.physicsImpostor);
  46066. m.physicsImpostor._init();
  46067. }
  46068. });
  46069. };
  46070. addToArray(impostor.object);
  46071. var checkWithEpsilon_1 = function (value) {
  46072. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  46073. };
  46074. impostors.forEach(function (i) {
  46075. //get the correct bounding box
  46076. var oldQuaternion = i.object.rotationQuaternion;
  46077. var rot = new OIMO.Euler().setFromQuaternion({
  46078. x: impostor.object.rotationQuaternion.x,
  46079. y: impostor.object.rotationQuaternion.y,
  46080. z: impostor.object.rotationQuaternion.z,
  46081. s: impostor.object.rotationQuaternion.w
  46082. });
  46083. var extendSize = i.getObjectExtendSize();
  46084. if (i === impostor) {
  46085. var center = impostor.getObjectCenter();
  46086. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  46087. //Can also use Array.prototype.push.apply
  46088. bodyConfig.pos.push(center.x);
  46089. bodyConfig.pos.push(center.y);
  46090. bodyConfig.pos.push(center.z);
  46091. //tmp solution
  46092. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  46093. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  46094. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  46095. }
  46096. else {
  46097. bodyConfig.pos.push(i.object.position.x);
  46098. bodyConfig.pos.push(i.object.position.y);
  46099. bodyConfig.pos.push(i.object.position.z);
  46100. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  46101. bodyConfig.rot.push(0);
  46102. bodyConfig.rot.push(0);
  46103. bodyConfig.rot.push(0);
  46104. }
  46105. // register mesh
  46106. switch (i.type) {
  46107. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46108. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  46109. case BABYLON.PhysicsImpostor.SphereImpostor:
  46110. var radiusX = extendSize.x;
  46111. var radiusY = extendSize.y;
  46112. var radiusZ = extendSize.z;
  46113. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  46114. bodyConfig.type.push('sphere');
  46115. //due to the way oimo works with compounds, add 3 times
  46116. bodyConfig.size.push(size);
  46117. bodyConfig.size.push(size);
  46118. bodyConfig.size.push(size);
  46119. break;
  46120. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46121. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  46122. var sizeY = checkWithEpsilon_1(extendSize.y);
  46123. bodyConfig.type.push('cylinder');
  46124. bodyConfig.size.push(sizeX);
  46125. bodyConfig.size.push(sizeY);
  46126. //due to the way oimo works with compounds, add one more value.
  46127. bodyConfig.size.push(sizeY);
  46128. break;
  46129. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46130. case BABYLON.PhysicsImpostor.BoxImpostor:
  46131. default:
  46132. var sizeX = checkWithEpsilon_1(extendSize.x);
  46133. var sizeY = checkWithEpsilon_1(extendSize.y);
  46134. var sizeZ = checkWithEpsilon_1(extendSize.z);
  46135. bodyConfig.type.push('box');
  46136. bodyConfig.size.push(sizeX);
  46137. bodyConfig.size.push(sizeY);
  46138. bodyConfig.size.push(sizeZ);
  46139. break;
  46140. }
  46141. //actually not needed, but hey...
  46142. i.object.rotationQuaternion = oldQuaternion;
  46143. });
  46144. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  46145. }
  46146. else {
  46147. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  46148. }
  46149. impostor.setDeltaPosition(this._tmpPositionVector);
  46150. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  46151. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  46152. };
  46153. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46154. //impostor.physicsBody.dispose();
  46155. //Same as : (older oimo versions)
  46156. this.world.removeRigidBody(impostor.physicsBody);
  46157. };
  46158. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46159. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46160. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46161. if (!mainBody || !connectedBody) {
  46162. return;
  46163. }
  46164. var jointData = impostorJoint.joint.jointData;
  46165. var options = jointData.nativeParams || {};
  46166. var type;
  46167. var nativeJointData = {
  46168. body1: mainBody,
  46169. body2: connectedBody,
  46170. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  46171. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  46172. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  46173. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  46174. min: options.min,
  46175. max: options.max,
  46176. collision: options.collision || jointData.collision,
  46177. spring: options.spring,
  46178. //supporting older version of Oimo
  46179. world: this.world
  46180. };
  46181. switch (impostorJoint.joint.type) {
  46182. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46183. type = "jointBall";
  46184. break;
  46185. case BABYLON.PhysicsJoint.SpringJoint:
  46186. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  46187. var springData = jointData;
  46188. nativeJointData.min = springData.length || nativeJointData.min;
  46189. //Max should also be set, just make sure it is at least min
  46190. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  46191. case BABYLON.PhysicsJoint.DistanceJoint:
  46192. type = "jointDistance";
  46193. nativeJointData.max = jointData.maxDistance;
  46194. break;
  46195. case BABYLON.PhysicsJoint.PrismaticJoint:
  46196. type = "jointPrisme";
  46197. break;
  46198. case BABYLON.PhysicsJoint.SliderJoint:
  46199. type = "jointSlide";
  46200. break;
  46201. case BABYLON.PhysicsJoint.WheelJoint:
  46202. type = "jointWheel";
  46203. break;
  46204. case BABYLON.PhysicsJoint.HingeJoint:
  46205. default:
  46206. type = "jointHinge";
  46207. break;
  46208. }
  46209. nativeJointData.type = type;
  46210. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  46211. };
  46212. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46213. //Bug in Oimo prevents us from disposing a joint in the playground
  46214. //joint.joint.physicsJoint.dispose();
  46215. //So we will bruteforce it!
  46216. try {
  46217. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  46218. }
  46219. catch (e) {
  46220. BABYLON.Tools.Warn(e);
  46221. }
  46222. };
  46223. OimoJSPlugin.prototype.isSupported = function () {
  46224. return OIMO !== undefined;
  46225. };
  46226. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46227. if (!impostor.physicsBody.sleeping) {
  46228. //TODO check that
  46229. if (impostor.physicsBody.shapes.next) {
  46230. var parentShape = this._getLastShape(impostor.physicsBody);
  46231. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  46232. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  46233. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  46234. }
  46235. else {
  46236. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  46237. }
  46238. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  46239. impostor.object.rotationQuaternion.normalize();
  46240. }
  46241. };
  46242. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46243. var body = impostor.physicsBody;
  46244. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  46245. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  46246. body.syncShapes();
  46247. body.awake();
  46248. };
  46249. OimoJSPlugin.prototype._getLastShape = function (body) {
  46250. var lastShape = body.shapes;
  46251. while (lastShape.next) {
  46252. lastShape = lastShape.next;
  46253. }
  46254. return lastShape;
  46255. };
  46256. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46257. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  46258. };
  46259. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46260. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  46261. };
  46262. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46263. var v = impostor.physicsBody.linearVelocity;
  46264. if (!v)
  46265. return null;
  46266. return new BABYLON.Vector3(v.x, v.y, v.z);
  46267. };
  46268. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46269. var v = impostor.physicsBody.angularVelocity;
  46270. if (!v)
  46271. return null;
  46272. return new BABYLON.Vector3(v.x, v.y, v.z);
  46273. };
  46274. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46275. var staticBody = mass === 0;
  46276. //this will actually set the body's density and not its mass.
  46277. //But this is how oimo treats the mass variable.
  46278. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  46279. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  46280. };
  46281. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  46282. impostor.physicsBody.sleep();
  46283. };
  46284. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  46285. impostor.physicsBody.awake();
  46286. };
  46287. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46288. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  46289. if (minDistance !== void 0) {
  46290. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  46291. }
  46292. };
  46293. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46294. //TODO separate rotational and transational motors.
  46295. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46296. if (motor) {
  46297. motor.setMotor(speed, maxForce);
  46298. }
  46299. };
  46300. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  46301. //TODO separate rotational and transational motors.
  46302. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46303. if (motor) {
  46304. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  46305. }
  46306. };
  46307. OimoJSPlugin.prototype.dispose = function () {
  46308. this.world.clear();
  46309. };
  46310. return OimoJSPlugin;
  46311. }());
  46312. BABYLON.OimoJSPlugin = OimoJSPlugin;
  46313. })(BABYLON || (BABYLON = {}));
  46314. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  46315. var BABYLON;
  46316. (function (BABYLON) {
  46317. var DisplayPassPostProcess = (function (_super) {
  46318. __extends(DisplayPassPostProcess, _super);
  46319. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46320. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  46321. }
  46322. return DisplayPassPostProcess;
  46323. }(BABYLON.PostProcess));
  46324. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  46325. })(BABYLON || (BABYLON = {}));
  46326. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  46327. var BABYLON;
  46328. (function (BABYLON) {
  46329. var SimplificationSettings = (function () {
  46330. function SimplificationSettings(quality, distance, optimizeMesh) {
  46331. this.quality = quality;
  46332. this.distance = distance;
  46333. this.optimizeMesh = optimizeMesh;
  46334. }
  46335. return SimplificationSettings;
  46336. }());
  46337. BABYLON.SimplificationSettings = SimplificationSettings;
  46338. var SimplificationQueue = (function () {
  46339. function SimplificationQueue() {
  46340. this.running = false;
  46341. this._simplificationArray = [];
  46342. }
  46343. SimplificationQueue.prototype.addTask = function (task) {
  46344. this._simplificationArray.push(task);
  46345. };
  46346. SimplificationQueue.prototype.executeNext = function () {
  46347. var task = this._simplificationArray.pop();
  46348. if (task) {
  46349. this.running = true;
  46350. this.runSimplification(task);
  46351. }
  46352. else {
  46353. this.running = false;
  46354. }
  46355. };
  46356. SimplificationQueue.prototype.runSimplification = function (task) {
  46357. var _this = this;
  46358. if (task.parallelProcessing) {
  46359. //parallel simplifier
  46360. task.settings.forEach(function (setting) {
  46361. var simplifier = _this.getSimplifier(task);
  46362. simplifier.simplify(setting, function (newMesh) {
  46363. task.mesh.addLODLevel(setting.distance, newMesh);
  46364. newMesh.isVisible = true;
  46365. //check if it is the last
  46366. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  46367. //all done, run the success callback.
  46368. task.successCallback();
  46369. }
  46370. _this.executeNext();
  46371. });
  46372. });
  46373. }
  46374. else {
  46375. //single simplifier.
  46376. var simplifier = this.getSimplifier(task);
  46377. var runDecimation = function (setting, callback) {
  46378. simplifier.simplify(setting, function (newMesh) {
  46379. task.mesh.addLODLevel(setting.distance, newMesh);
  46380. newMesh.isVisible = true;
  46381. //run the next quality level
  46382. callback();
  46383. });
  46384. };
  46385. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  46386. runDecimation(task.settings[loop.index], function () {
  46387. loop.executeNext();
  46388. });
  46389. }, function () {
  46390. //execution ended, run the success callback.
  46391. if (task.successCallback) {
  46392. task.successCallback();
  46393. }
  46394. _this.executeNext();
  46395. });
  46396. }
  46397. };
  46398. SimplificationQueue.prototype.getSimplifier = function (task) {
  46399. switch (task.simplificationType) {
  46400. case SimplificationType.QUADRATIC:
  46401. default:
  46402. return new QuadraticErrorSimplification(task.mesh);
  46403. }
  46404. };
  46405. return SimplificationQueue;
  46406. }());
  46407. BABYLON.SimplificationQueue = SimplificationQueue;
  46408. /**
  46409. * The implemented types of simplification.
  46410. * At the moment only Quadratic Error Decimation is implemented.
  46411. */
  46412. var SimplificationType;
  46413. (function (SimplificationType) {
  46414. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  46415. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  46416. var DecimationTriangle = (function () {
  46417. function DecimationTriangle(vertices) {
  46418. this.vertices = vertices;
  46419. this.error = new Array(4);
  46420. this.deleted = false;
  46421. this.isDirty = false;
  46422. this.deletePending = false;
  46423. this.borderFactor = 0;
  46424. }
  46425. return DecimationTriangle;
  46426. }());
  46427. BABYLON.DecimationTriangle = DecimationTriangle;
  46428. var DecimationVertex = (function () {
  46429. function DecimationVertex(position, id) {
  46430. this.position = position;
  46431. this.id = id;
  46432. this.isBorder = true;
  46433. this.q = new QuadraticMatrix();
  46434. this.triangleCount = 0;
  46435. this.triangleStart = 0;
  46436. this.originalOffsets = [];
  46437. }
  46438. DecimationVertex.prototype.updatePosition = function (newPosition) {
  46439. this.position.copyFrom(newPosition);
  46440. };
  46441. return DecimationVertex;
  46442. }());
  46443. BABYLON.DecimationVertex = DecimationVertex;
  46444. var QuadraticMatrix = (function () {
  46445. function QuadraticMatrix(data) {
  46446. this.data = new Array(10);
  46447. for (var i = 0; i < 10; ++i) {
  46448. if (data && data[i]) {
  46449. this.data[i] = data[i];
  46450. }
  46451. else {
  46452. this.data[i] = 0;
  46453. }
  46454. }
  46455. }
  46456. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  46457. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  46458. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  46459. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  46460. return det;
  46461. };
  46462. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  46463. for (var i = 0; i < 10; ++i) {
  46464. this.data[i] += matrix.data[i];
  46465. }
  46466. };
  46467. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  46468. for (var i = 0; i < 10; ++i) {
  46469. this.data[i] += data[i];
  46470. }
  46471. };
  46472. QuadraticMatrix.prototype.add = function (matrix) {
  46473. var m = new QuadraticMatrix();
  46474. for (var i = 0; i < 10; ++i) {
  46475. m.data[i] = this.data[i] + matrix.data[i];
  46476. }
  46477. return m;
  46478. };
  46479. QuadraticMatrix.FromData = function (a, b, c, d) {
  46480. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  46481. };
  46482. //returning an array to avoid garbage collection
  46483. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  46484. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  46485. };
  46486. return QuadraticMatrix;
  46487. }());
  46488. BABYLON.QuadraticMatrix = QuadraticMatrix;
  46489. var Reference = (function () {
  46490. function Reference(vertexId, triangleId) {
  46491. this.vertexId = vertexId;
  46492. this.triangleId = triangleId;
  46493. }
  46494. return Reference;
  46495. }());
  46496. BABYLON.Reference = Reference;
  46497. /**
  46498. * An implementation of the Quadratic Error simplification algorithm.
  46499. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  46500. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  46501. * @author RaananW
  46502. */
  46503. var QuadraticErrorSimplification = (function () {
  46504. function QuadraticErrorSimplification(_mesh) {
  46505. this._mesh = _mesh;
  46506. this.initialized = false;
  46507. this.syncIterations = 5000;
  46508. this.aggressiveness = 7;
  46509. this.decimationIterations = 100;
  46510. this.boundingBoxEpsilon = BABYLON.Epsilon;
  46511. }
  46512. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  46513. var _this = this;
  46514. this.initDecimatedMesh();
  46515. //iterating through the submeshes array, one after the other.
  46516. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  46517. _this.initWithMesh(loop.index, function () {
  46518. _this.runDecimation(settings, loop.index, function () {
  46519. loop.executeNext();
  46520. });
  46521. }, settings.optimizeMesh);
  46522. }, function () {
  46523. setTimeout(function () {
  46524. successCallback(_this._reconstructedMesh);
  46525. }, 0);
  46526. });
  46527. };
  46528. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  46529. var _this = this;
  46530. var gCount = 0;
  46531. triangle.vertices.forEach(function (vertex) {
  46532. var count = 0;
  46533. var vPos = vertex.position;
  46534. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  46535. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  46536. ++count;
  46537. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  46538. ++count;
  46539. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  46540. ++count;
  46541. if (count > 1) {
  46542. ++gCount;
  46543. }
  46544. ;
  46545. });
  46546. if (gCount > 1) {
  46547. console.log(triangle, gCount);
  46548. }
  46549. return gCount > 1;
  46550. };
  46551. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  46552. var _this = this;
  46553. var targetCount = ~~(this.triangles.length * settings.quality);
  46554. var deletedTriangles = 0;
  46555. var triangleCount = this.triangles.length;
  46556. var iterationFunction = function (iteration, callback) {
  46557. setTimeout(function () {
  46558. if (iteration % 5 === 0) {
  46559. _this.updateMesh(iteration === 0);
  46560. }
  46561. for (var i = 0; i < _this.triangles.length; ++i) {
  46562. _this.triangles[i].isDirty = false;
  46563. }
  46564. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  46565. var trianglesIterator = function (i) {
  46566. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  46567. var t = _this.triangles[tIdx];
  46568. if (!t)
  46569. return;
  46570. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  46571. return;
  46572. }
  46573. for (var j = 0; j < 3; ++j) {
  46574. if (t.error[j] < threshold) {
  46575. var deleted0 = [];
  46576. var deleted1 = [];
  46577. var v0 = t.vertices[j];
  46578. var v1 = t.vertices[(j + 1) % 3];
  46579. if (v0.isBorder || v1.isBorder)
  46580. continue;
  46581. var p = BABYLON.Vector3.Zero();
  46582. var n = BABYLON.Vector3.Zero();
  46583. var uv = BABYLON.Vector2.Zero();
  46584. var color = new BABYLON.Color4(0, 0, 0, 1);
  46585. _this.calculateError(v0, v1, p, n, uv, color);
  46586. var delTr = [];
  46587. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  46588. continue;
  46589. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  46590. continue;
  46591. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  46592. continue;
  46593. var uniqueArray = [];
  46594. delTr.forEach(function (deletedT) {
  46595. if (uniqueArray.indexOf(deletedT) === -1) {
  46596. deletedT.deletePending = true;
  46597. uniqueArray.push(deletedT);
  46598. }
  46599. });
  46600. if (uniqueArray.length % 2 !== 0) {
  46601. continue;
  46602. }
  46603. v0.q = v1.q.add(v0.q);
  46604. v0.updatePosition(p);
  46605. var tStart = _this.references.length;
  46606. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  46607. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  46608. var tCount = _this.references.length - tStart;
  46609. if (tCount <= v0.triangleCount) {
  46610. if (tCount) {
  46611. for (var c = 0; c < tCount; c++) {
  46612. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  46613. }
  46614. }
  46615. }
  46616. else {
  46617. v0.triangleStart = tStart;
  46618. }
  46619. v0.triangleCount = tCount;
  46620. break;
  46621. }
  46622. }
  46623. };
  46624. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  46625. }, 0);
  46626. };
  46627. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  46628. if (triangleCount - deletedTriangles <= targetCount)
  46629. loop.breakLoop();
  46630. else {
  46631. iterationFunction(loop.index, function () {
  46632. loop.executeNext();
  46633. });
  46634. }
  46635. }, function () {
  46636. setTimeout(function () {
  46637. //reconstruct this part of the mesh
  46638. _this.reconstructMesh(submeshIndex);
  46639. successCallback();
  46640. }, 0);
  46641. });
  46642. };
  46643. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  46644. var _this = this;
  46645. this.vertices = [];
  46646. this.triangles = [];
  46647. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46648. var indices = this._mesh.getIndices();
  46649. var submesh = this._mesh.subMeshes[submeshIndex];
  46650. var findInVertices = function (positionToSearch) {
  46651. if (optimizeMesh) {
  46652. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  46653. if (_this.vertices[ii].position.equals(positionToSearch)) {
  46654. return _this.vertices[ii];
  46655. }
  46656. }
  46657. }
  46658. return null;
  46659. };
  46660. var vertexReferences = [];
  46661. var vertexInit = function (i) {
  46662. var offset = i + submesh.verticesStart;
  46663. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  46664. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  46665. vertex.originalOffsets.push(offset);
  46666. if (vertex.id === _this.vertices.length) {
  46667. _this.vertices.push(vertex);
  46668. }
  46669. vertexReferences.push(vertex.id);
  46670. };
  46671. //var totalVertices = mesh.getTotalVertices();
  46672. var totalVertices = submesh.verticesCount;
  46673. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  46674. var indicesInit = function (i) {
  46675. var offset = (submesh.indexStart / 3) + i;
  46676. var pos = (offset * 3);
  46677. var i0 = indices[pos + 0];
  46678. var i1 = indices[pos + 1];
  46679. var i2 = indices[pos + 2];
  46680. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  46681. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  46682. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  46683. var triangle = new DecimationTriangle([v0, v1, v2]);
  46684. triangle.originalOffset = pos;
  46685. _this.triangles.push(triangle);
  46686. };
  46687. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  46688. _this.init(callback);
  46689. });
  46690. });
  46691. };
  46692. QuadraticErrorSimplification.prototype.init = function (callback) {
  46693. var _this = this;
  46694. var triangleInit1 = function (i) {
  46695. var t = _this.triangles[i];
  46696. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  46697. for (var j = 0; j < 3; j++) {
  46698. 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))));
  46699. }
  46700. };
  46701. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  46702. var triangleInit2 = function (i) {
  46703. var t = _this.triangles[i];
  46704. for (var j = 0; j < 3; ++j) {
  46705. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  46706. }
  46707. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46708. };
  46709. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  46710. _this.initialized = true;
  46711. callback();
  46712. });
  46713. });
  46714. };
  46715. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  46716. var newTriangles = [];
  46717. var i;
  46718. for (i = 0; i < this.vertices.length; ++i) {
  46719. this.vertices[i].triangleCount = 0;
  46720. }
  46721. var t;
  46722. var j;
  46723. for (i = 0; i < this.triangles.length; ++i) {
  46724. if (!this.triangles[i].deleted) {
  46725. t = this.triangles[i];
  46726. for (j = 0; j < 3; ++j) {
  46727. t.vertices[j].triangleCount = 1;
  46728. }
  46729. newTriangles.push(t);
  46730. }
  46731. }
  46732. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46733. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46734. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46735. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46736. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46737. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46738. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46739. var vertexCount = 0;
  46740. for (i = 0; i < this.vertices.length; ++i) {
  46741. var vertex = this.vertices[i];
  46742. vertex.id = vertexCount;
  46743. if (vertex.triangleCount) {
  46744. vertex.originalOffsets.forEach(function (originalOffset) {
  46745. newPositionData.push(vertex.position.x);
  46746. newPositionData.push(vertex.position.y);
  46747. newPositionData.push(vertex.position.z);
  46748. newNormalData.push(normalData[originalOffset * 3]);
  46749. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46750. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46751. if (uvs && uvs.length) {
  46752. newUVsData.push(uvs[(originalOffset * 2)]);
  46753. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46754. }
  46755. else if (colorsData && colorsData.length) {
  46756. newColorsData.push(colorsData[(originalOffset * 4)]);
  46757. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46758. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46759. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46760. }
  46761. ++vertexCount;
  46762. });
  46763. }
  46764. }
  46765. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46766. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46767. var submeshesArray = this._reconstructedMesh.subMeshes;
  46768. this._reconstructedMesh.subMeshes = [];
  46769. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46770. var originalIndices = this._mesh.getIndices();
  46771. for (i = 0; i < newTriangles.length; ++i) {
  46772. t = newTriangles[i]; //now get the new referencing point for each vertex
  46773. [0, 1, 2].forEach(function (idx) {
  46774. var id = originalIndices[t.originalOffset + idx];
  46775. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46776. if (offset < 0)
  46777. offset = 0;
  46778. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  46779. });
  46780. }
  46781. //overwriting the old vertex buffers and indices.
  46782. this._reconstructedMesh.setIndices(newIndicesArray);
  46783. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  46784. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  46785. if (newUVsData.length > 0)
  46786. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  46787. if (newColorsData.length > 0)
  46788. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  46789. //create submesh
  46790. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  46791. if (submeshIndex > 0) {
  46792. this._reconstructedMesh.subMeshes = [];
  46793. submeshesArray.forEach(function (submesh) {
  46794. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  46795. });
  46796. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  46797. }
  46798. };
  46799. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  46800. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  46801. this._reconstructedMesh.material = this._mesh.material;
  46802. this._reconstructedMesh.parent = this._mesh.parent;
  46803. this._reconstructedMesh.isVisible = false;
  46804. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  46805. };
  46806. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  46807. for (var i = 0; i < vertex1.triangleCount; ++i) {
  46808. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  46809. if (t.deleted)
  46810. continue;
  46811. var s = this.references[vertex1.triangleStart + i].vertexId;
  46812. var v1 = t.vertices[(s + 1) % 3];
  46813. var v2 = t.vertices[(s + 2) % 3];
  46814. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  46815. deletedArray[i] = true;
  46816. delTr.push(t);
  46817. continue;
  46818. }
  46819. var d1 = v1.position.subtract(point);
  46820. d1 = d1.normalize();
  46821. var d2 = v2.position.subtract(point);
  46822. d2 = d2.normalize();
  46823. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  46824. return true;
  46825. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  46826. deletedArray[i] = false;
  46827. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  46828. return true;
  46829. }
  46830. return false;
  46831. };
  46832. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  46833. var newDeleted = deletedTriangles;
  46834. for (var i = 0; i < vertex.triangleCount; ++i) {
  46835. var ref = this.references[vertex.triangleStart + i];
  46836. var t = this.triangles[ref.triangleId];
  46837. if (t.deleted)
  46838. continue;
  46839. if (deletedArray[i] && t.deletePending) {
  46840. t.deleted = true;
  46841. newDeleted++;
  46842. continue;
  46843. }
  46844. t.vertices[ref.vertexId] = origVertex;
  46845. t.isDirty = true;
  46846. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  46847. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  46848. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  46849. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46850. this.references.push(ref);
  46851. }
  46852. return newDeleted;
  46853. };
  46854. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  46855. for (var i = 0; i < this.vertices.length; ++i) {
  46856. var vCount = [];
  46857. var vId = [];
  46858. var v = this.vertices[i];
  46859. var j;
  46860. for (j = 0; j < v.triangleCount; ++j) {
  46861. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  46862. for (var ii = 0; ii < 3; ii++) {
  46863. var ofs = 0;
  46864. var vv = triangle.vertices[ii];
  46865. while (ofs < vCount.length) {
  46866. if (vId[ofs] === vv.id)
  46867. break;
  46868. ++ofs;
  46869. }
  46870. if (ofs === vCount.length) {
  46871. vCount.push(1);
  46872. vId.push(vv.id);
  46873. }
  46874. else {
  46875. vCount[ofs]++;
  46876. }
  46877. }
  46878. }
  46879. for (j = 0; j < vCount.length; ++j) {
  46880. if (vCount[j] === 1) {
  46881. this.vertices[vId[j]].isBorder = true;
  46882. }
  46883. else {
  46884. this.vertices[vId[j]].isBorder = false;
  46885. }
  46886. }
  46887. }
  46888. };
  46889. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  46890. if (identifyBorders === void 0) { identifyBorders = false; }
  46891. var i;
  46892. if (!identifyBorders) {
  46893. var newTrianglesVector = [];
  46894. for (i = 0; i < this.triangles.length; ++i) {
  46895. if (!this.triangles[i].deleted) {
  46896. newTrianglesVector.push(this.triangles[i]);
  46897. }
  46898. }
  46899. this.triangles = newTrianglesVector;
  46900. }
  46901. for (i = 0; i < this.vertices.length; ++i) {
  46902. this.vertices[i].triangleCount = 0;
  46903. this.vertices[i].triangleStart = 0;
  46904. }
  46905. var t;
  46906. var j;
  46907. var v;
  46908. for (i = 0; i < this.triangles.length; ++i) {
  46909. t = this.triangles[i];
  46910. for (j = 0; j < 3; ++j) {
  46911. v = t.vertices[j];
  46912. v.triangleCount++;
  46913. }
  46914. }
  46915. var tStart = 0;
  46916. for (i = 0; i < this.vertices.length; ++i) {
  46917. this.vertices[i].triangleStart = tStart;
  46918. tStart += this.vertices[i].triangleCount;
  46919. this.vertices[i].triangleCount = 0;
  46920. }
  46921. var newReferences = new Array(this.triangles.length * 3);
  46922. for (i = 0; i < this.triangles.length; ++i) {
  46923. t = this.triangles[i];
  46924. for (j = 0; j < 3; ++j) {
  46925. v = t.vertices[j];
  46926. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  46927. v.triangleCount++;
  46928. }
  46929. }
  46930. this.references = newReferences;
  46931. if (identifyBorders) {
  46932. this.identifyBorder();
  46933. }
  46934. };
  46935. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  46936. var x = point.x;
  46937. var y = point.y;
  46938. var z = point.z;
  46939. 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
  46940. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  46941. };
  46942. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  46943. var q = vertex1.q.add(vertex2.q);
  46944. var border = vertex1.isBorder && vertex2.isBorder;
  46945. var error = 0;
  46946. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  46947. if (qDet !== 0 && !border) {
  46948. if (!pointResult) {
  46949. pointResult = BABYLON.Vector3.Zero();
  46950. }
  46951. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  46952. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  46953. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  46954. error = this.vertexError(q, pointResult);
  46955. }
  46956. else {
  46957. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  46958. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  46959. var error1 = this.vertexError(q, vertex1.position);
  46960. var error2 = this.vertexError(q, vertex2.position);
  46961. var error3 = this.vertexError(q, p3);
  46962. error = Math.min(error1, error2, error3);
  46963. if (error === error1) {
  46964. if (pointResult) {
  46965. pointResult.copyFrom(vertex1.position);
  46966. }
  46967. }
  46968. else if (error === error2) {
  46969. if (pointResult) {
  46970. pointResult.copyFrom(vertex2.position);
  46971. }
  46972. }
  46973. else {
  46974. if (pointResult) {
  46975. pointResult.copyFrom(p3);
  46976. }
  46977. }
  46978. }
  46979. return error;
  46980. };
  46981. return QuadraticErrorSimplification;
  46982. }());
  46983. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  46984. })(BABYLON || (BABYLON = {}));
  46985. //# sourceMappingURL=babylon.meshSimplification.js.map
  46986. var BABYLON;
  46987. (function (BABYLON) {
  46988. var serializedGeometries = [];
  46989. var serializeGeometry = function (geometry, serializationGeometries) {
  46990. if (serializedGeometries[geometry.id]) {
  46991. return;
  46992. }
  46993. if (geometry.doNotSerialize) {
  46994. return;
  46995. }
  46996. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  46997. serializationGeometries.boxes.push(geometry.serialize());
  46998. }
  46999. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  47000. serializationGeometries.spheres.push(geometry.serialize());
  47001. }
  47002. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  47003. serializationGeometries.cylinders.push(geometry.serialize());
  47004. }
  47005. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  47006. serializationGeometries.toruses.push(geometry.serialize());
  47007. }
  47008. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  47009. serializationGeometries.grounds.push(geometry.serialize());
  47010. }
  47011. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  47012. serializationGeometries.planes.push(geometry.serialize());
  47013. }
  47014. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  47015. serializationGeometries.torusKnots.push(geometry.serialize());
  47016. }
  47017. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  47018. throw new Error("Unknown primitive type");
  47019. }
  47020. else {
  47021. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  47022. }
  47023. serializedGeometries[geometry.id] = true;
  47024. };
  47025. var serializeMesh = function (mesh, serializationScene) {
  47026. var serializationObject = {};
  47027. // Geometry
  47028. var geometry = mesh._geometry;
  47029. if (geometry) {
  47030. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  47031. // 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
  47032. serializeGeometry(geometry, serializationScene.geometries);
  47033. }
  47034. }
  47035. // Custom
  47036. if (mesh.serialize) {
  47037. mesh.serialize(serializationObject);
  47038. }
  47039. return serializationObject;
  47040. };
  47041. var finalizeSingleMesh = function (mesh, serializationObject) {
  47042. //only works if the mesh is already loaded
  47043. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47044. //serialize material
  47045. if (mesh.material) {
  47046. if (mesh.material instanceof BABYLON.StandardMaterial) {
  47047. serializationObject.materials = serializationObject.materials || [];
  47048. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47049. serializationObject.materials.push(mesh.material.serialize());
  47050. }
  47051. }
  47052. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  47053. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  47054. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47055. serializationObject.multiMaterials.push(mesh.material.serialize());
  47056. }
  47057. }
  47058. }
  47059. //serialize geometry
  47060. var geometry = mesh._geometry;
  47061. if (geometry) {
  47062. if (!serializationObject.geometries) {
  47063. serializationObject.geometries = {};
  47064. serializationObject.geometries.boxes = [];
  47065. serializationObject.geometries.spheres = [];
  47066. serializationObject.geometries.cylinders = [];
  47067. serializationObject.geometries.toruses = [];
  47068. serializationObject.geometries.grounds = [];
  47069. serializationObject.geometries.planes = [];
  47070. serializationObject.geometries.torusKnots = [];
  47071. serializationObject.geometries.vertexData = [];
  47072. }
  47073. serializeGeometry(geometry, serializationObject.geometries);
  47074. }
  47075. // Skeletons
  47076. if (mesh.skeleton) {
  47077. serializationObject.skeletons = serializationObject.skeletons || [];
  47078. serializationObject.skeletons.push(mesh.skeleton.serialize());
  47079. }
  47080. //serialize the actual mesh
  47081. serializationObject.meshes = serializationObject.meshes || [];
  47082. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47083. }
  47084. };
  47085. var SceneSerializer = (function () {
  47086. function SceneSerializer() {
  47087. }
  47088. SceneSerializer.ClearCache = function () {
  47089. serializedGeometries = [];
  47090. };
  47091. SceneSerializer.Serialize = function (scene) {
  47092. var serializationObject = {};
  47093. SceneSerializer.ClearCache();
  47094. // Scene
  47095. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  47096. serializationObject.autoClear = scene.autoClear;
  47097. serializationObject.clearColor = scene.clearColor.asArray();
  47098. serializationObject.ambientColor = scene.ambientColor.asArray();
  47099. serializationObject.gravity = scene.gravity.asArray();
  47100. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  47101. serializationObject.workerCollisions = scene.workerCollisions;
  47102. // Fog
  47103. if (scene.fogMode && scene.fogMode !== 0) {
  47104. serializationObject.fogMode = scene.fogMode;
  47105. serializationObject.fogColor = scene.fogColor.asArray();
  47106. serializationObject.fogStart = scene.fogStart;
  47107. serializationObject.fogEnd = scene.fogEnd;
  47108. serializationObject.fogDensity = scene.fogDensity;
  47109. }
  47110. //Physics
  47111. if (scene.isPhysicsEnabled()) {
  47112. serializationObject.physicsEnabled = true;
  47113. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  47114. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  47115. }
  47116. // Metadata
  47117. if (scene.metadata) {
  47118. serializationObject.metadata = scene.metadata;
  47119. }
  47120. // Lights
  47121. serializationObject.lights = [];
  47122. var index;
  47123. var light;
  47124. for (index = 0; index < scene.lights.length; index++) {
  47125. light = scene.lights[index];
  47126. if (!light.doNotSerialize) {
  47127. serializationObject.lights.push(light.serialize());
  47128. }
  47129. }
  47130. // Cameras
  47131. serializationObject.cameras = [];
  47132. for (index = 0; index < scene.cameras.length; index++) {
  47133. var camera = scene.cameras[index];
  47134. if (!camera.doNotSerialize) {
  47135. serializationObject.cameras.push(camera.serialize());
  47136. }
  47137. }
  47138. if (scene.activeCamera) {
  47139. serializationObject.activeCameraID = scene.activeCamera.id;
  47140. }
  47141. // Animations
  47142. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  47143. // Materials
  47144. serializationObject.materials = [];
  47145. serializationObject.multiMaterials = [];
  47146. var material;
  47147. for (index = 0; index < scene.materials.length; index++) {
  47148. material = scene.materials[index];
  47149. if (!material.doNotSerialize) {
  47150. serializationObject.materials.push(material.serialize());
  47151. }
  47152. }
  47153. // MultiMaterials
  47154. serializationObject.multiMaterials = [];
  47155. for (index = 0; index < scene.multiMaterials.length; index++) {
  47156. var multiMaterial = scene.multiMaterials[index];
  47157. serializationObject.multiMaterials.push(multiMaterial.serialize());
  47158. }
  47159. // Skeletons
  47160. serializationObject.skeletons = [];
  47161. for (index = 0; index < scene.skeletons.length; index++) {
  47162. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  47163. }
  47164. // Geometries
  47165. serializationObject.geometries = {};
  47166. serializationObject.geometries.boxes = [];
  47167. serializationObject.geometries.spheres = [];
  47168. serializationObject.geometries.cylinders = [];
  47169. serializationObject.geometries.toruses = [];
  47170. serializationObject.geometries.grounds = [];
  47171. serializationObject.geometries.planes = [];
  47172. serializationObject.geometries.torusKnots = [];
  47173. serializationObject.geometries.vertexData = [];
  47174. serializedGeometries = [];
  47175. var geometries = scene.getGeometries();
  47176. for (index = 0; index < geometries.length; index++) {
  47177. var geometry = geometries[index];
  47178. if (geometry.isReady()) {
  47179. serializeGeometry(geometry, serializationObject.geometries);
  47180. }
  47181. }
  47182. // Meshes
  47183. serializationObject.meshes = [];
  47184. for (index = 0; index < scene.meshes.length; index++) {
  47185. var abstractMesh = scene.meshes[index];
  47186. if (abstractMesh instanceof BABYLON.Mesh) {
  47187. var mesh = abstractMesh;
  47188. if (!mesh.doNotSerialize) {
  47189. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47190. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47191. }
  47192. }
  47193. }
  47194. }
  47195. // Particles Systems
  47196. serializationObject.particleSystems = [];
  47197. for (index = 0; index < scene.particleSystems.length; index++) {
  47198. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  47199. }
  47200. // Lens flares
  47201. serializationObject.lensFlareSystems = [];
  47202. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  47203. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  47204. }
  47205. // Shadows
  47206. serializationObject.shadowGenerators = [];
  47207. for (index = 0; index < scene.lights.length; index++) {
  47208. light = scene.lights[index];
  47209. var shadowGenerator = light.getShadowGenerator();
  47210. // Only support serialization for official generator so far.
  47211. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  47212. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  47213. }
  47214. }
  47215. // Action Manager
  47216. if (scene.actionManager) {
  47217. serializationObject.actions = scene.actionManager.serialize("scene");
  47218. }
  47219. // Audio
  47220. serializationObject.sounds = [];
  47221. for (index = 0; index < scene.soundTracks.length; index++) {
  47222. var soundtrack = scene.soundTracks[index];
  47223. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  47224. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  47225. }
  47226. }
  47227. return serializationObject;
  47228. };
  47229. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  47230. if (withParents === void 0) { withParents = false; }
  47231. if (withChildren === void 0) { withChildren = false; }
  47232. var serializationObject = {};
  47233. SceneSerializer.ClearCache();
  47234. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  47235. if (withParents || withChildren) {
  47236. //deliberate for loop! not for each, appended should be processed as well.
  47237. for (var i = 0; i < toSerialize.length; ++i) {
  47238. if (withChildren) {
  47239. toSerialize[i].getDescendants().forEach(function (node) {
  47240. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  47241. toSerialize.push(node);
  47242. }
  47243. });
  47244. }
  47245. //make sure the array doesn't contain the object already
  47246. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  47247. toSerialize.push(toSerialize[i].parent);
  47248. }
  47249. }
  47250. }
  47251. toSerialize.forEach(function (mesh) {
  47252. finalizeSingleMesh(mesh, serializationObject);
  47253. });
  47254. return serializationObject;
  47255. };
  47256. return SceneSerializer;
  47257. }());
  47258. BABYLON.SceneSerializer = SceneSerializer;
  47259. })(BABYLON || (BABYLON = {}));
  47260. //# sourceMappingURL=babylon.sceneSerializer.js.map
  47261. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  47262. // Huge respect for a such great lib.
  47263. // Earcut license:
  47264. // Copyright (c) 2016, Mapbox
  47265. //
  47266. // Permission to use, copy, modify, and/or distribute this software for any purpose
  47267. // with or without fee is hereby granted, provided that the above copyright notice
  47268. // and this permission notice appear in all copies.
  47269. //
  47270. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  47271. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  47272. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  47273. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  47274. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  47275. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  47276. // THIS SOFTWARE.
  47277. var Earcut;
  47278. (function (Earcut) {
  47279. /**
  47280. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  47281. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  47282. * @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).
  47283. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  47284. */
  47285. function earcut(data, holeIndices, dim) {
  47286. dim = dim || 2;
  47287. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  47288. if (!outerNode)
  47289. return triangles;
  47290. var minX, minY, maxX, maxY, x, y, size;
  47291. if (hasHoles)
  47292. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  47293. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  47294. if (data.length > 80 * dim) {
  47295. minX = maxX = data[0];
  47296. minY = maxY = data[1];
  47297. for (var i = dim; i < outerLen; i += dim) {
  47298. x = data[i];
  47299. y = data[i + 1];
  47300. if (x < minX)
  47301. minX = x;
  47302. if (y < minY)
  47303. minY = y;
  47304. if (x > maxX)
  47305. maxX = x;
  47306. if (y > maxY)
  47307. maxY = y;
  47308. }
  47309. // minX, minY and size are later used to transform coords into integers for z-order calculation
  47310. size = Math.max(maxX - minX, maxY - minY);
  47311. }
  47312. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  47313. return triangles;
  47314. }
  47315. Earcut.earcut = earcut;
  47316. // create a circular doubly linked list from polygon points in the specified winding order
  47317. function linkedList(data, start, end, dim, clockwise) {
  47318. var i, last;
  47319. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  47320. for (i = start; i < end; i += dim)
  47321. last = insertNode(i, data[i], data[i + 1], last);
  47322. }
  47323. else {
  47324. for (i = end - dim; i >= start; i -= dim)
  47325. last = insertNode(i, data[i], data[i + 1], last);
  47326. }
  47327. if (last && equals(last, last.next)) {
  47328. removeNode(last);
  47329. last = last.next;
  47330. }
  47331. return last;
  47332. }
  47333. // eliminate colinear or duplicate points
  47334. function filterPoints(start, end) {
  47335. if (!start)
  47336. return start;
  47337. if (!end)
  47338. end = start;
  47339. var p = start, again;
  47340. do {
  47341. again = false;
  47342. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  47343. removeNode(p);
  47344. p = end = p.prev;
  47345. if (p === p.next)
  47346. return null;
  47347. again = true;
  47348. }
  47349. else {
  47350. p = p.next;
  47351. }
  47352. } while (again || p !== end);
  47353. return end;
  47354. }
  47355. // main ear slicing loop which triangulates a polygon (given as a linked list)
  47356. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  47357. if (!ear)
  47358. return;
  47359. // interlink polygon nodes in z-order
  47360. if (!pass && size)
  47361. indexCurve(ear, minX, minY, size);
  47362. var stop = ear, prev, next;
  47363. // iterate through ears, slicing them one by one
  47364. while (ear.prev !== ear.next) {
  47365. prev = ear.prev;
  47366. next = ear.next;
  47367. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  47368. // cut off the triangle
  47369. triangles.push(prev.i / dim);
  47370. triangles.push(ear.i / dim);
  47371. triangles.push(next.i / dim);
  47372. removeNode(ear);
  47373. // skipping the next vertice leads to less sliver triangles
  47374. ear = next.next;
  47375. stop = next.next;
  47376. continue;
  47377. }
  47378. ear = next;
  47379. // if we looped through the whole remaining polygon and can't find any more ears
  47380. if (ear === stop) {
  47381. // try filtering points and slicing again
  47382. if (!pass) {
  47383. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  47384. }
  47385. else if (pass === 1) {
  47386. ear = cureLocalIntersections(ear, triangles, dim);
  47387. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  47388. }
  47389. else if (pass === 2) {
  47390. splitEarcut(ear, triangles, dim, minX, minY, size);
  47391. }
  47392. break;
  47393. }
  47394. }
  47395. }
  47396. // check whether a polygon node forms a valid ear with adjacent nodes
  47397. function isEar(ear) {
  47398. var a = ear.prev, b = ear, c = ear.next;
  47399. if (area(a, b, c) >= 0)
  47400. return false; // reflex, can't be an ear
  47401. // now make sure we don't have other points inside the potential ear
  47402. var p = ear.next.next;
  47403. while (p !== ear.prev) {
  47404. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47405. area(p.prev, p, p.next) >= 0)
  47406. return false;
  47407. p = p.next;
  47408. }
  47409. return true;
  47410. }
  47411. function isEarHashed(ear, minX, minY, size) {
  47412. var a = ear.prev, b = ear, c = ear.next;
  47413. if (area(a, b, c) >= 0)
  47414. return false; // reflex, can't be an ear
  47415. // triangle bbox; min & max are calculated like this for speed
  47416. 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);
  47417. // z-order range for the current triangle bbox;
  47418. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  47419. // first look for points inside the triangle in increasing z-order
  47420. var p = ear.nextZ;
  47421. while (p && p.z <= maxZ) {
  47422. if (p !== ear.prev &&
  47423. p !== ear.next &&
  47424. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47425. area(p.prev, p, p.next) >= 0)
  47426. return false;
  47427. p = p.nextZ;
  47428. }
  47429. // then look for points in decreasing z-order
  47430. p = ear.prevZ;
  47431. while (p && p.z >= minZ) {
  47432. if (p !== ear.prev &&
  47433. p !== ear.next &&
  47434. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47435. area(p.prev, p, p.next) >= 0)
  47436. return false;
  47437. p = p.prevZ;
  47438. }
  47439. return true;
  47440. }
  47441. // go through all polygon nodes and cure small local self-intersections
  47442. function cureLocalIntersections(start, triangles, dim) {
  47443. var p = start;
  47444. do {
  47445. var a = p.prev, b = p.next.next;
  47446. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  47447. triangles.push(a.i / dim);
  47448. triangles.push(p.i / dim);
  47449. triangles.push(b.i / dim);
  47450. // remove two nodes involved
  47451. removeNode(p);
  47452. removeNode(p.next);
  47453. p = start = b;
  47454. }
  47455. p = p.next;
  47456. } while (p !== start);
  47457. return p;
  47458. }
  47459. // try splitting polygon into two and triangulate them independently
  47460. function splitEarcut(start, triangles, dim, minX, minY, size) {
  47461. // look for a valid diagonal that divides the polygon into two
  47462. var a = start;
  47463. do {
  47464. var b = a.next.next;
  47465. while (b !== a.prev) {
  47466. if (a.i !== b.i && isValidDiagonal(a, b)) {
  47467. // split the polygon in two by the diagonal
  47468. var c = splitPolygon(a, b);
  47469. // filter colinear points around the cuts
  47470. a = filterPoints(a, a.next);
  47471. c = filterPoints(c, c.next);
  47472. // run earcut on each half
  47473. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  47474. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  47475. return;
  47476. }
  47477. b = b.next;
  47478. }
  47479. a = a.next;
  47480. } while (a !== start);
  47481. }
  47482. // link every hole into the outer loop, producing a single-ring polygon without holes
  47483. function eliminateHoles(data, holeIndices, outerNode, dim) {
  47484. var queue = [], i, len, start, end, list;
  47485. for (i = 0, len = holeIndices.length; i < len; i++) {
  47486. start = holeIndices[i] * dim;
  47487. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47488. list = linkedList(data, start, end, dim, false);
  47489. if (list === list.next)
  47490. list.steiner = true;
  47491. queue.push(getLeftmost(list));
  47492. }
  47493. queue.sort(compareX);
  47494. // process holes from left to right
  47495. for (i = 0; i < queue.length; i++) {
  47496. eliminateHole(queue[i], outerNode);
  47497. outerNode = filterPoints(outerNode, outerNode.next);
  47498. }
  47499. return outerNode;
  47500. }
  47501. function compareX(a, b) {
  47502. return a.x - b.x;
  47503. }
  47504. // find a bridge between vertices that connects hole with an outer ring and and link it
  47505. function eliminateHole(hole, outerNode) {
  47506. outerNode = findHoleBridge(hole, outerNode);
  47507. if (outerNode) {
  47508. var b = splitPolygon(outerNode, hole);
  47509. filterPoints(b, b.next);
  47510. }
  47511. }
  47512. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  47513. function findHoleBridge(hole, outerNode) {
  47514. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  47515. // find a segment intersected by a ray from the hole's leftmost point to the left;
  47516. // segment's endpoint with lesser x will be potential connection point
  47517. do {
  47518. if (hy <= p.y && hy >= p.next.y) {
  47519. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  47520. if (x <= hx && x > qx) {
  47521. qx = x;
  47522. if (x === hx) {
  47523. if (hy === p.y)
  47524. return p;
  47525. if (hy === p.next.y)
  47526. return p.next;
  47527. }
  47528. m = p.x < p.next.x ? p : p.next;
  47529. }
  47530. }
  47531. p = p.next;
  47532. } while (p !== outerNode);
  47533. if (!m)
  47534. return null;
  47535. if (hx === qx)
  47536. return m.prev; // hole touches outer segment; pick lower endpoint
  47537. // look for points inside the triangle of hole point, segment intersection and endpoint;
  47538. // if there are no points found, we have a valid connection;
  47539. // otherwise choose the point of the minimum angle with the ray as connection point
  47540. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  47541. p = m.next;
  47542. while (p !== stop) {
  47543. if (hx >= p.x &&
  47544. p.x >= mx &&
  47545. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  47546. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  47547. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  47548. m = p;
  47549. tanMin = tan;
  47550. }
  47551. }
  47552. p = p.next;
  47553. }
  47554. return m;
  47555. }
  47556. // interlink polygon nodes in z-order
  47557. function indexCurve(start, minX, minY, size) {
  47558. var p = start;
  47559. do {
  47560. if (p.z === null)
  47561. p.z = zOrder(p.x, p.y, minX, minY, size);
  47562. p.prevZ = p.prev;
  47563. p.nextZ = p.next;
  47564. p = p.next;
  47565. } while (p !== start);
  47566. p.prevZ.nextZ = null;
  47567. p.prevZ = null;
  47568. sortLinked(p);
  47569. }
  47570. // Simon Tatham's linked list merge sort algorithm
  47571. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  47572. function sortLinked(list) {
  47573. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  47574. do {
  47575. p = list;
  47576. list = null;
  47577. tail = null;
  47578. numMerges = 0;
  47579. while (p) {
  47580. numMerges++;
  47581. q = p;
  47582. pSize = 0;
  47583. for (i = 0; i < inSize; i++) {
  47584. pSize++;
  47585. q = q.nextZ;
  47586. if (!q)
  47587. break;
  47588. }
  47589. qSize = inSize;
  47590. while (pSize > 0 || (qSize > 0 && q)) {
  47591. if (pSize === 0) {
  47592. e = q;
  47593. q = q.nextZ;
  47594. qSize--;
  47595. }
  47596. else if (qSize === 0 || !q) {
  47597. e = p;
  47598. p = p.nextZ;
  47599. pSize--;
  47600. }
  47601. else if (p.z <= q.z) {
  47602. e = p;
  47603. p = p.nextZ;
  47604. pSize--;
  47605. }
  47606. else {
  47607. e = q;
  47608. q = q.nextZ;
  47609. qSize--;
  47610. }
  47611. if (tail)
  47612. tail.nextZ = e;
  47613. else
  47614. list = e;
  47615. e.prevZ = tail;
  47616. tail = e;
  47617. }
  47618. p = q;
  47619. }
  47620. tail.nextZ = null;
  47621. inSize *= 2;
  47622. } while (numMerges > 1);
  47623. return list;
  47624. }
  47625. // z-order of a point given coords and size of the data bounding box
  47626. function zOrder(x, y, minX, minY, size) {
  47627. // coords are transformed into non-negative 15-bit integer range
  47628. x = 32767 * (x - minX) / size;
  47629. y = 32767 * (y - minY) / size;
  47630. x = (x | (x << 8)) & 0x00FF00FF;
  47631. x = (x | (x << 4)) & 0x0F0F0F0F;
  47632. x = (x | (x << 2)) & 0x33333333;
  47633. x = (x | (x << 1)) & 0x55555555;
  47634. y = (y | (y << 8)) & 0x00FF00FF;
  47635. y = (y | (y << 4)) & 0x0F0F0F0F;
  47636. y = (y | (y << 2)) & 0x33333333;
  47637. y = (y | (y << 1)) & 0x55555555;
  47638. return x | (y << 1);
  47639. }
  47640. // find the leftmost node of a polygon ring
  47641. function getLeftmost(start) {
  47642. var p = start, leftmost = start;
  47643. do {
  47644. if (p.x < leftmost.x)
  47645. leftmost = p;
  47646. p = p.next;
  47647. } while (p !== start);
  47648. return leftmost;
  47649. }
  47650. // check if a point lies within a convex triangle
  47651. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  47652. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  47653. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  47654. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  47655. }
  47656. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  47657. function isValidDiagonal(a, b) {
  47658. return a.next.i !== b.i &&
  47659. a.prev.i !== b.i &&
  47660. !intersectsPolygon(a, b) &&
  47661. locallyInside(a, b) &&
  47662. locallyInside(b, a) &&
  47663. middleInside(a, b);
  47664. }
  47665. // signed area of a triangle
  47666. function area(p, q, r) {
  47667. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  47668. }
  47669. // check if two points are equal
  47670. function equals(p1, p2) {
  47671. return p1.x === p2.x && p1.y === p2.y;
  47672. }
  47673. // check if two segments intersect
  47674. function intersects(p1, q1, p2, q2) {
  47675. if ((equals(p1, q1) && equals(p2, q2)) ||
  47676. (equals(p1, q2) && equals(p2, q1)))
  47677. return true;
  47678. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  47679. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  47680. }
  47681. // check if a polygon diagonal intersects any polygon segments
  47682. function intersectsPolygon(a, b) {
  47683. var p = a;
  47684. do {
  47685. if (p.i !== a.i &&
  47686. p.next.i !== a.i &&
  47687. p.i !== b.i &&
  47688. p.next.i !== b.i &&
  47689. intersects(p, p.next, a, b))
  47690. return true;
  47691. p = p.next;
  47692. } while (p !== a);
  47693. return false;
  47694. }
  47695. // check if a polygon diagonal is locally inside the polygon
  47696. function locallyInside(a, b) {
  47697. return area(a.prev, a, a.next) < 0
  47698. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  47699. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  47700. }
  47701. // check if the middle point of a polygon diagonal is inside the polygon
  47702. function middleInside(a, b) {
  47703. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  47704. do {
  47705. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  47706. inside = !inside;
  47707. p = p.next;
  47708. } while (p !== a);
  47709. return inside;
  47710. }
  47711. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  47712. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  47713. function splitPolygon(a, b) {
  47714. 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;
  47715. a.next = b;
  47716. b.prev = a;
  47717. a2.next = an;
  47718. an.prev = a2;
  47719. b2.next = a2;
  47720. a2.prev = b2;
  47721. bp.next = b2;
  47722. b2.prev = bp;
  47723. return b2;
  47724. }
  47725. // create a node and optionally link it with previous one (in a circular doubly linked list)
  47726. function insertNode(i, x, y, last) {
  47727. var p = new Node(i, x, y);
  47728. if (!last) {
  47729. p.prev = p;
  47730. p.next = p;
  47731. }
  47732. else {
  47733. p.next = last.next;
  47734. p.prev = last;
  47735. last.next.prev = p;
  47736. last.next = p;
  47737. }
  47738. return p;
  47739. }
  47740. function removeNode(p) {
  47741. p.next.prev = p.prev;
  47742. p.prev.next = p.next;
  47743. if (p.prevZ)
  47744. p.prevZ.nextZ = p.nextZ;
  47745. if (p.nextZ)
  47746. p.nextZ.prevZ = p.prevZ;
  47747. }
  47748. function Node(i, x, y) {
  47749. // vertice index in coordinates array
  47750. this.i = i;
  47751. // vertex coordinates
  47752. this.x = x;
  47753. this.y = y;
  47754. // previous and next vertice nodes in a polygon ring
  47755. this.prev = null;
  47756. this.next = null;
  47757. // z-order curve value
  47758. this.z = null;
  47759. // previous and next nodes in z-order
  47760. this.prevZ = null;
  47761. this.nextZ = null;
  47762. // indicates whether this is a steiner point
  47763. this.steiner = false;
  47764. }
  47765. /**
  47766. * return a percentage difference between the polygon area and its triangulation area;
  47767. * used to verify correctness of triangulation
  47768. */
  47769. function deviation(data, holeIndices, dim, triangles) {
  47770. var hasHoles = holeIndices && holeIndices.length;
  47771. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  47772. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  47773. if (hasHoles) {
  47774. for (var i = 0, len = holeIndices.length; i < len; i++) {
  47775. var start = holeIndices[i] * dim;
  47776. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47777. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  47778. }
  47779. }
  47780. var trianglesArea = 0;
  47781. for (i = 0; i < triangles.length; i += 3) {
  47782. var a = triangles[i] * dim;
  47783. var b = triangles[i + 1] * dim;
  47784. var c = triangles[i + 2] * dim;
  47785. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  47786. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  47787. }
  47788. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  47789. }
  47790. Earcut.deviation = deviation;
  47791. ;
  47792. function signedArea(data, start, end, dim) {
  47793. var sum = 0;
  47794. for (var i = start, j = end - dim; i < end; i += dim) {
  47795. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  47796. j = i;
  47797. }
  47798. return sum;
  47799. }
  47800. /**
  47801. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  47802. */
  47803. function flatten(data) {
  47804. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  47805. for (var i = 0; i < data.length; i++) {
  47806. for (var j = 0; j < data[i].length; j++) {
  47807. for (var d = 0; d < dim; d++)
  47808. result.vertices.push(data[i][j][d]);
  47809. }
  47810. if (i > 0) {
  47811. holeIndex += data[i - 1].length;
  47812. result.holes.push(holeIndex);
  47813. }
  47814. }
  47815. return result;
  47816. }
  47817. Earcut.flatten = flatten;
  47818. ;
  47819. })(Earcut || (Earcut = {}));
  47820. //# sourceMappingURL=babylon.earcut.js.map
  47821. var BABYLON;
  47822. (function (BABYLON) {
  47823. // Unique ID when we import meshes from Babylon to CSG
  47824. var currentCSGMeshId = 0;
  47825. // # class Vertex
  47826. // Represents a vertex of a polygon. Use your own vertex class instead of this
  47827. // one to provide additional features like texture coordinates and vertex
  47828. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  47829. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  47830. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  47831. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  47832. // is not used anywhere else.
  47833. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  47834. var Vertex = (function () {
  47835. function Vertex(pos, normal, uv) {
  47836. this.pos = pos;
  47837. this.normal = normal;
  47838. this.uv = uv;
  47839. }
  47840. Vertex.prototype.clone = function () {
  47841. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  47842. };
  47843. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  47844. // orientation of a polygon is flipped.
  47845. Vertex.prototype.flip = function () {
  47846. this.normal = this.normal.scale(-1);
  47847. };
  47848. // Create a new vertex between this vertex and `other` by linearly
  47849. // interpolating all properties using a parameter of `t`. Subclasses should
  47850. // override this to interpolate additional properties.
  47851. Vertex.prototype.interpolate = function (other, t) {
  47852. 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));
  47853. };
  47854. return Vertex;
  47855. }());
  47856. // # class Plane
  47857. // Represents a plane in 3D space.
  47858. var Plane = (function () {
  47859. function Plane(normal, w) {
  47860. this.normal = normal;
  47861. this.w = w;
  47862. }
  47863. Plane.FromPoints = function (a, b, c) {
  47864. var v0 = c.subtract(a);
  47865. var v1 = b.subtract(a);
  47866. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  47867. return null;
  47868. }
  47869. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  47870. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  47871. };
  47872. Plane.prototype.clone = function () {
  47873. return new Plane(this.normal.clone(), this.w);
  47874. };
  47875. Plane.prototype.flip = function () {
  47876. this.normal.scaleInPlace(-1);
  47877. this.w = -this.w;
  47878. };
  47879. // Split `polygon` by this plane if needed, then put the polygon or polygon
  47880. // fragments in the appropriate lists. Coplanar polygons go into either
  47881. // `coplanarFront` or `coplanarBack` depending on their orientation with
  47882. // respect to this plane. Polygons in front or in back of this plane go into
  47883. // either `front` or `back`.
  47884. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  47885. var COPLANAR = 0;
  47886. var FRONT = 1;
  47887. var BACK = 2;
  47888. var SPANNING = 3;
  47889. // Classify each point as well as the entire polygon into one of the above
  47890. // four classes.
  47891. var polygonType = 0;
  47892. var types = [];
  47893. var i;
  47894. var t;
  47895. for (i = 0; i < polygon.vertices.length; i++) {
  47896. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  47897. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  47898. polygonType |= type;
  47899. types.push(type);
  47900. }
  47901. // Put the polygon in the correct list, splitting it when necessary.
  47902. switch (polygonType) {
  47903. case COPLANAR:
  47904. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  47905. break;
  47906. case FRONT:
  47907. front.push(polygon);
  47908. break;
  47909. case BACK:
  47910. back.push(polygon);
  47911. break;
  47912. case SPANNING:
  47913. var f = [], b = [];
  47914. for (i = 0; i < polygon.vertices.length; i++) {
  47915. var j = (i + 1) % polygon.vertices.length;
  47916. var ti = types[i], tj = types[j];
  47917. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  47918. if (ti !== BACK)
  47919. f.push(vi);
  47920. if (ti !== FRONT)
  47921. b.push(ti !== BACK ? vi.clone() : vi);
  47922. if ((ti | tj) === SPANNING) {
  47923. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  47924. var v = vi.interpolate(vj, t);
  47925. f.push(v);
  47926. b.push(v.clone());
  47927. }
  47928. }
  47929. var poly;
  47930. if (f.length >= 3) {
  47931. poly = new Polygon(f, polygon.shared);
  47932. if (poly.plane)
  47933. front.push(poly);
  47934. }
  47935. if (b.length >= 3) {
  47936. poly = new Polygon(b, polygon.shared);
  47937. if (poly.plane)
  47938. back.push(poly);
  47939. }
  47940. break;
  47941. }
  47942. };
  47943. return Plane;
  47944. }());
  47945. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  47946. // point is on the plane.
  47947. Plane.EPSILON = 1e-5;
  47948. // # class Polygon
  47949. // Represents a convex polygon. The vertices used to initialize a polygon must
  47950. // be coplanar and form a convex loop.
  47951. //
  47952. // Each convex polygon has a `shared` property, which is shared between all
  47953. // polygons that are clones of each other or were split from the same polygon.
  47954. // This can be used to define per-polygon properties (such as surface color).
  47955. var Polygon = (function () {
  47956. function Polygon(vertices, shared) {
  47957. this.vertices = vertices;
  47958. this.shared = shared;
  47959. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  47960. }
  47961. Polygon.prototype.clone = function () {
  47962. var vertices = this.vertices.map(function (v) { return v.clone(); });
  47963. return new Polygon(vertices, this.shared);
  47964. };
  47965. Polygon.prototype.flip = function () {
  47966. this.vertices.reverse().map(function (v) { v.flip(); });
  47967. this.plane.flip();
  47968. };
  47969. return Polygon;
  47970. }());
  47971. // # class Node
  47972. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  47973. // by picking a polygon to split along. That polygon (and all other coplanar
  47974. // polygons) are added directly to that node and the other polygons are added to
  47975. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  47976. // no distinction between internal and leaf nodes.
  47977. var Node = (function () {
  47978. function Node(polygons) {
  47979. this.plane = null;
  47980. this.front = null;
  47981. this.back = null;
  47982. this.polygons = [];
  47983. if (polygons) {
  47984. this.build(polygons);
  47985. }
  47986. }
  47987. Node.prototype.clone = function () {
  47988. var node = new Node();
  47989. node.plane = this.plane && this.plane.clone();
  47990. node.front = this.front && this.front.clone();
  47991. node.back = this.back && this.back.clone();
  47992. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  47993. return node;
  47994. };
  47995. // Convert solid space to empty space and empty space to solid space.
  47996. Node.prototype.invert = function () {
  47997. for (var i = 0; i < this.polygons.length; i++) {
  47998. this.polygons[i].flip();
  47999. }
  48000. if (this.plane) {
  48001. this.plane.flip();
  48002. }
  48003. if (this.front) {
  48004. this.front.invert();
  48005. }
  48006. if (this.back) {
  48007. this.back.invert();
  48008. }
  48009. var temp = this.front;
  48010. this.front = this.back;
  48011. this.back = temp;
  48012. };
  48013. // Recursively remove all polygons in `polygons` that are inside this BSP
  48014. // tree.
  48015. Node.prototype.clipPolygons = function (polygons) {
  48016. if (!this.plane)
  48017. return polygons.slice();
  48018. var front = [], back = [];
  48019. for (var i = 0; i < polygons.length; i++) {
  48020. this.plane.splitPolygon(polygons[i], front, back, front, back);
  48021. }
  48022. if (this.front) {
  48023. front = this.front.clipPolygons(front);
  48024. }
  48025. if (this.back) {
  48026. back = this.back.clipPolygons(back);
  48027. }
  48028. else {
  48029. back = [];
  48030. }
  48031. return front.concat(back);
  48032. };
  48033. // Remove all polygons in this BSP tree that are inside the other BSP tree
  48034. // `bsp`.
  48035. Node.prototype.clipTo = function (bsp) {
  48036. this.polygons = bsp.clipPolygons(this.polygons);
  48037. if (this.front)
  48038. this.front.clipTo(bsp);
  48039. if (this.back)
  48040. this.back.clipTo(bsp);
  48041. };
  48042. // Return a list of all polygons in this BSP tree.
  48043. Node.prototype.allPolygons = function () {
  48044. var polygons = this.polygons.slice();
  48045. if (this.front)
  48046. polygons = polygons.concat(this.front.allPolygons());
  48047. if (this.back)
  48048. polygons = polygons.concat(this.back.allPolygons());
  48049. return polygons;
  48050. };
  48051. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  48052. // new polygons are filtered down to the bottom of the tree and become new
  48053. // nodes there. Each set of polygons is partitioned using the first polygon
  48054. // (no heuristic is used to pick a good split).
  48055. Node.prototype.build = function (polygons) {
  48056. if (!polygons.length)
  48057. return;
  48058. if (!this.plane)
  48059. this.plane = polygons[0].plane.clone();
  48060. var front = [], back = [];
  48061. for (var i = 0; i < polygons.length; i++) {
  48062. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  48063. }
  48064. if (front.length) {
  48065. if (!this.front)
  48066. this.front = new Node();
  48067. this.front.build(front);
  48068. }
  48069. if (back.length) {
  48070. if (!this.back)
  48071. this.back = new Node();
  48072. this.back.build(back);
  48073. }
  48074. };
  48075. return Node;
  48076. }());
  48077. var CSG = (function () {
  48078. function CSG() {
  48079. this.polygons = new Array();
  48080. }
  48081. // Convert BABYLON.Mesh to BABYLON.CSG
  48082. CSG.FromMesh = function (mesh) {
  48083. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  48084. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  48085. if (mesh instanceof BABYLON.Mesh) {
  48086. mesh.computeWorldMatrix(true);
  48087. matrix = mesh.getWorldMatrix();
  48088. meshPosition = mesh.position.clone();
  48089. meshRotation = mesh.rotation.clone();
  48090. if (mesh.rotationQuaternion) {
  48091. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  48092. }
  48093. meshScaling = mesh.scaling.clone();
  48094. }
  48095. else {
  48096. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  48097. }
  48098. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48099. var subMeshes = mesh.subMeshes;
  48100. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  48101. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  48102. vertices = [];
  48103. for (var j = 0; j < 3; j++) {
  48104. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  48105. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  48106. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  48107. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  48108. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  48109. vertex = new Vertex(position, normal, uv);
  48110. vertices.push(vertex);
  48111. }
  48112. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  48113. // To handle the case of degenerated triangle
  48114. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  48115. if (polygon.plane)
  48116. polygons.push(polygon);
  48117. }
  48118. }
  48119. var csg = CSG.FromPolygons(polygons);
  48120. csg.matrix = matrix;
  48121. csg.position = meshPosition;
  48122. csg.rotation = meshRotation;
  48123. csg.scaling = meshScaling;
  48124. csg.rotationQuaternion = meshRotationQuaternion;
  48125. currentCSGMeshId++;
  48126. return csg;
  48127. };
  48128. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  48129. CSG.FromPolygons = function (polygons) {
  48130. var csg = new CSG();
  48131. csg.polygons = polygons;
  48132. return csg;
  48133. };
  48134. CSG.prototype.clone = function () {
  48135. var csg = new CSG();
  48136. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  48137. csg.copyTransformAttributes(this);
  48138. return csg;
  48139. };
  48140. CSG.prototype.toPolygons = function () {
  48141. return this.polygons;
  48142. };
  48143. CSG.prototype.union = function (csg) {
  48144. var a = new Node(this.clone().polygons);
  48145. var b = new Node(csg.clone().polygons);
  48146. a.clipTo(b);
  48147. b.clipTo(a);
  48148. b.invert();
  48149. b.clipTo(a);
  48150. b.invert();
  48151. a.build(b.allPolygons());
  48152. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48153. };
  48154. CSG.prototype.unionInPlace = function (csg) {
  48155. var a = new Node(this.polygons);
  48156. var b = new Node(csg.polygons);
  48157. a.clipTo(b);
  48158. b.clipTo(a);
  48159. b.invert();
  48160. b.clipTo(a);
  48161. b.invert();
  48162. a.build(b.allPolygons());
  48163. this.polygons = a.allPolygons();
  48164. };
  48165. CSG.prototype.subtract = function (csg) {
  48166. var a = new Node(this.clone().polygons);
  48167. var b = new Node(csg.clone().polygons);
  48168. a.invert();
  48169. a.clipTo(b);
  48170. b.clipTo(a);
  48171. b.invert();
  48172. b.clipTo(a);
  48173. b.invert();
  48174. a.build(b.allPolygons());
  48175. a.invert();
  48176. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48177. };
  48178. CSG.prototype.subtractInPlace = function (csg) {
  48179. var a = new Node(this.polygons);
  48180. var b = new Node(csg.polygons);
  48181. a.invert();
  48182. a.clipTo(b);
  48183. b.clipTo(a);
  48184. b.invert();
  48185. b.clipTo(a);
  48186. b.invert();
  48187. a.build(b.allPolygons());
  48188. a.invert();
  48189. this.polygons = a.allPolygons();
  48190. };
  48191. CSG.prototype.intersect = function (csg) {
  48192. var a = new Node(this.clone().polygons);
  48193. var b = new Node(csg.clone().polygons);
  48194. a.invert();
  48195. b.clipTo(a);
  48196. b.invert();
  48197. a.clipTo(b);
  48198. b.clipTo(a);
  48199. a.build(b.allPolygons());
  48200. a.invert();
  48201. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48202. };
  48203. CSG.prototype.intersectInPlace = function (csg) {
  48204. var a = new Node(this.polygons);
  48205. var b = new Node(csg.polygons);
  48206. a.invert();
  48207. b.clipTo(a);
  48208. b.invert();
  48209. a.clipTo(b);
  48210. b.clipTo(a);
  48211. a.build(b.allPolygons());
  48212. a.invert();
  48213. this.polygons = a.allPolygons();
  48214. };
  48215. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  48216. // not modified.
  48217. CSG.prototype.inverse = function () {
  48218. var csg = this.clone();
  48219. csg.inverseInPlace();
  48220. return csg;
  48221. };
  48222. CSG.prototype.inverseInPlace = function () {
  48223. this.polygons.map(function (p) { p.flip(); });
  48224. };
  48225. // This is used to keep meshes transformations so they can be restored
  48226. // when we build back a Babylon Mesh
  48227. // NB : All CSG operations are performed in world coordinates
  48228. CSG.prototype.copyTransformAttributes = function (csg) {
  48229. this.matrix = csg.matrix;
  48230. this.position = csg.position;
  48231. this.rotation = csg.rotation;
  48232. this.scaling = csg.scaling;
  48233. this.rotationQuaternion = csg.rotationQuaternion;
  48234. return this;
  48235. };
  48236. // Build Raw mesh from CSG
  48237. // Coordinates here are in world space
  48238. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  48239. var matrix = this.matrix.clone();
  48240. matrix.invert();
  48241. 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;
  48242. if (keepSubMeshes) {
  48243. // Sort Polygons, since subMeshes are indices range
  48244. polygons.sort(function (a, b) {
  48245. if (a.shared.meshId === b.shared.meshId) {
  48246. return a.shared.subMeshId - b.shared.subMeshId;
  48247. }
  48248. else {
  48249. return a.shared.meshId - b.shared.meshId;
  48250. }
  48251. });
  48252. }
  48253. for (var i = 0, il = polygons.length; i < il; i++) {
  48254. polygon = polygons[i];
  48255. // Building SubMeshes
  48256. if (!subMesh_dict[polygon.shared.meshId]) {
  48257. subMesh_dict[polygon.shared.meshId] = {};
  48258. }
  48259. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  48260. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  48261. indexStart: +Infinity,
  48262. indexEnd: -Infinity,
  48263. materialIndex: polygon.shared.materialIndex
  48264. };
  48265. }
  48266. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  48267. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  48268. polygonIndices[0] = 0;
  48269. polygonIndices[1] = j - 1;
  48270. polygonIndices[2] = j;
  48271. for (var k = 0; k < 3; k++) {
  48272. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  48273. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  48274. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  48275. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  48276. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  48277. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  48278. // Check if 2 points can be merged
  48279. if (!(typeof vertex_idx !== 'undefined' &&
  48280. normals[vertex_idx * 3] === localNormal.x &&
  48281. normals[vertex_idx * 3 + 1] === localNormal.y &&
  48282. normals[vertex_idx * 3 + 2] === localNormal.z &&
  48283. uvs[vertex_idx * 2] === uv.x &&
  48284. uvs[vertex_idx * 2 + 1] === uv.y)) {
  48285. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  48286. uvs.push(uv.x, uv.y);
  48287. normals.push(normal.x, normal.y, normal.z);
  48288. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  48289. }
  48290. indices.push(vertex_idx);
  48291. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  48292. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  48293. currentIndex++;
  48294. }
  48295. }
  48296. }
  48297. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  48298. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  48299. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  48300. mesh.setIndices(indices);
  48301. if (keepSubMeshes) {
  48302. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  48303. var materialIndexOffset = 0, materialMaxIndex;
  48304. mesh.subMeshes = new Array();
  48305. for (var m in subMesh_dict) {
  48306. materialMaxIndex = -1;
  48307. for (var sm in subMesh_dict[m]) {
  48308. subMesh_obj = subMesh_dict[m][sm];
  48309. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  48310. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  48311. }
  48312. materialIndexOffset += ++materialMaxIndex;
  48313. }
  48314. }
  48315. return mesh;
  48316. };
  48317. // Build Mesh from CSG taking material and transforms into account
  48318. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  48319. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  48320. mesh.material = material;
  48321. mesh.position.copyFrom(this.position);
  48322. mesh.rotation.copyFrom(this.rotation);
  48323. if (this.rotationQuaternion) {
  48324. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  48325. }
  48326. mesh.scaling.copyFrom(this.scaling);
  48327. mesh.computeWorldMatrix(true);
  48328. return mesh;
  48329. };
  48330. return CSG;
  48331. }());
  48332. BABYLON.CSG = CSG;
  48333. })(BABYLON || (BABYLON = {}));
  48334. //# sourceMappingURL=babylon.csg.js.map
  48335. var BABYLON;
  48336. (function (BABYLON) {
  48337. var VRDistortionCorrectionPostProcess = (function (_super) {
  48338. __extends(VRDistortionCorrectionPostProcess, _super);
  48339. //ANY
  48340. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  48341. var _this = _super.call(this, name, "vrDistortionCorrection", [
  48342. 'LensCenter',
  48343. 'Scale',
  48344. 'ScaleIn',
  48345. 'HmdWarpParam'
  48346. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  48347. _this._isRightEye = isRightEye;
  48348. _this._distortionFactors = vrMetrics.distortionK;
  48349. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  48350. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  48351. _this.onSizeChangedObservable.add(function () {
  48352. _this.aspectRatio = _this.width * .5 / _this.height;
  48353. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  48354. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  48355. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  48356. });
  48357. _this.onApplyObservable.add(function (effect) {
  48358. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  48359. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  48360. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  48361. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  48362. });
  48363. return _this;
  48364. }
  48365. return VRDistortionCorrectionPostProcess;
  48366. }(BABYLON.PostProcess));
  48367. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  48368. })(BABYLON || (BABYLON = {}));
  48369. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  48370. // Mainly based on these 2 articles :
  48371. // 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
  48372. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  48373. var BABYLON;
  48374. (function (BABYLON) {
  48375. var JoystickAxis;
  48376. (function (JoystickAxis) {
  48377. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  48378. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  48379. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  48380. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  48381. var VirtualJoystick = (function () {
  48382. function VirtualJoystick(leftJoystick) {
  48383. var _this = this;
  48384. if (leftJoystick) {
  48385. this._leftJoystick = true;
  48386. }
  48387. else {
  48388. this._leftJoystick = false;
  48389. }
  48390. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  48391. VirtualJoystick._globalJoystickIndex++;
  48392. // By default left & right arrow keys are moving the X
  48393. // and up & down keys are moving the Y
  48394. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48395. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48396. this.reverseLeftRight = false;
  48397. this.reverseUpDown = false;
  48398. // collections of pointers
  48399. this._touches = new BABYLON.StringDictionary();
  48400. this.deltaPosition = BABYLON.Vector3.Zero();
  48401. this._joystickSensibility = 25;
  48402. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48403. this._rotationSpeed = 25;
  48404. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  48405. this._rotateOnAxisRelativeToMesh = false;
  48406. this._onResize = function (evt) {
  48407. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48408. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48409. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  48410. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  48411. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  48412. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  48413. };
  48414. // injecting a canvas element on top of the canvas 3D game
  48415. if (!VirtualJoystick.vjCanvas) {
  48416. window.addEventListener("resize", this._onResize, false);
  48417. VirtualJoystick.vjCanvas = document.createElement("canvas");
  48418. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48419. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48420. VirtualJoystick.vjCanvas.width = window.innerWidth;
  48421. VirtualJoystick.vjCanvas.height = window.innerHeight;
  48422. VirtualJoystick.vjCanvas.style.width = "100%";
  48423. VirtualJoystick.vjCanvas.style.height = "100%";
  48424. VirtualJoystick.vjCanvas.style.position = "absolute";
  48425. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  48426. VirtualJoystick.vjCanvas.style.top = "0px";
  48427. VirtualJoystick.vjCanvas.style.left = "0px";
  48428. VirtualJoystick.vjCanvas.style.zIndex = "5";
  48429. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  48430. // Support for jQuery PEP polyfill
  48431. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  48432. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  48433. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  48434. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48435. document.body.appendChild(VirtualJoystick.vjCanvas);
  48436. }
  48437. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  48438. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  48439. this.pressed = false;
  48440. // default joystick color
  48441. this._joystickColor = "cyan";
  48442. this._joystickPointerID = -1;
  48443. // current joystick position
  48444. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  48445. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  48446. // origin joystick position
  48447. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  48448. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  48449. this._onPointerDownHandlerRef = function (evt) {
  48450. _this._onPointerDown(evt);
  48451. };
  48452. this._onPointerMoveHandlerRef = function (evt) {
  48453. _this._onPointerMove(evt);
  48454. };
  48455. this._onPointerOutHandlerRef = function (evt) {
  48456. _this._onPointerUp(evt);
  48457. };
  48458. this._onPointerUpHandlerRef = function (evt) {
  48459. _this._onPointerUp(evt);
  48460. };
  48461. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  48462. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  48463. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  48464. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  48465. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  48466. evt.preventDefault(); // Disables system menu
  48467. }, false);
  48468. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48469. }
  48470. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  48471. this._joystickSensibility = newJoystickSensibility;
  48472. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48473. };
  48474. VirtualJoystick.prototype._onPointerDown = function (e) {
  48475. var positionOnScreenCondition;
  48476. e.preventDefault();
  48477. if (this._leftJoystick === true) {
  48478. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  48479. }
  48480. else {
  48481. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  48482. }
  48483. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  48484. // First contact will be dedicated to the virtual joystick
  48485. this._joystickPointerID = e.pointerId;
  48486. this._joystickPointerStartPos.x = e.clientX;
  48487. this._joystickPointerStartPos.y = e.clientY;
  48488. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  48489. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  48490. this._deltaJoystickVector.x = 0;
  48491. this._deltaJoystickVector.y = 0;
  48492. this.pressed = true;
  48493. this._touches.add(e.pointerId.toString(), e);
  48494. }
  48495. else {
  48496. // You can only trigger the action buttons with a joystick declared
  48497. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  48498. this._action();
  48499. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  48500. }
  48501. }
  48502. };
  48503. VirtualJoystick.prototype._onPointerMove = function (e) {
  48504. // If the current pointer is the one associated to the joystick (first touch contact)
  48505. if (this._joystickPointerID == e.pointerId) {
  48506. this._joystickPointerPos.x = e.clientX;
  48507. this._joystickPointerPos.y = e.clientY;
  48508. this._deltaJoystickVector = this._joystickPointerPos.clone();
  48509. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  48510. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  48511. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  48512. switch (this._axisTargetedByLeftAndRight) {
  48513. case JoystickAxis.X:
  48514. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  48515. break;
  48516. case JoystickAxis.Y:
  48517. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  48518. break;
  48519. case JoystickAxis.Z:
  48520. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  48521. break;
  48522. }
  48523. var directionUpDown = this.reverseUpDown ? 1 : -1;
  48524. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  48525. switch (this._axisTargetedByUpAndDown) {
  48526. case JoystickAxis.X:
  48527. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  48528. break;
  48529. case JoystickAxis.Y:
  48530. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  48531. break;
  48532. case JoystickAxis.Z:
  48533. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  48534. break;
  48535. }
  48536. }
  48537. else {
  48538. var data = this._touches.get(e.pointerId.toString());
  48539. if (data) {
  48540. data.x = e.clientX;
  48541. data.y = e.clientY;
  48542. }
  48543. }
  48544. };
  48545. VirtualJoystick.prototype._onPointerUp = function (e) {
  48546. if (this._joystickPointerID == e.pointerId) {
  48547. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  48548. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  48549. this._joystickPointerID = -1;
  48550. this.pressed = false;
  48551. }
  48552. else {
  48553. var touch = this._touches.get(e.pointerId.toString());
  48554. if (touch) {
  48555. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48556. }
  48557. }
  48558. this._deltaJoystickVector.x = 0;
  48559. this._deltaJoystickVector.y = 0;
  48560. this._touches.remove(e.pointerId.toString());
  48561. };
  48562. /**
  48563. * Change the color of the virtual joystick
  48564. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  48565. */
  48566. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  48567. this._joystickColor = newColor;
  48568. };
  48569. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  48570. this._action = action;
  48571. };
  48572. // Define which axis you'd like to control for left & right
  48573. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  48574. switch (axis) {
  48575. case JoystickAxis.X:
  48576. case JoystickAxis.Y:
  48577. case JoystickAxis.Z:
  48578. this._axisTargetedByLeftAndRight = axis;
  48579. break;
  48580. default:
  48581. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48582. break;
  48583. }
  48584. };
  48585. // Define which axis you'd like to control for up & down
  48586. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  48587. switch (axis) {
  48588. case JoystickAxis.X:
  48589. case JoystickAxis.Y:
  48590. case JoystickAxis.Z:
  48591. this._axisTargetedByUpAndDown = axis;
  48592. break;
  48593. default:
  48594. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48595. break;
  48596. }
  48597. };
  48598. VirtualJoystick.prototype._clearCanvas = function () {
  48599. if (this._leftJoystick) {
  48600. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  48601. }
  48602. else {
  48603. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  48604. }
  48605. };
  48606. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  48607. var _this = this;
  48608. if (this.pressed) {
  48609. this._touches.forEach(function (key, touch) {
  48610. if (touch.pointerId === _this._joystickPointerID) {
  48611. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  48612. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  48613. VirtualJoystick.vjCanvasContext.beginPath();
  48614. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48615. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48616. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  48617. VirtualJoystick.vjCanvasContext.stroke();
  48618. VirtualJoystick.vjCanvasContext.closePath();
  48619. VirtualJoystick.vjCanvasContext.beginPath();
  48620. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48621. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48622. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  48623. VirtualJoystick.vjCanvasContext.stroke();
  48624. VirtualJoystick.vjCanvasContext.closePath();
  48625. VirtualJoystick.vjCanvasContext.beginPath();
  48626. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48627. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  48628. VirtualJoystick.vjCanvasContext.stroke();
  48629. VirtualJoystick.vjCanvasContext.closePath();
  48630. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  48631. }
  48632. else {
  48633. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48634. VirtualJoystick.vjCanvasContext.beginPath();
  48635. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  48636. VirtualJoystick.vjCanvasContext.beginPath();
  48637. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  48638. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48639. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  48640. VirtualJoystick.vjCanvasContext.stroke();
  48641. VirtualJoystick.vjCanvasContext.closePath();
  48642. touch.prevX = touch.x;
  48643. touch.prevY = touch.y;
  48644. }
  48645. ;
  48646. });
  48647. }
  48648. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48649. };
  48650. VirtualJoystick.prototype.releaseCanvas = function () {
  48651. if (VirtualJoystick.vjCanvas) {
  48652. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  48653. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  48654. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  48655. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  48656. window.removeEventListener("resize", this._onResize);
  48657. document.body.removeChild(VirtualJoystick.vjCanvas);
  48658. VirtualJoystick.vjCanvas = null;
  48659. }
  48660. };
  48661. return VirtualJoystick;
  48662. }());
  48663. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  48664. VirtualJoystick._globalJoystickIndex = 0;
  48665. BABYLON.VirtualJoystick = VirtualJoystick;
  48666. })(BABYLON || (BABYLON = {}));
  48667. //# sourceMappingURL=babylon.virtualJoystick.js.map
  48668. var BABYLON;
  48669. (function (BABYLON) {
  48670. // We're mainly based on the logic defined into the FreeCamera code
  48671. var VirtualJoysticksCamera = (function (_super) {
  48672. __extends(VirtualJoysticksCamera, _super);
  48673. function VirtualJoysticksCamera(name, position, scene) {
  48674. var _this = _super.call(this, name, position, scene) || this;
  48675. _this.inputs.addVirtualJoystick();
  48676. return _this;
  48677. }
  48678. VirtualJoysticksCamera.prototype.getClassName = function () {
  48679. return "VirtualJoysticksCamera";
  48680. };
  48681. return VirtualJoysticksCamera;
  48682. }(BABYLON.FreeCamera));
  48683. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  48684. })(BABYLON || (BABYLON = {}));
  48685. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  48686. var BABYLON;
  48687. (function (BABYLON) {
  48688. var FreeCameraVirtualJoystickInput = (function () {
  48689. function FreeCameraVirtualJoystickInput() {
  48690. }
  48691. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  48692. return this._leftjoystick;
  48693. };
  48694. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  48695. return this._rightjoystick;
  48696. };
  48697. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  48698. if (this._leftjoystick) {
  48699. var camera = this.camera;
  48700. var speed = camera._computeLocalCameraSpeed() * 50;
  48701. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  48702. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  48703. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  48704. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  48705. if (!this._leftjoystick.pressed) {
  48706. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  48707. }
  48708. if (!this._rightjoystick.pressed) {
  48709. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  48710. }
  48711. }
  48712. };
  48713. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  48714. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  48715. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  48716. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  48717. this._leftjoystick.setJoystickSensibility(0.15);
  48718. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  48719. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  48720. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48721. this._rightjoystick.reverseUpDown = true;
  48722. this._rightjoystick.setJoystickSensibility(0.05);
  48723. this._rightjoystick.setJoystickColor("yellow");
  48724. };
  48725. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48726. this._leftjoystick.releaseCanvas();
  48727. this._rightjoystick.releaseCanvas();
  48728. };
  48729. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48730. return "FreeCameraVirtualJoystickInput";
  48731. };
  48732. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  48733. return "virtualJoystick";
  48734. };
  48735. return FreeCameraVirtualJoystickInput;
  48736. }());
  48737. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  48738. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  48739. })(BABYLON || (BABYLON = {}));
  48740. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  48741. var BABYLON;
  48742. (function (BABYLON) {
  48743. var AnaglyphPostProcess = (function (_super) {
  48744. __extends(AnaglyphPostProcess, _super);
  48745. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  48746. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  48747. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48748. _this.onApplyObservable.add(function (effect) {
  48749. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  48750. });
  48751. return _this;
  48752. }
  48753. return AnaglyphPostProcess;
  48754. }(BABYLON.PostProcess));
  48755. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  48756. })(BABYLON || (BABYLON = {}));
  48757. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  48758. var BABYLON;
  48759. (function (BABYLON) {
  48760. var OutlineRenderer = (function () {
  48761. function OutlineRenderer(scene) {
  48762. this._scene = scene;
  48763. }
  48764. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  48765. var _this = this;
  48766. if (useOverlay === void 0) { useOverlay = false; }
  48767. var scene = this._scene;
  48768. var engine = this._scene.getEngine();
  48769. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48770. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  48771. return;
  48772. }
  48773. var mesh = subMesh.getRenderingMesh();
  48774. var material = subMesh.getMaterial();
  48775. engine.enableEffect(this._effect);
  48776. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  48777. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  48778. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48779. // Bones
  48780. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48781. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48782. }
  48783. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48784. // Alpha test
  48785. if (material && material.needAlphaTesting()) {
  48786. var alphaTexture = material.getAlphaTestTexture();
  48787. this._effect.setTexture("diffuseSampler", alphaTexture);
  48788. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48789. }
  48790. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  48791. };
  48792. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  48793. var defines = [];
  48794. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  48795. var mesh = subMesh.getMesh();
  48796. var material = subMesh.getMaterial();
  48797. // Alpha test
  48798. if (material && material.needAlphaTesting()) {
  48799. defines.push("#define ALPHATEST");
  48800. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48801. attribs.push(BABYLON.VertexBuffer.UVKind);
  48802. defines.push("#define UV1");
  48803. }
  48804. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48805. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48806. defines.push("#define UV2");
  48807. }
  48808. }
  48809. // Bones
  48810. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48811. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48812. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48813. if (mesh.numBoneInfluencers > 4) {
  48814. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48815. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48816. }
  48817. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48818. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48819. }
  48820. else {
  48821. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48822. }
  48823. // Instances
  48824. if (useInstances) {
  48825. defines.push("#define INSTANCES");
  48826. attribs.push("world0");
  48827. attribs.push("world1");
  48828. attribs.push("world2");
  48829. attribs.push("world3");
  48830. }
  48831. // Get correct effect
  48832. var join = defines.join("\n");
  48833. if (this._cachedDefines !== join) {
  48834. this._cachedDefines = join;
  48835. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  48836. }
  48837. return this._effect.isReady();
  48838. };
  48839. return OutlineRenderer;
  48840. }());
  48841. BABYLON.OutlineRenderer = OutlineRenderer;
  48842. })(BABYLON || (BABYLON = {}));
  48843. //# sourceMappingURL=babylon.outlineRenderer.js.map
  48844. var BABYLON;
  48845. (function (BABYLON) {
  48846. var MeshAssetTask = (function () {
  48847. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  48848. this.name = name;
  48849. this.meshesNames = meshesNames;
  48850. this.rootUrl = rootUrl;
  48851. this.sceneFilename = sceneFilename;
  48852. this.isCompleted = false;
  48853. }
  48854. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48855. var _this = this;
  48856. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  48857. _this.loadedMeshes = meshes;
  48858. _this.loadedParticleSystems = particleSystems;
  48859. _this.loadedSkeletons = skeletons;
  48860. _this.isCompleted = true;
  48861. if (_this.onSuccess) {
  48862. _this.onSuccess(_this);
  48863. }
  48864. onSuccess();
  48865. }, null, function () {
  48866. if (_this.onError) {
  48867. _this.onError(_this);
  48868. }
  48869. onError();
  48870. });
  48871. };
  48872. return MeshAssetTask;
  48873. }());
  48874. BABYLON.MeshAssetTask = MeshAssetTask;
  48875. var TextFileAssetTask = (function () {
  48876. function TextFileAssetTask(name, url) {
  48877. this.name = name;
  48878. this.url = url;
  48879. this.isCompleted = false;
  48880. }
  48881. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48882. var _this = this;
  48883. BABYLON.Tools.LoadFile(this.url, function (data) {
  48884. _this.text = data;
  48885. _this.isCompleted = true;
  48886. if (_this.onSuccess) {
  48887. _this.onSuccess(_this);
  48888. }
  48889. onSuccess();
  48890. }, null, scene.database, false, function () {
  48891. if (_this.onError) {
  48892. _this.onError(_this);
  48893. }
  48894. onError();
  48895. });
  48896. };
  48897. return TextFileAssetTask;
  48898. }());
  48899. BABYLON.TextFileAssetTask = TextFileAssetTask;
  48900. var BinaryFileAssetTask = (function () {
  48901. function BinaryFileAssetTask(name, url) {
  48902. this.name = name;
  48903. this.url = url;
  48904. this.isCompleted = false;
  48905. }
  48906. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48907. var _this = this;
  48908. BABYLON.Tools.LoadFile(this.url, function (data) {
  48909. _this.data = data;
  48910. _this.isCompleted = true;
  48911. if (_this.onSuccess) {
  48912. _this.onSuccess(_this);
  48913. }
  48914. onSuccess();
  48915. }, null, scene.database, true, function () {
  48916. if (_this.onError) {
  48917. _this.onError(_this);
  48918. }
  48919. onError();
  48920. });
  48921. };
  48922. return BinaryFileAssetTask;
  48923. }());
  48924. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  48925. var ImageAssetTask = (function () {
  48926. function ImageAssetTask(name, url) {
  48927. this.name = name;
  48928. this.url = url;
  48929. this.isCompleted = false;
  48930. }
  48931. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48932. var _this = this;
  48933. var img = new Image();
  48934. BABYLON.Tools.SetCorsBehavior(this.url, img);
  48935. img.onload = function () {
  48936. _this.image = img;
  48937. _this.isCompleted = true;
  48938. if (_this.onSuccess) {
  48939. _this.onSuccess(_this);
  48940. }
  48941. onSuccess();
  48942. };
  48943. img.onerror = function () {
  48944. if (_this.onError) {
  48945. _this.onError(_this);
  48946. }
  48947. onError();
  48948. };
  48949. img.src = this.url;
  48950. };
  48951. return ImageAssetTask;
  48952. }());
  48953. BABYLON.ImageAssetTask = ImageAssetTask;
  48954. var TextureAssetTask = (function () {
  48955. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  48956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48957. this.name = name;
  48958. this.url = url;
  48959. this.noMipmap = noMipmap;
  48960. this.invertY = invertY;
  48961. this.samplingMode = samplingMode;
  48962. this.isCompleted = false;
  48963. }
  48964. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48965. var _this = this;
  48966. var onload = function () {
  48967. _this.isCompleted = true;
  48968. if (_this.onSuccess) {
  48969. _this.onSuccess(_this);
  48970. }
  48971. onSuccess();
  48972. };
  48973. var onerror = function () {
  48974. if (_this.onError) {
  48975. _this.onError(_this);
  48976. }
  48977. onError();
  48978. };
  48979. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  48980. };
  48981. return TextureAssetTask;
  48982. }());
  48983. BABYLON.TextureAssetTask = TextureAssetTask;
  48984. var CubeTextureAssetTask = (function () {
  48985. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  48986. this.name = name;
  48987. this.url = url;
  48988. this.extensions = extensions;
  48989. this.noMipmap = noMipmap;
  48990. this.files = files;
  48991. this.isCompleted = false;
  48992. }
  48993. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48994. var _this = this;
  48995. var onload = function () {
  48996. _this.isCompleted = true;
  48997. if (_this.onSuccess) {
  48998. _this.onSuccess(_this);
  48999. }
  49000. onSuccess();
  49001. };
  49002. var onerror = function () {
  49003. if (_this.onError) {
  49004. _this.onError(_this);
  49005. }
  49006. onError();
  49007. };
  49008. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  49009. };
  49010. return CubeTextureAssetTask;
  49011. }());
  49012. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  49013. var HDRCubeTextureAssetTask = (function () {
  49014. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49015. if (noMipmap === void 0) { noMipmap = false; }
  49016. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49017. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49018. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49019. this.name = name;
  49020. this.url = url;
  49021. this.size = size;
  49022. this.noMipmap = noMipmap;
  49023. this.generateHarmonics = generateHarmonics;
  49024. this.useInGammaSpace = useInGammaSpace;
  49025. this.usePMREMGenerator = usePMREMGenerator;
  49026. this.isCompleted = false;
  49027. }
  49028. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49029. var _this = this;
  49030. var onload = function () {
  49031. _this.isCompleted = true;
  49032. if (_this.onSuccess) {
  49033. _this.onSuccess(_this);
  49034. }
  49035. onSuccess();
  49036. };
  49037. var onerror = function () {
  49038. if (_this.onError) {
  49039. _this.onError(_this);
  49040. }
  49041. onError();
  49042. };
  49043. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  49044. };
  49045. return HDRCubeTextureAssetTask;
  49046. }());
  49047. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  49048. var AssetsManager = (function () {
  49049. function AssetsManager(scene) {
  49050. this.tasks = new Array();
  49051. this.waitingTasksCount = 0;
  49052. this.useDefaultLoadingScreen = true;
  49053. this._scene = scene;
  49054. }
  49055. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  49056. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  49057. this.tasks.push(task);
  49058. return task;
  49059. };
  49060. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  49061. var task = new TextFileAssetTask(taskName, url);
  49062. this.tasks.push(task);
  49063. return task;
  49064. };
  49065. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49066. var task = new BinaryFileAssetTask(taskName, url);
  49067. this.tasks.push(task);
  49068. return task;
  49069. };
  49070. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49071. var task = new ImageAssetTask(taskName, url);
  49072. this.tasks.push(task);
  49073. return task;
  49074. };
  49075. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49077. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49078. this.tasks.push(task);
  49079. return task;
  49080. };
  49081. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49082. this.waitingTasksCount--;
  49083. if (this.waitingTasksCount === 0) {
  49084. if (this.onFinish) {
  49085. this.onFinish(this.tasks);
  49086. }
  49087. this._scene.getEngine().hideLoadingUI();
  49088. }
  49089. };
  49090. AssetsManager.prototype._runTask = function (task) {
  49091. var _this = this;
  49092. task.run(this._scene, function () {
  49093. if (_this.onTaskSuccess) {
  49094. _this.onTaskSuccess(task);
  49095. }
  49096. _this._decreaseWaitingTasksCount();
  49097. }, function () {
  49098. if (_this.onTaskError) {
  49099. _this.onTaskError(task);
  49100. }
  49101. _this._decreaseWaitingTasksCount();
  49102. });
  49103. };
  49104. AssetsManager.prototype.reset = function () {
  49105. this.tasks = new Array();
  49106. return this;
  49107. };
  49108. AssetsManager.prototype.load = function () {
  49109. this.waitingTasksCount = this.tasks.length;
  49110. if (this.waitingTasksCount === 0) {
  49111. if (this.onFinish) {
  49112. this.onFinish(this.tasks);
  49113. }
  49114. return this;
  49115. }
  49116. if (this.useDefaultLoadingScreen) {
  49117. this._scene.getEngine().displayLoadingUI();
  49118. }
  49119. for (var index = 0; index < this.tasks.length; index++) {
  49120. var task = this.tasks[index];
  49121. this._runTask(task);
  49122. }
  49123. return this;
  49124. };
  49125. return AssetsManager;
  49126. }());
  49127. BABYLON.AssetsManager = AssetsManager;
  49128. })(BABYLON || (BABYLON = {}));
  49129. //# sourceMappingURL=babylon.assetsManager.js.map
  49130. var BABYLON;
  49131. (function (BABYLON) {
  49132. var VRCameraMetrics = (function () {
  49133. function VRCameraMetrics() {
  49134. this.compensateDistortion = true;
  49135. }
  49136. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  49137. get: function () {
  49138. return this.hResolution / (2 * this.vResolution);
  49139. },
  49140. enumerable: true,
  49141. configurable: true
  49142. });
  49143. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  49144. get: function () {
  49145. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  49151. get: function () {
  49152. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49153. var h = (4 * meters) / this.hScreenSize;
  49154. return BABYLON.Matrix.Translation(h, 0, 0);
  49155. },
  49156. enumerable: true,
  49157. configurable: true
  49158. });
  49159. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  49160. get: function () {
  49161. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49162. var h = (4 * meters) / this.hScreenSize;
  49163. return BABYLON.Matrix.Translation(-h, 0, 0);
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  49169. get: function () {
  49170. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  49171. },
  49172. enumerable: true,
  49173. configurable: true
  49174. });
  49175. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  49176. get: function () {
  49177. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  49178. },
  49179. enumerable: true,
  49180. configurable: true
  49181. });
  49182. VRCameraMetrics.GetDefault = function () {
  49183. var result = new VRCameraMetrics();
  49184. result.hResolution = 1280;
  49185. result.vResolution = 800;
  49186. result.hScreenSize = 0.149759993;
  49187. result.vScreenSize = 0.0935999975;
  49188. result.vScreenCenter = 0.0467999987;
  49189. result.eyeToScreenDistance = 0.0410000011;
  49190. result.lensSeparationDistance = 0.0635000020;
  49191. result.interpupillaryDistance = 0.0640000030;
  49192. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  49193. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  49194. result.postProcessScaleFactor = 1.714605507808412;
  49195. result.lensCenterOffset = 0.151976421;
  49196. return result;
  49197. };
  49198. return VRCameraMetrics;
  49199. }());
  49200. BABYLON.VRCameraMetrics = VRCameraMetrics;
  49201. })(BABYLON || (BABYLON = {}));
  49202. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  49203. var BABYLON;
  49204. (function (BABYLON) {
  49205. var WebVRFreeCamera = (function (_super) {
  49206. __extends(WebVRFreeCamera, _super);
  49207. function WebVRFreeCamera(name, position, scene, webVROptions) {
  49208. if (webVROptions === void 0) { webVROptions = {}; }
  49209. var _this = _super.call(this, name, position, scene) || this;
  49210. _this.webVROptions = webVROptions;
  49211. _this._vrDevice = null;
  49212. _this.rawPose = null;
  49213. _this._vrEnabled = false;
  49214. _this._attached = false;
  49215. _this._positionOffset = BABYLON.Vector3.Zero();
  49216. _this._descendants = [];
  49217. _this.devicePosition = BABYLON.Vector3.Zero();
  49218. _this.deviceScaleFactor = 1;
  49219. _this.controllers = [];
  49220. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  49221. //legacy support - the compensation boolean was removed.
  49222. if (arguments.length === 5) {
  49223. _this.webVROptions = arguments[4];
  49224. }
  49225. // default webVR options
  49226. if (_this.webVROptions.trackPosition == undefined) {
  49227. _this.webVROptions.trackPosition = true;
  49228. }
  49229. if (_this.webVROptions.controllerMeshes == undefined) {
  49230. _this.webVROptions.controllerMeshes = true;
  49231. }
  49232. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  49233. _this.webVROptions.defaultLightningOnControllers = true;
  49234. }
  49235. _this.rotationQuaternion = new BABYLON.Quaternion();
  49236. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  49237. if (_this.webVROptions && _this.webVROptions.positionScale) {
  49238. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  49239. }
  49240. //enable VR
  49241. _this.getEngine().initWebVR();
  49242. if (!_this.getEngine().vrDisplaysPromise) {
  49243. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  49244. }
  49245. else {
  49246. _this._frameData = new VRFrameData();
  49247. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  49248. if (devices.length > 0) {
  49249. _this._vrEnabled = true;
  49250. if (_this.webVROptions.displayName) {
  49251. var found = devices.some(function (device) {
  49252. if (device.displayName === _this.webVROptions.displayName) {
  49253. _this._vrDevice = device;
  49254. return true;
  49255. }
  49256. else {
  49257. return false;
  49258. }
  49259. });
  49260. if (!found) {
  49261. _this._vrDevice = devices[0];
  49262. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  49263. }
  49264. }
  49265. else {
  49266. //choose the first one
  49267. _this._vrDevice = devices[0];
  49268. }
  49269. //reset the rig parameters.
  49270. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  49271. if (_this._attached) {
  49272. _this.getEngine().enableVR(_this._vrDevice);
  49273. }
  49274. }
  49275. else {
  49276. BABYLON.Tools.Error("No WebVR devices found!");
  49277. }
  49278. });
  49279. }
  49280. // try to attach the controllers, if found.
  49281. _this.initControllers();
  49282. /**
  49283. * The idea behind the following lines:
  49284. * objects that have the camera as parent should actually have the rig cameras as a parent.
  49285. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  49286. * the second will not show it correctly.
  49287. *
  49288. * To solve this - each object that has the camera as parent will be added to a protected array.
  49289. * When the rig camera renders, it will take this array and set all of those to be its children.
  49290. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  49291. * Amazing!
  49292. */
  49293. scene.onBeforeCameraRenderObservable.add(function (camera) {
  49294. if (camera.parent === _this && _this.rigParenting) {
  49295. _this._descendants = _this.getDescendants(true, function (n) {
  49296. // don't take the cameras or the controllers!
  49297. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  49298. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  49299. return !isController && !isRigCamera;
  49300. });
  49301. _this._descendants.forEach(function (node) {
  49302. node.parent = camera;
  49303. });
  49304. }
  49305. });
  49306. scene.onAfterCameraRenderObservable.add(function (camera) {
  49307. if (camera.parent === _this && _this.rigParenting) {
  49308. _this._descendants.forEach(function (node) {
  49309. node.parent = _this;
  49310. });
  49311. }
  49312. });
  49313. return _this;
  49314. }
  49315. WebVRFreeCamera.prototype._checkInputs = function () {
  49316. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  49317. var currentPose = this._frameData.pose;
  49318. this.updateFromDevice(currentPose);
  49319. }
  49320. _super.prototype._checkInputs.call(this);
  49321. };
  49322. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  49323. if (poseData && poseData.orientation) {
  49324. this.rawPose = poseData;
  49325. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  49326. if (this.getScene().useRightHandedSystem) {
  49327. this.deviceRotationQuaternion.z *= -1;
  49328. this.deviceRotationQuaternion.w *= -1;
  49329. }
  49330. if (this.webVROptions.trackPosition && this.rawPose.position) {
  49331. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  49332. if (this.getScene().useRightHandedSystem) {
  49333. this.devicePosition.z *= -1;
  49334. }
  49335. }
  49336. }
  49337. };
  49338. /**
  49339. * WebVR's attach control will start broadcasting frames to the device.
  49340. * Note that in certain browsers (chrome for example) this function must be called
  49341. * within a user-interaction callback. Example:
  49342. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  49343. *
  49344. * @param {HTMLElement} element
  49345. * @param {boolean} [noPreventDefault]
  49346. *
  49347. * @memberOf WebVRFreeCamera
  49348. */
  49349. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49350. _super.prototype.attachControl.call(this, element, noPreventDefault);
  49351. this._attached = true;
  49352. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  49353. if (this._vrEnabled) {
  49354. this.getEngine().enableVR(this._vrDevice);
  49355. }
  49356. };
  49357. WebVRFreeCamera.prototype.detachControl = function (element) {
  49358. _super.prototype.detachControl.call(this, element);
  49359. this._vrEnabled = false;
  49360. this._attached = false;
  49361. this.getEngine().disableVR();
  49362. };
  49363. WebVRFreeCamera.prototype.getClassName = function () {
  49364. return "WebVRFreeCamera";
  49365. };
  49366. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  49367. //uses the vrDisplay's "resetPose()".
  49368. //pitch and roll won't be affected.
  49369. this._vrDevice.resetPose();
  49370. };
  49371. WebVRFreeCamera.prototype._updateRigCameras = function () {
  49372. var camLeft = this._rigCameras[0];
  49373. var camRight = this._rigCameras[1];
  49374. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49375. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49376. camLeft.position.copyFrom(this.devicePosition);
  49377. camRight.position.copyFrom(this.devicePosition);
  49378. };
  49379. /**
  49380. * This function is called by the two RIG cameras.
  49381. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  49382. */
  49383. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  49384. var _this = this;
  49385. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  49386. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  49387. if (!this.getScene().useRightHandedSystem) {
  49388. [2, 6, 8, 9, 14].forEach(function (num) {
  49389. _this._webvrViewMatrix.m[num] *= -1;
  49390. });
  49391. }
  49392. var parentCamera = this._cameraRigParams["parentCamera"];
  49393. // should the view matrix be updated with scale and position offset?
  49394. if (parentCamera.deviceScaleFactor !== 1) {
  49395. this._webvrViewMatrix.invert();
  49396. // scale the position, if set
  49397. if (parentCamera.deviceScaleFactor) {
  49398. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  49399. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  49400. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  49401. }
  49402. this._webvrViewMatrix.invert();
  49403. }
  49404. // update the camera rotation matrix
  49405. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  49406. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  49407. // Computing target and final matrix
  49408. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  49409. return this._webvrViewMatrix;
  49410. };
  49411. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  49412. var _this = this;
  49413. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  49414. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  49415. //babylon compatible matrix
  49416. if (!this.getScene().useRightHandedSystem) {
  49417. [8, 9, 10, 11].forEach(function (num) {
  49418. _this._projectionMatrix.m[num] *= -1;
  49419. });
  49420. }
  49421. return this._projectionMatrix;
  49422. };
  49423. WebVRFreeCamera.prototype.initControllers = function () {
  49424. var _this = this;
  49425. this.controllers = [];
  49426. new BABYLON.Gamepads(function (gp) {
  49427. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  49428. var webVrController = gp;
  49429. if (_this.webVROptions.controllerMeshes) {
  49430. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  49431. if (_this.webVROptions.defaultLightningOnControllers) {
  49432. if (!_this._lightOnControllers) {
  49433. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  49434. }
  49435. loadedMesh.getChildren().forEach(function (mesh) {
  49436. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  49437. });
  49438. }
  49439. });
  49440. }
  49441. webVrController.attachToPoseControlledCamera(_this);
  49442. // since this is async - sanity check. Is the controller already stored?
  49443. if (_this.controllers.indexOf(webVrController) === -1) {
  49444. //add to the controllers array
  49445. _this.controllers.push(webVrController);
  49446. //did we find enough controllers? Great! let the developer know.
  49447. if (_this.onControllersAttached && _this.controllers.length === 2) {
  49448. _this.onControllersAttached(_this.controllers);
  49449. }
  49450. }
  49451. }
  49452. });
  49453. };
  49454. return WebVRFreeCamera;
  49455. }(BABYLON.FreeCamera));
  49456. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  49457. })(BABYLON || (BABYLON = {}));
  49458. //# sourceMappingURL=babylon.webVRCamera.js.map
  49459. var BABYLON;
  49460. (function (BABYLON) {
  49461. // Standard optimizations
  49462. var SceneOptimization = (function () {
  49463. function SceneOptimization(priority) {
  49464. if (priority === void 0) { priority = 0; }
  49465. this.priority = priority;
  49466. this.apply = function (scene) {
  49467. return true; // Return true if everything that can be done was applied
  49468. };
  49469. }
  49470. return SceneOptimization;
  49471. }());
  49472. BABYLON.SceneOptimization = SceneOptimization;
  49473. var TextureOptimization = (function (_super) {
  49474. __extends(TextureOptimization, _super);
  49475. function TextureOptimization(priority, maximumSize) {
  49476. if (priority === void 0) { priority = 0; }
  49477. if (maximumSize === void 0) { maximumSize = 1024; }
  49478. var _this = _super.call(this, priority) || this;
  49479. _this.priority = priority;
  49480. _this.maximumSize = maximumSize;
  49481. _this.apply = function (scene) {
  49482. var allDone = true;
  49483. for (var index = 0; index < scene.textures.length; index++) {
  49484. var texture = scene.textures[index];
  49485. if (!texture.canRescale) {
  49486. continue;
  49487. }
  49488. var currentSize = texture.getSize();
  49489. var maxDimension = Math.max(currentSize.width, currentSize.height);
  49490. if (maxDimension > _this.maximumSize) {
  49491. texture.scale(0.5);
  49492. allDone = false;
  49493. }
  49494. }
  49495. return allDone;
  49496. };
  49497. return _this;
  49498. }
  49499. return TextureOptimization;
  49500. }(SceneOptimization));
  49501. BABYLON.TextureOptimization = TextureOptimization;
  49502. var HardwareScalingOptimization = (function (_super) {
  49503. __extends(HardwareScalingOptimization, _super);
  49504. function HardwareScalingOptimization(priority, maximumScale) {
  49505. if (priority === void 0) { priority = 0; }
  49506. if (maximumScale === void 0) { maximumScale = 2; }
  49507. var _this = _super.call(this, priority) || this;
  49508. _this.priority = priority;
  49509. _this.maximumScale = maximumScale;
  49510. _this._currentScale = 1;
  49511. _this.apply = function (scene) {
  49512. _this._currentScale++;
  49513. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  49514. return _this._currentScale >= _this.maximumScale;
  49515. };
  49516. return _this;
  49517. }
  49518. return HardwareScalingOptimization;
  49519. }(SceneOptimization));
  49520. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  49521. var ShadowsOptimization = (function (_super) {
  49522. __extends(ShadowsOptimization, _super);
  49523. function ShadowsOptimization() {
  49524. var _this = _super.apply(this, arguments) || this;
  49525. _this.apply = function (scene) {
  49526. scene.shadowsEnabled = false;
  49527. return true;
  49528. };
  49529. return _this;
  49530. }
  49531. return ShadowsOptimization;
  49532. }(SceneOptimization));
  49533. BABYLON.ShadowsOptimization = ShadowsOptimization;
  49534. var PostProcessesOptimization = (function (_super) {
  49535. __extends(PostProcessesOptimization, _super);
  49536. function PostProcessesOptimization() {
  49537. var _this = _super.apply(this, arguments) || this;
  49538. _this.apply = function (scene) {
  49539. scene.postProcessesEnabled = false;
  49540. return true;
  49541. };
  49542. return _this;
  49543. }
  49544. return PostProcessesOptimization;
  49545. }(SceneOptimization));
  49546. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  49547. var LensFlaresOptimization = (function (_super) {
  49548. __extends(LensFlaresOptimization, _super);
  49549. function LensFlaresOptimization() {
  49550. var _this = _super.apply(this, arguments) || this;
  49551. _this.apply = function (scene) {
  49552. scene.lensFlaresEnabled = false;
  49553. return true;
  49554. };
  49555. return _this;
  49556. }
  49557. return LensFlaresOptimization;
  49558. }(SceneOptimization));
  49559. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  49560. var ParticlesOptimization = (function (_super) {
  49561. __extends(ParticlesOptimization, _super);
  49562. function ParticlesOptimization() {
  49563. var _this = _super.apply(this, arguments) || this;
  49564. _this.apply = function (scene) {
  49565. scene.particlesEnabled = false;
  49566. return true;
  49567. };
  49568. return _this;
  49569. }
  49570. return ParticlesOptimization;
  49571. }(SceneOptimization));
  49572. BABYLON.ParticlesOptimization = ParticlesOptimization;
  49573. var RenderTargetsOptimization = (function (_super) {
  49574. __extends(RenderTargetsOptimization, _super);
  49575. function RenderTargetsOptimization() {
  49576. var _this = _super.apply(this, arguments) || this;
  49577. _this.apply = function (scene) {
  49578. scene.renderTargetsEnabled = false;
  49579. return true;
  49580. };
  49581. return _this;
  49582. }
  49583. return RenderTargetsOptimization;
  49584. }(SceneOptimization));
  49585. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  49586. var MergeMeshesOptimization = (function (_super) {
  49587. __extends(MergeMeshesOptimization, _super);
  49588. function MergeMeshesOptimization() {
  49589. var _this = _super.apply(this, arguments) || this;
  49590. _this._canBeMerged = function (abstractMesh) {
  49591. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  49592. return false;
  49593. }
  49594. var mesh = abstractMesh;
  49595. if (!mesh.isVisible || !mesh.isEnabled()) {
  49596. return false;
  49597. }
  49598. if (mesh.instances.length > 0) {
  49599. return false;
  49600. }
  49601. if (mesh.skeleton || mesh.hasLODLevels) {
  49602. return false;
  49603. }
  49604. if (mesh.parent) {
  49605. return false;
  49606. }
  49607. return true;
  49608. };
  49609. _this.apply = function (scene, updateSelectionTree) {
  49610. var globalPool = scene.meshes.slice(0);
  49611. var globalLength = globalPool.length;
  49612. for (var index = 0; index < globalLength; index++) {
  49613. var currentPool = new Array();
  49614. var current = globalPool[index];
  49615. // Checks
  49616. if (!_this._canBeMerged(current)) {
  49617. continue;
  49618. }
  49619. currentPool.push(current);
  49620. // Find compatible meshes
  49621. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  49622. var otherMesh = globalPool[subIndex];
  49623. if (!_this._canBeMerged(otherMesh)) {
  49624. continue;
  49625. }
  49626. if (otherMesh.material !== current.material) {
  49627. continue;
  49628. }
  49629. if (otherMesh.checkCollisions !== current.checkCollisions) {
  49630. continue;
  49631. }
  49632. currentPool.push(otherMesh);
  49633. globalLength--;
  49634. globalPool.splice(subIndex, 1);
  49635. subIndex--;
  49636. }
  49637. if (currentPool.length < 2) {
  49638. continue;
  49639. }
  49640. // Merge meshes
  49641. BABYLON.Mesh.MergeMeshes(currentPool);
  49642. }
  49643. if (updateSelectionTree != undefined) {
  49644. if (updateSelectionTree) {
  49645. scene.createOrUpdateSelectionOctree();
  49646. }
  49647. }
  49648. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  49649. scene.createOrUpdateSelectionOctree();
  49650. }
  49651. return true;
  49652. };
  49653. return _this;
  49654. }
  49655. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  49656. get: function () {
  49657. return MergeMeshesOptimization._UpdateSelectionTree;
  49658. },
  49659. set: function (value) {
  49660. MergeMeshesOptimization._UpdateSelectionTree = value;
  49661. },
  49662. enumerable: true,
  49663. configurable: true
  49664. });
  49665. return MergeMeshesOptimization;
  49666. }(SceneOptimization));
  49667. MergeMeshesOptimization._UpdateSelectionTree = false;
  49668. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  49669. // Options
  49670. var SceneOptimizerOptions = (function () {
  49671. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  49672. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  49673. if (trackerDuration === void 0) { trackerDuration = 2000; }
  49674. this.targetFrameRate = targetFrameRate;
  49675. this.trackerDuration = trackerDuration;
  49676. this.optimizations = new Array();
  49677. }
  49678. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  49679. var result = new SceneOptimizerOptions(targetFrameRate);
  49680. var priority = 0;
  49681. result.optimizations.push(new MergeMeshesOptimization(priority));
  49682. result.optimizations.push(new ShadowsOptimization(priority));
  49683. result.optimizations.push(new LensFlaresOptimization(priority));
  49684. // Next priority
  49685. priority++;
  49686. result.optimizations.push(new PostProcessesOptimization(priority));
  49687. result.optimizations.push(new ParticlesOptimization(priority));
  49688. // Next priority
  49689. priority++;
  49690. result.optimizations.push(new TextureOptimization(priority, 1024));
  49691. return result;
  49692. };
  49693. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  49694. var result = new SceneOptimizerOptions(targetFrameRate);
  49695. var priority = 0;
  49696. result.optimizations.push(new MergeMeshesOptimization(priority));
  49697. result.optimizations.push(new ShadowsOptimization(priority));
  49698. result.optimizations.push(new LensFlaresOptimization(priority));
  49699. // Next priority
  49700. priority++;
  49701. result.optimizations.push(new PostProcessesOptimization(priority));
  49702. result.optimizations.push(new ParticlesOptimization(priority));
  49703. // Next priority
  49704. priority++;
  49705. result.optimizations.push(new TextureOptimization(priority, 512));
  49706. // Next priority
  49707. priority++;
  49708. result.optimizations.push(new RenderTargetsOptimization(priority));
  49709. // Next priority
  49710. priority++;
  49711. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  49712. return result;
  49713. };
  49714. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  49715. var result = new SceneOptimizerOptions(targetFrameRate);
  49716. var priority = 0;
  49717. result.optimizations.push(new MergeMeshesOptimization(priority));
  49718. result.optimizations.push(new ShadowsOptimization(priority));
  49719. result.optimizations.push(new LensFlaresOptimization(priority));
  49720. // Next priority
  49721. priority++;
  49722. result.optimizations.push(new PostProcessesOptimization(priority));
  49723. result.optimizations.push(new ParticlesOptimization(priority));
  49724. // Next priority
  49725. priority++;
  49726. result.optimizations.push(new TextureOptimization(priority, 256));
  49727. // Next priority
  49728. priority++;
  49729. result.optimizations.push(new RenderTargetsOptimization(priority));
  49730. // Next priority
  49731. priority++;
  49732. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  49733. return result;
  49734. };
  49735. return SceneOptimizerOptions;
  49736. }());
  49737. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  49738. // Scene optimizer tool
  49739. var SceneOptimizer = (function () {
  49740. function SceneOptimizer() {
  49741. }
  49742. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  49743. // TODO: add an epsilon
  49744. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  49745. if (onSuccess) {
  49746. onSuccess();
  49747. }
  49748. return;
  49749. }
  49750. // Apply current level of optimizations
  49751. var allDone = true;
  49752. var noOptimizationApplied = true;
  49753. for (var index = 0; index < options.optimizations.length; index++) {
  49754. var optimization = options.optimizations[index];
  49755. if (optimization.priority === currentPriorityLevel) {
  49756. noOptimizationApplied = false;
  49757. allDone = allDone && optimization.apply(scene);
  49758. }
  49759. }
  49760. // If no optimization was applied, this is a failure :(
  49761. if (noOptimizationApplied) {
  49762. if (onFailure) {
  49763. onFailure();
  49764. }
  49765. return;
  49766. }
  49767. // If all optimizations were done, move to next level
  49768. if (allDone) {
  49769. currentPriorityLevel++;
  49770. }
  49771. // Let's the system running for a specific amount of time before checking FPS
  49772. scene.executeWhenReady(function () {
  49773. setTimeout(function () {
  49774. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49775. }, options.trackerDuration);
  49776. });
  49777. };
  49778. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49779. if (!options) {
  49780. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49781. }
  49782. // Let's the system running for a specific amount of time before checking FPS
  49783. scene.executeWhenReady(function () {
  49784. setTimeout(function () {
  49785. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49786. }, options.trackerDuration);
  49787. });
  49788. };
  49789. return SceneOptimizer;
  49790. }());
  49791. BABYLON.SceneOptimizer = SceneOptimizer;
  49792. })(BABYLON || (BABYLON = {}));
  49793. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  49794. var BABYLON;
  49795. (function (BABYLON) {
  49796. var Internals;
  49797. (function (Internals) {
  49798. var MeshLODLevel = (function () {
  49799. function MeshLODLevel(distance, mesh) {
  49800. this.distance = distance;
  49801. this.mesh = mesh;
  49802. }
  49803. return MeshLODLevel;
  49804. }());
  49805. Internals.MeshLODLevel = MeshLODLevel;
  49806. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49807. })(BABYLON || (BABYLON = {}));
  49808. //# sourceMappingURL=babylon.meshLODLevel.js.map
  49809. var BABYLON;
  49810. (function (BABYLON) {
  49811. var RawTexture = (function (_super) {
  49812. __extends(RawTexture, _super);
  49813. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49814. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49815. if (invertY === void 0) { invertY = false; }
  49816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49817. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49818. _this.format = format;
  49819. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49820. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49821. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49822. return _this;
  49823. }
  49824. RawTexture.prototype.update = function (data) {
  49825. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49826. };
  49827. // Statics
  49828. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49830. if (invertY === void 0) { invertY = false; }
  49831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49832. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49833. };
  49834. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49835. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49836. if (invertY === void 0) { invertY = false; }
  49837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49838. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49839. };
  49840. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49841. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49842. if (invertY === void 0) { invertY = false; }
  49843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49844. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49845. };
  49846. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49847. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49848. if (invertY === void 0) { invertY = false; }
  49849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49850. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49851. };
  49852. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49853. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49854. if (invertY === void 0) { invertY = false; }
  49855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49856. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49857. };
  49858. return RawTexture;
  49859. }(BABYLON.Texture));
  49860. BABYLON.RawTexture = RawTexture;
  49861. })(BABYLON || (BABYLON = {}));
  49862. //# sourceMappingURL=babylon.rawTexture.js.map
  49863. /// <reference path="..\Math\babylon.math.ts" />
  49864. var BABYLON;
  49865. (function (BABYLON) {
  49866. var IndexedVector2 = (function (_super) {
  49867. __extends(IndexedVector2, _super);
  49868. function IndexedVector2(original, index) {
  49869. var _this = _super.call(this, original.x, original.y) || this;
  49870. _this.index = index;
  49871. return _this;
  49872. }
  49873. return IndexedVector2;
  49874. }(BABYLON.Vector2));
  49875. var PolygonPoints = (function () {
  49876. function PolygonPoints() {
  49877. this.elements = new Array();
  49878. }
  49879. PolygonPoints.prototype.add = function (originalPoints) {
  49880. var _this = this;
  49881. var result = new Array();
  49882. originalPoints.forEach(function (point) {
  49883. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49884. var newPoint = new IndexedVector2(point, _this.elements.length);
  49885. result.push(newPoint);
  49886. _this.elements.push(newPoint);
  49887. }
  49888. });
  49889. return result;
  49890. };
  49891. PolygonPoints.prototype.computeBounds = function () {
  49892. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49893. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49894. this.elements.forEach(function (point) {
  49895. // x
  49896. if (point.x < lmin.x) {
  49897. lmin.x = point.x;
  49898. }
  49899. else if (point.x > lmax.x) {
  49900. lmax.x = point.x;
  49901. }
  49902. // y
  49903. if (point.y < lmin.y) {
  49904. lmin.y = point.y;
  49905. }
  49906. else if (point.y > lmax.y) {
  49907. lmax.y = point.y;
  49908. }
  49909. });
  49910. return {
  49911. min: lmin,
  49912. max: lmax,
  49913. width: lmax.x - lmin.x,
  49914. height: lmax.y - lmin.y
  49915. };
  49916. };
  49917. return PolygonPoints;
  49918. }());
  49919. var Polygon = (function () {
  49920. function Polygon() {
  49921. }
  49922. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  49923. return [
  49924. new BABYLON.Vector2(xmin, ymin),
  49925. new BABYLON.Vector2(xmax, ymin),
  49926. new BABYLON.Vector2(xmax, ymax),
  49927. new BABYLON.Vector2(xmin, ymax)
  49928. ];
  49929. };
  49930. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  49931. if (cx === void 0) { cx = 0; }
  49932. if (cy === void 0) { cy = 0; }
  49933. if (numberOfSides === void 0) { numberOfSides = 32; }
  49934. var result = new Array();
  49935. var angle = 0;
  49936. var increment = (Math.PI * 2) / numberOfSides;
  49937. for (var i = 0; i < numberOfSides; i++) {
  49938. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  49939. angle -= increment;
  49940. }
  49941. return result;
  49942. };
  49943. Polygon.Parse = function (input) {
  49944. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  49945. var i, result = [];
  49946. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  49947. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  49948. }
  49949. return result;
  49950. };
  49951. Polygon.StartingAt = function (x, y) {
  49952. return BABYLON.Path2.StartingAt(x, y);
  49953. };
  49954. return Polygon;
  49955. }());
  49956. BABYLON.Polygon = Polygon;
  49957. var PolygonMeshBuilder = (function () {
  49958. function PolygonMeshBuilder(name, contours, scene) {
  49959. this._points = new PolygonPoints();
  49960. this._outlinepoints = new PolygonPoints();
  49961. this._holes = [];
  49962. this._epoints = new Array();
  49963. this._eholes = new Array();
  49964. this._name = name;
  49965. this._scene = scene;
  49966. var points;
  49967. if (contours instanceof BABYLON.Path2) {
  49968. points = contours.getPoints();
  49969. }
  49970. else {
  49971. points = contours;
  49972. }
  49973. this._addToepoint(points);
  49974. this._points.add(points);
  49975. this._outlinepoints.add(points);
  49976. }
  49977. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  49978. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  49979. var p = points_1[_i];
  49980. this._epoints.push(p.x, p.y);
  49981. }
  49982. };
  49983. PolygonMeshBuilder.prototype.addHole = function (hole) {
  49984. this._points.add(hole);
  49985. var holepoints = new PolygonPoints();
  49986. holepoints.add(hole);
  49987. this._holes.push(holepoints);
  49988. this._eholes.push(this._epoints.length / 2);
  49989. this._addToepoint(hole);
  49990. return this;
  49991. };
  49992. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  49993. var _this = this;
  49994. if (updatable === void 0) { updatable = false; }
  49995. var result = new BABYLON.Mesh(this._name, this._scene);
  49996. var normals = [];
  49997. var positions = [];
  49998. var uvs = [];
  49999. var bounds = this._points.computeBounds();
  50000. this._points.elements.forEach(function (p) {
  50001. normals.push(0, 1.0, 0);
  50002. positions.push(p.x, 0, p.y);
  50003. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  50004. });
  50005. var indices = [];
  50006. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  50007. for (var i = 0; i < res.length; i++) {
  50008. indices.push(res[i]);
  50009. }
  50010. if (depth > 0) {
  50011. var positionscount = (positions.length / 3); //get the current pointcount
  50012. this._points.elements.forEach(function (p) {
  50013. normals.push(0, -1.0, 0);
  50014. positions.push(p.x, -depth, p.y);
  50015. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  50016. });
  50017. var totalCount = indices.length;
  50018. for (var i = 0; i < totalCount; i += 3) {
  50019. var i0 = indices[i + 0];
  50020. var i1 = indices[i + 1];
  50021. var i2 = indices[i + 2];
  50022. indices.push(i2 + positionscount);
  50023. indices.push(i1 + positionscount);
  50024. indices.push(i0 + positionscount);
  50025. }
  50026. //Add the sides
  50027. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  50028. this._holes.forEach(function (hole) {
  50029. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  50030. });
  50031. }
  50032. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  50033. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  50034. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  50035. result.setIndices(indices);
  50036. return result;
  50037. };
  50038. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  50039. var StartIndex = positions.length / 3;
  50040. var ulength = 0;
  50041. for (var i = 0; i < points.elements.length; i++) {
  50042. var p = points.elements[i];
  50043. var p1;
  50044. if ((i + 1) > points.elements.length - 1) {
  50045. p1 = points.elements[0];
  50046. }
  50047. else {
  50048. p1 = points.elements[i + 1];
  50049. }
  50050. positions.push(p.x, 0, p.y);
  50051. positions.push(p.x, -depth, p.y);
  50052. positions.push(p1.x, 0, p1.y);
  50053. positions.push(p1.x, -depth, p1.y);
  50054. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  50055. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  50056. var v3 = v2.subtract(v1);
  50057. var v4 = new BABYLON.Vector3(0, 1, 0);
  50058. var vn = BABYLON.Vector3.Cross(v3, v4);
  50059. vn = vn.normalize();
  50060. uvs.push(ulength / bounds.width, 0);
  50061. uvs.push(ulength / bounds.width, 1);
  50062. ulength += v3.length();
  50063. uvs.push((ulength / bounds.width), 0);
  50064. uvs.push((ulength / bounds.width), 1);
  50065. if (!flip) {
  50066. normals.push(-vn.x, -vn.y, -vn.z);
  50067. normals.push(-vn.x, -vn.y, -vn.z);
  50068. normals.push(-vn.x, -vn.y, -vn.z);
  50069. normals.push(-vn.x, -vn.y, -vn.z);
  50070. indices.push(StartIndex);
  50071. indices.push(StartIndex + 1);
  50072. indices.push(StartIndex + 2);
  50073. indices.push(StartIndex + 1);
  50074. indices.push(StartIndex + 3);
  50075. indices.push(StartIndex + 2);
  50076. }
  50077. else {
  50078. normals.push(vn.x, vn.y, vn.z);
  50079. normals.push(vn.x, vn.y, vn.z);
  50080. normals.push(vn.x, vn.y, vn.z);
  50081. normals.push(vn.x, vn.y, vn.z);
  50082. indices.push(StartIndex);
  50083. indices.push(StartIndex + 2);
  50084. indices.push(StartIndex + 1);
  50085. indices.push(StartIndex + 1);
  50086. indices.push(StartIndex + 2);
  50087. indices.push(StartIndex + 3);
  50088. }
  50089. StartIndex += 4;
  50090. }
  50091. ;
  50092. };
  50093. return PolygonMeshBuilder;
  50094. }());
  50095. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50096. })(BABYLON || (BABYLON = {}));
  50097. //# sourceMappingURL=babylon.polygonMesh.js.map
  50098. var BABYLON;
  50099. (function (BABYLON) {
  50100. var Octree = (function () {
  50101. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50102. if (maxDepth === void 0) { maxDepth = 2; }
  50103. this.maxDepth = maxDepth;
  50104. this.dynamicContent = new Array();
  50105. this._maxBlockCapacity = maxBlockCapacity || 64;
  50106. this._selectionContent = new BABYLON.SmartArray(1024);
  50107. this._creationFunc = creationFunc;
  50108. }
  50109. // Methods
  50110. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50111. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50112. };
  50113. Octree.prototype.addMesh = function (entry) {
  50114. for (var index = 0; index < this.blocks.length; index++) {
  50115. var block = this.blocks[index];
  50116. block.addEntry(entry);
  50117. }
  50118. };
  50119. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50120. this._selectionContent.reset();
  50121. for (var index = 0; index < this.blocks.length; index++) {
  50122. var block = this.blocks[index];
  50123. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50124. }
  50125. if (allowDuplicate) {
  50126. this._selectionContent.concat(this.dynamicContent);
  50127. }
  50128. else {
  50129. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50130. }
  50131. return this._selectionContent;
  50132. };
  50133. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50134. this._selectionContent.reset();
  50135. for (var index = 0; index < this.blocks.length; index++) {
  50136. var block = this.blocks[index];
  50137. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50138. }
  50139. if (allowDuplicate) {
  50140. this._selectionContent.concat(this.dynamicContent);
  50141. }
  50142. else {
  50143. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50144. }
  50145. return this._selectionContent;
  50146. };
  50147. Octree.prototype.intersectsRay = function (ray) {
  50148. this._selectionContent.reset();
  50149. for (var index = 0; index < this.blocks.length; index++) {
  50150. var block = this.blocks[index];
  50151. block.intersectsRay(ray, this._selectionContent);
  50152. }
  50153. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50154. return this._selectionContent;
  50155. };
  50156. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50157. target.blocks = new Array();
  50158. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50159. // Segmenting space
  50160. for (var x = 0; x < 2; x++) {
  50161. for (var y = 0; y < 2; y++) {
  50162. for (var z = 0; z < 2; z++) {
  50163. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50164. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50165. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50166. block.addEntries(entries);
  50167. target.blocks.push(block);
  50168. }
  50169. }
  50170. }
  50171. };
  50172. return Octree;
  50173. }());
  50174. Octree.CreationFuncForMeshes = function (entry, block) {
  50175. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50176. block.entries.push(entry);
  50177. }
  50178. };
  50179. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50180. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50181. block.entries.push(entry);
  50182. }
  50183. };
  50184. BABYLON.Octree = Octree;
  50185. })(BABYLON || (BABYLON = {}));
  50186. //# sourceMappingURL=babylon.octree.js.map
  50187. var BABYLON;
  50188. (function (BABYLON) {
  50189. var OctreeBlock = (function () {
  50190. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50191. this.entries = new Array();
  50192. this._boundingVectors = new Array();
  50193. this._capacity = capacity;
  50194. this._depth = depth;
  50195. this._maxDepth = maxDepth;
  50196. this._creationFunc = creationFunc;
  50197. this._minPoint = minPoint;
  50198. this._maxPoint = maxPoint;
  50199. this._boundingVectors.push(minPoint.clone());
  50200. this._boundingVectors.push(maxPoint.clone());
  50201. this._boundingVectors.push(minPoint.clone());
  50202. this._boundingVectors[2].x = maxPoint.x;
  50203. this._boundingVectors.push(minPoint.clone());
  50204. this._boundingVectors[3].y = maxPoint.y;
  50205. this._boundingVectors.push(minPoint.clone());
  50206. this._boundingVectors[4].z = maxPoint.z;
  50207. this._boundingVectors.push(maxPoint.clone());
  50208. this._boundingVectors[5].z = minPoint.z;
  50209. this._boundingVectors.push(maxPoint.clone());
  50210. this._boundingVectors[6].x = minPoint.x;
  50211. this._boundingVectors.push(maxPoint.clone());
  50212. this._boundingVectors[7].y = minPoint.y;
  50213. }
  50214. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50215. // Property
  50216. get: function () {
  50217. return this._capacity;
  50218. },
  50219. enumerable: true,
  50220. configurable: true
  50221. });
  50222. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50223. get: function () {
  50224. return this._minPoint;
  50225. },
  50226. enumerable: true,
  50227. configurable: true
  50228. });
  50229. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50230. get: function () {
  50231. return this._maxPoint;
  50232. },
  50233. enumerable: true,
  50234. configurable: true
  50235. });
  50236. // Methods
  50237. OctreeBlock.prototype.addEntry = function (entry) {
  50238. if (this.blocks) {
  50239. for (var index = 0; index < this.blocks.length; index++) {
  50240. var block = this.blocks[index];
  50241. block.addEntry(entry);
  50242. }
  50243. return;
  50244. }
  50245. this._creationFunc(entry, this);
  50246. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  50247. this.createInnerBlocks();
  50248. }
  50249. };
  50250. OctreeBlock.prototype.addEntries = function (entries) {
  50251. for (var index = 0; index < entries.length; index++) {
  50252. var mesh = entries[index];
  50253. this.addEntry(mesh);
  50254. }
  50255. };
  50256. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  50257. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  50258. if (this.blocks) {
  50259. for (var index = 0; index < this.blocks.length; index++) {
  50260. var block = this.blocks[index];
  50261. block.select(frustumPlanes, selection, allowDuplicate);
  50262. }
  50263. return;
  50264. }
  50265. if (allowDuplicate) {
  50266. selection.concat(this.entries);
  50267. }
  50268. else {
  50269. selection.concatWithNoDuplicate(this.entries);
  50270. }
  50271. }
  50272. };
  50273. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  50274. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  50275. if (this.blocks) {
  50276. for (var index = 0; index < this.blocks.length; index++) {
  50277. var block = this.blocks[index];
  50278. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  50279. }
  50280. return;
  50281. }
  50282. if (allowDuplicate) {
  50283. selection.concat(this.entries);
  50284. }
  50285. else {
  50286. selection.concatWithNoDuplicate(this.entries);
  50287. }
  50288. }
  50289. };
  50290. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  50291. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  50292. if (this.blocks) {
  50293. for (var index = 0; index < this.blocks.length; index++) {
  50294. var block = this.blocks[index];
  50295. block.intersectsRay(ray, selection);
  50296. }
  50297. return;
  50298. }
  50299. selection.concatWithNoDuplicate(this.entries);
  50300. }
  50301. };
  50302. OctreeBlock.prototype.createInnerBlocks = function () {
  50303. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  50304. };
  50305. return OctreeBlock;
  50306. }());
  50307. BABYLON.OctreeBlock = OctreeBlock;
  50308. })(BABYLON || (BABYLON = {}));
  50309. //# sourceMappingURL=babylon.octreeBlock.js.map
  50310. var BABYLON;
  50311. (function (BABYLON) {
  50312. var BlurPostProcess = (function (_super) {
  50313. __extends(BlurPostProcess, _super);
  50314. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  50315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50316. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  50317. _this.direction = direction;
  50318. _this.blurWidth = blurWidth;
  50319. _this.onApplyObservable.add(function (effect) {
  50320. effect.setFloat2("screenSize", _this.width, _this.height);
  50321. effect.setVector2("direction", _this.direction);
  50322. effect.setFloat("blurWidth", _this.blurWidth);
  50323. });
  50324. return _this;
  50325. }
  50326. return BlurPostProcess;
  50327. }(BABYLON.PostProcess));
  50328. BABYLON.BlurPostProcess = BlurPostProcess;
  50329. })(BABYLON || (BABYLON = {}));
  50330. //# sourceMappingURL=babylon.blurPostProcess.js.map
  50331. var BABYLON;
  50332. (function (BABYLON) {
  50333. var RefractionPostProcess = (function (_super) {
  50334. __extends(RefractionPostProcess, _super);
  50335. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50336. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50337. _this.color = color;
  50338. _this.depth = depth;
  50339. _this.colorLevel = colorLevel;
  50340. _this.onActivateObservable.add(function (cam) {
  50341. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50342. });
  50343. _this.onApplyObservable.add(function (effect) {
  50344. effect.setColor3("baseColor", _this.color);
  50345. effect.setFloat("depth", _this.depth);
  50346. effect.setFloat("colorLevel", _this.colorLevel);
  50347. effect.setTexture("refractionSampler", _this._refRexture);
  50348. });
  50349. return _this;
  50350. }
  50351. // Methods
  50352. RefractionPostProcess.prototype.dispose = function (camera) {
  50353. if (this._refRexture) {
  50354. this._refRexture.dispose();
  50355. }
  50356. _super.prototype.dispose.call(this, camera);
  50357. };
  50358. return RefractionPostProcess;
  50359. }(BABYLON.PostProcess));
  50360. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50361. })(BABYLON || (BABYLON = {}));
  50362. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50363. var BABYLON;
  50364. (function (BABYLON) {
  50365. var BlackAndWhitePostProcess = (function (_super) {
  50366. __extends(BlackAndWhitePostProcess, _super);
  50367. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50368. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  50369. }
  50370. return BlackAndWhitePostProcess;
  50371. }(BABYLON.PostProcess));
  50372. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50373. })(BABYLON || (BABYLON = {}));
  50374. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50375. var BABYLON;
  50376. (function (BABYLON) {
  50377. var ConvolutionPostProcess = (function (_super) {
  50378. __extends(ConvolutionPostProcess, _super);
  50379. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50380. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50381. _this.kernel = kernel;
  50382. _this.onApply = function (effect) {
  50383. effect.setFloat2("screenSize", _this.width, _this.height);
  50384. effect.setArray("kernel", _this.kernel);
  50385. };
  50386. return _this;
  50387. }
  50388. return ConvolutionPostProcess;
  50389. }(BABYLON.PostProcess));
  50390. // Statics
  50391. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50392. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50393. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50394. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50395. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50396. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50397. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50398. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50399. })(BABYLON || (BABYLON = {}));
  50400. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50401. var BABYLON;
  50402. (function (BABYLON) {
  50403. var FilterPostProcess = (function (_super) {
  50404. __extends(FilterPostProcess, _super);
  50405. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50406. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50407. _this.kernelMatrix = kernelMatrix;
  50408. _this.onApply = function (effect) {
  50409. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50410. };
  50411. return _this;
  50412. }
  50413. return FilterPostProcess;
  50414. }(BABYLON.PostProcess));
  50415. BABYLON.FilterPostProcess = FilterPostProcess;
  50416. })(BABYLON || (BABYLON = {}));
  50417. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50418. var BABYLON;
  50419. (function (BABYLON) {
  50420. var FxaaPostProcess = (function (_super) {
  50421. __extends(FxaaPostProcess, _super);
  50422. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50423. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  50424. _this.onSizeChangedObservable.add(function () {
  50425. _this.texelWidth = 1.0 / _this.width;
  50426. _this.texelHeight = 1.0 / _this.height;
  50427. });
  50428. _this.onApplyObservable.add(function (effect) {
  50429. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50430. });
  50431. return _this;
  50432. }
  50433. return FxaaPostProcess;
  50434. }(BABYLON.PostProcess));
  50435. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50436. })(BABYLON || (BABYLON = {}));
  50437. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50438. var BABYLON;
  50439. (function (BABYLON) {
  50440. var StereoscopicInterlacePostProcess = (function (_super) {
  50441. __extends(StereoscopicInterlacePostProcess, _super);
  50442. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  50443. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  50444. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50445. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50446. _this.onSizeChangedObservable.add(function () {
  50447. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50448. });
  50449. _this.onApplyObservable.add(function (effect) {
  50450. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  50451. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  50452. });
  50453. return _this;
  50454. }
  50455. return StereoscopicInterlacePostProcess;
  50456. }(BABYLON.PostProcess));
  50457. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  50458. })(BABYLON || (BABYLON = {}));
  50459. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  50460. var BABYLON;
  50461. (function (BABYLON) {
  50462. var LensFlare = (function () {
  50463. function LensFlare(size, position, color, imgUrl, system) {
  50464. this.size = size;
  50465. this.position = position;
  50466. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  50467. this.dispose = function () {
  50468. if (this.texture) {
  50469. this.texture.dispose();
  50470. }
  50471. // Remove from scene
  50472. var index = this._system.lensFlares.indexOf(this);
  50473. this._system.lensFlares.splice(index, 1);
  50474. };
  50475. this.color = color || new BABYLON.Color3(1, 1, 1);
  50476. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  50477. this._system = system;
  50478. system.lensFlares.push(this);
  50479. }
  50480. return LensFlare;
  50481. }());
  50482. BABYLON.LensFlare = LensFlare;
  50483. })(BABYLON || (BABYLON = {}));
  50484. //# sourceMappingURL=babylon.lensFlare.js.map
  50485. var BABYLON;
  50486. (function (BABYLON) {
  50487. var LensFlareSystem = (function () {
  50488. function LensFlareSystem(name, emitter, scene) {
  50489. this.name = name;
  50490. this.lensFlares = new Array();
  50491. this.borderLimit = 300;
  50492. this.viewportBorder = 0;
  50493. this.layerMask = 0x0FFFFFFF;
  50494. this._vertexBuffers = {};
  50495. this._isEnabled = true;
  50496. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50497. this._emitter = emitter;
  50498. this.id = name;
  50499. scene.lensFlareSystems.push(this);
  50500. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  50501. var engine = scene.getEngine();
  50502. // VBO
  50503. var vertices = [];
  50504. vertices.push(1, 1);
  50505. vertices.push(-1, 1);
  50506. vertices.push(-1, -1);
  50507. vertices.push(1, -1);
  50508. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50509. // Indices
  50510. var indices = [];
  50511. indices.push(0);
  50512. indices.push(1);
  50513. indices.push(2);
  50514. indices.push(0);
  50515. indices.push(2);
  50516. indices.push(3);
  50517. this._indexBuffer = engine.createIndexBuffer(indices);
  50518. // Effects
  50519. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  50520. }
  50521. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  50522. get: function () {
  50523. return this._isEnabled;
  50524. },
  50525. set: function (value) {
  50526. this._isEnabled = value;
  50527. },
  50528. enumerable: true,
  50529. configurable: true
  50530. });
  50531. LensFlareSystem.prototype.getScene = function () {
  50532. return this._scene;
  50533. };
  50534. LensFlareSystem.prototype.getEmitter = function () {
  50535. return this._emitter;
  50536. };
  50537. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  50538. this._emitter = newEmitter;
  50539. };
  50540. LensFlareSystem.prototype.getEmitterPosition = function () {
  50541. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  50542. };
  50543. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  50544. var position = this.getEmitterPosition();
  50545. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  50546. this._positionX = position.x;
  50547. this._positionY = position.y;
  50548. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  50549. if (this.viewportBorder > 0) {
  50550. globalViewport.x -= this.viewportBorder;
  50551. globalViewport.y -= this.viewportBorder;
  50552. globalViewport.width += this.viewportBorder * 2;
  50553. globalViewport.height += this.viewportBorder * 2;
  50554. position.x += this.viewportBorder;
  50555. position.y += this.viewportBorder;
  50556. this._positionX += this.viewportBorder;
  50557. this._positionY += this.viewportBorder;
  50558. }
  50559. if (position.z > 0) {
  50560. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  50561. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  50562. return true;
  50563. }
  50564. return true;
  50565. }
  50566. return false;
  50567. };
  50568. LensFlareSystem.prototype._isVisible = function () {
  50569. if (!this._isEnabled) {
  50570. return false;
  50571. }
  50572. var emitterPosition = this.getEmitterPosition();
  50573. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  50574. var distance = direction.length();
  50575. direction.normalize();
  50576. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  50577. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  50578. return !pickInfo.hit || pickInfo.distance > distance;
  50579. };
  50580. LensFlareSystem.prototype.render = function () {
  50581. if (!this._effect.isReady())
  50582. return false;
  50583. var engine = this._scene.getEngine();
  50584. var viewport = this._scene.activeCamera.viewport;
  50585. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  50586. // Position
  50587. if (!this.computeEffectivePosition(globalViewport)) {
  50588. return false;
  50589. }
  50590. // Visibility
  50591. if (!this._isVisible()) {
  50592. return false;
  50593. }
  50594. // Intensity
  50595. var awayX;
  50596. var awayY;
  50597. if (this._positionX < this.borderLimit + globalViewport.x) {
  50598. awayX = this.borderLimit + globalViewport.x - this._positionX;
  50599. }
  50600. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  50601. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  50602. }
  50603. else {
  50604. awayX = 0;
  50605. }
  50606. if (this._positionY < this.borderLimit + globalViewport.y) {
  50607. awayY = this.borderLimit + globalViewport.y - this._positionY;
  50608. }
  50609. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  50610. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  50611. }
  50612. else {
  50613. awayY = 0;
  50614. }
  50615. var away = (awayX > awayY) ? awayX : awayY;
  50616. away -= this.viewportBorder;
  50617. if (away > this.borderLimit) {
  50618. away = this.borderLimit;
  50619. }
  50620. var intensity = 1.0 - (away / this.borderLimit);
  50621. if (intensity < 0) {
  50622. return false;
  50623. }
  50624. if (intensity > 1.0) {
  50625. intensity = 1.0;
  50626. }
  50627. if (this.viewportBorder > 0) {
  50628. globalViewport.x += this.viewportBorder;
  50629. globalViewport.y += this.viewportBorder;
  50630. globalViewport.width -= this.viewportBorder * 2;
  50631. globalViewport.height -= this.viewportBorder * 2;
  50632. this._positionX -= this.viewportBorder;
  50633. this._positionY -= this.viewportBorder;
  50634. }
  50635. // Position
  50636. var centerX = globalViewport.x + globalViewport.width / 2;
  50637. var centerY = globalViewport.y + globalViewport.height / 2;
  50638. var distX = centerX - this._positionX;
  50639. var distY = centerY - this._positionY;
  50640. // Effects
  50641. engine.enableEffect(this._effect);
  50642. engine.setState(false);
  50643. engine.setDepthBuffer(false);
  50644. // VBOs
  50645. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50646. // Flares
  50647. for (var index = 0; index < this.lensFlares.length; index++) {
  50648. var flare = this.lensFlares[index];
  50649. engine.setAlphaMode(flare.alphaMode);
  50650. var x = centerX - (distX * flare.position);
  50651. var y = centerY - (distY * flare.position);
  50652. var cw = flare.size;
  50653. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  50654. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  50655. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  50656. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  50657. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  50658. // Texture
  50659. this._effect.setTexture("textureSampler", flare.texture);
  50660. // Color
  50661. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  50662. // Draw order
  50663. engine.draw(true, 0, 6);
  50664. }
  50665. engine.setDepthBuffer(true);
  50666. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50667. return true;
  50668. };
  50669. LensFlareSystem.prototype.dispose = function () {
  50670. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50671. if (vertexBuffer) {
  50672. vertexBuffer.dispose();
  50673. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50674. }
  50675. if (this._indexBuffer) {
  50676. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50677. this._indexBuffer = null;
  50678. }
  50679. while (this.lensFlares.length) {
  50680. this.lensFlares[0].dispose();
  50681. }
  50682. // Remove from scene
  50683. var index = this._scene.lensFlareSystems.indexOf(this);
  50684. this._scene.lensFlareSystems.splice(index, 1);
  50685. };
  50686. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  50687. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  50688. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  50689. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  50690. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  50691. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  50692. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  50693. var parsedFlare = parsedLensFlareSystem.flares[index];
  50694. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  50695. }
  50696. return lensFlareSystem;
  50697. };
  50698. LensFlareSystem.prototype.serialize = function () {
  50699. var serializationObject = {};
  50700. serializationObject.id = this.id;
  50701. serializationObject.name = this.name;
  50702. serializationObject.emitterId = this.getEmitter().id;
  50703. serializationObject.borderLimit = this.borderLimit;
  50704. serializationObject.flares = [];
  50705. for (var index = 0; index < this.lensFlares.length; index++) {
  50706. var flare = this.lensFlares[index];
  50707. serializationObject.flares.push({
  50708. size: flare.size,
  50709. position: flare.position,
  50710. color: flare.color.asArray(),
  50711. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  50712. });
  50713. }
  50714. return serializationObject;
  50715. };
  50716. return LensFlareSystem;
  50717. }());
  50718. BABYLON.LensFlareSystem = LensFlareSystem;
  50719. })(BABYLON || (BABYLON = {}));
  50720. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  50721. /// <reference path="babylon.freeCamera.ts" />
  50722. var BABYLON;
  50723. (function (BABYLON) {
  50724. // We're mainly based on the logic defined into the FreeCamera code
  50725. var DeviceOrientationCamera = (function (_super) {
  50726. __extends(DeviceOrientationCamera, _super);
  50727. function DeviceOrientationCamera(name, position, scene) {
  50728. var _this = _super.call(this, name, position, scene) || this;
  50729. _this._quaternionCache = new BABYLON.Quaternion();
  50730. _this.inputs.addDeviceOrientation();
  50731. return _this;
  50732. }
  50733. DeviceOrientationCamera.prototype.getClassName = function () {
  50734. return "DeviceOrientationCamera";
  50735. };
  50736. DeviceOrientationCamera.prototype._checkInputs = function () {
  50737. _super.prototype._checkInputs.call(this);
  50738. this._quaternionCache.copyFrom(this.rotationQuaternion);
  50739. if (this._initialQuaternion) {
  50740. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50741. }
  50742. };
  50743. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  50744. var _this = this;
  50745. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  50746. //can only work if this camera has a rotation quaternion already.
  50747. if (!this.rotationQuaternion)
  50748. return;
  50749. if (!this._initialQuaternion) {
  50750. this._initialQuaternion = new BABYLON.Quaternion();
  50751. }
  50752. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  50753. ['x', 'y', 'z'].forEach(function (axisName) {
  50754. if (!axis[axisName]) {
  50755. _this._initialQuaternion[axisName] = 0;
  50756. }
  50757. else {
  50758. _this._initialQuaternion[axisName] *= -1;
  50759. }
  50760. });
  50761. this._initialQuaternion.normalize();
  50762. //force rotation update
  50763. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50764. };
  50765. return DeviceOrientationCamera;
  50766. }(BABYLON.FreeCamera));
  50767. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  50768. })(BABYLON || (BABYLON = {}));
  50769. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  50770. var BABYLON;
  50771. (function (BABYLON) {
  50772. var VRDeviceOrientationFreeCamera = (function (_super) {
  50773. __extends(VRDeviceOrientationFreeCamera, _super);
  50774. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50775. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50776. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50777. var _this = _super.call(this, name, position, scene) || this;
  50778. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50779. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50780. return _this;
  50781. }
  50782. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  50783. return "VRDeviceOrientationFreeCamera";
  50784. };
  50785. return VRDeviceOrientationFreeCamera;
  50786. }(BABYLON.DeviceOrientationCamera));
  50787. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50788. var VRDeviceOrientationGamepadCamera = (function (_super) {
  50789. __extends(VRDeviceOrientationGamepadCamera, _super);
  50790. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50791. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50792. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50793. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  50794. _this.inputs.addGamepad();
  50795. return _this;
  50796. }
  50797. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  50798. return "VRDeviceOrientationGamepadCamera";
  50799. };
  50800. return VRDeviceOrientationGamepadCamera;
  50801. }(VRDeviceOrientationFreeCamera));
  50802. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  50803. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50804. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50805. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  50806. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50807. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50808. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  50809. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50810. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50811. _this.inputs.addVRDeviceOrientation();
  50812. return _this;
  50813. }
  50814. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  50815. return "VRDeviceOrientationArcRotateCamera";
  50816. };
  50817. return VRDeviceOrientationArcRotateCamera;
  50818. }(BABYLON.ArcRotateCamera));
  50819. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50820. })(BABYLON || (BABYLON = {}));
  50821. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  50822. /// <reference path="babylon.touchCamera.ts" />
  50823. var BABYLON;
  50824. (function (BABYLON) {
  50825. // We're mainly based on the logic defined into the FreeCamera code
  50826. var UniversalCamera = (function (_super) {
  50827. __extends(UniversalCamera, _super);
  50828. //-- end properties for backward compatibility for inputs
  50829. function UniversalCamera(name, position, scene) {
  50830. var _this = _super.call(this, name, position, scene) || this;
  50831. _this.inputs.addGamepad();
  50832. return _this;
  50833. }
  50834. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50835. //-- Begin properties for backward compatibility for inputs
  50836. get: function () {
  50837. var gamepad = this.inputs.attached["gamepad"];
  50838. if (gamepad)
  50839. return gamepad.gamepadAngularSensibility;
  50840. },
  50841. set: function (value) {
  50842. var gamepad = this.inputs.attached["gamepad"];
  50843. if (gamepad)
  50844. gamepad.gamepadAngularSensibility = value;
  50845. },
  50846. enumerable: true,
  50847. configurable: true
  50848. });
  50849. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50850. get: function () {
  50851. var gamepad = this.inputs.attached["gamepad"];
  50852. if (gamepad)
  50853. return gamepad.gamepadMoveSensibility;
  50854. },
  50855. set: function (value) {
  50856. var gamepad = this.inputs.attached["gamepad"];
  50857. if (gamepad)
  50858. gamepad.gamepadMoveSensibility = value;
  50859. },
  50860. enumerable: true,
  50861. configurable: true
  50862. });
  50863. UniversalCamera.prototype.getClassName = function () {
  50864. return "UniversalCamera";
  50865. };
  50866. return UniversalCamera;
  50867. }(BABYLON.TouchCamera));
  50868. BABYLON.UniversalCamera = UniversalCamera;
  50869. })(BABYLON || (BABYLON = {}));
  50870. //# sourceMappingURL=babylon.universalCamera.js.map
  50871. var BABYLON;
  50872. (function (BABYLON) {
  50873. var Gamepads = (function () {
  50874. function Gamepads(ongamedpadconnected) {
  50875. var _this = this;
  50876. this.babylonGamepads = [];
  50877. this.oneGamepadConnected = false;
  50878. this.isMonitoring = false;
  50879. this.gamepadEventSupported = 'GamepadEvent' in window;
  50880. this.gamepadSupport = (navigator.getGamepads ||
  50881. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50882. this._callbackGamepadConnected = ongamedpadconnected;
  50883. if (this.gamepadSupport) {
  50884. //first add already-connected gamepads
  50885. this._updateGamepadObjects();
  50886. if (this.babylonGamepads.length) {
  50887. this._startMonitoringGamepads();
  50888. }
  50889. // Checking if the gamepad connected event is supported (like in Firefox)
  50890. if (this.gamepadEventSupported) {
  50891. this._onGamepadConnectedEvent = function (evt) {
  50892. _this._onGamepadConnected(evt.gamepad);
  50893. };
  50894. this._onGamepadDisonnectedEvent = function (evt) {
  50895. _this._onGamepadDisconnected(evt);
  50896. };
  50897. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50898. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50899. }
  50900. else {
  50901. this._startMonitoringGamepads();
  50902. }
  50903. }
  50904. }
  50905. Gamepads.prototype.dispose = function () {
  50906. if (Gamepads.gamepadDOMInfo) {
  50907. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50908. }
  50909. if (this._onGamepadConnectedEvent) {
  50910. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50911. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50912. this._onGamepadConnectedEvent = null;
  50913. this._onGamepadDisonnectedEvent = null;
  50914. }
  50915. };
  50916. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  50917. var newGamepad = this._addNewGamepad(gamepad);
  50918. if (this._callbackGamepadConnected)
  50919. this._callbackGamepadConnected(newGamepad);
  50920. this._startMonitoringGamepads();
  50921. };
  50922. Gamepads.prototype._addNewGamepad = function (gamepad) {
  50923. if (!this.oneGamepadConnected) {
  50924. this.oneGamepadConnected = true;
  50925. if (Gamepads.gamepadDOMInfo) {
  50926. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50927. Gamepads.gamepadDOMInfo = null;
  50928. }
  50929. }
  50930. var newGamepad;
  50931. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50932. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50933. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50934. }
  50935. else if (gamepad.pose) {
  50936. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50937. }
  50938. else {
  50939. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  50940. }
  50941. this.babylonGamepads.push(newGamepad);
  50942. return newGamepad;
  50943. };
  50944. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  50945. // Remove the gamepad from the list of gamepads to monitor.
  50946. for (var i in this.babylonGamepads) {
  50947. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  50948. this.babylonGamepads.splice(+i, 1);
  50949. break;
  50950. }
  50951. }
  50952. // If no gamepads are left, stop the polling loop.
  50953. if (this.babylonGamepads.length == 0) {
  50954. this._stopMonitoringGamepads();
  50955. }
  50956. };
  50957. Gamepads.prototype._startMonitoringGamepads = function () {
  50958. if (!this.isMonitoring) {
  50959. this.isMonitoring = true;
  50960. this._checkGamepadsStatus();
  50961. }
  50962. };
  50963. Gamepads.prototype._stopMonitoringGamepads = function () {
  50964. this.isMonitoring = false;
  50965. };
  50966. Gamepads.prototype._checkGamepadsStatus = function () {
  50967. var _this = this;
  50968. // updating gamepad objects
  50969. this._updateGamepadObjects();
  50970. for (var i in this.babylonGamepads) {
  50971. this.babylonGamepads[i].update();
  50972. }
  50973. if (this.isMonitoring) {
  50974. if (window.requestAnimationFrame) {
  50975. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50976. }
  50977. else if (window.mozRequestAnimationFrame) {
  50978. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50979. }
  50980. else if (window.webkitRequestAnimationFrame) {
  50981. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50982. }
  50983. }
  50984. };
  50985. // This function is called only on Chrome, which does not yet support
  50986. // connection/disconnection events, but requires you to monitor
  50987. // an array for changes.
  50988. Gamepads.prototype._updateGamepadObjects = function () {
  50989. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50990. for (var i = 0; i < gamepads.length; i++) {
  50991. if (gamepads[i]) {
  50992. if (!(gamepads[i].index in this.babylonGamepads)) {
  50993. var newGamepad = this._addNewGamepad(gamepads[i]);
  50994. if (this._callbackGamepadConnected) {
  50995. this._callbackGamepadConnected(newGamepad);
  50996. }
  50997. }
  50998. else {
  50999. this.babylonGamepads[i].browserGamepad = gamepads[i];
  51000. }
  51001. }
  51002. }
  51003. };
  51004. return Gamepads;
  51005. }());
  51006. BABYLON.Gamepads = Gamepads;
  51007. var StickValues = (function () {
  51008. function StickValues(x, y) {
  51009. this.x = x;
  51010. this.y = y;
  51011. }
  51012. return StickValues;
  51013. }());
  51014. BABYLON.StickValues = StickValues;
  51015. var Gamepad = (function () {
  51016. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51017. if (leftStickX === void 0) { leftStickX = 0; }
  51018. if (leftStickY === void 0) { leftStickY = 1; }
  51019. if (rightStickX === void 0) { rightStickX = 2; }
  51020. if (rightStickY === void 0) { rightStickY = 3; }
  51021. this.id = id;
  51022. this.index = index;
  51023. this.browserGamepad = browserGamepad;
  51024. this.type = Gamepad.GAMEPAD;
  51025. this._leftStickAxisX = leftStickX;
  51026. this._leftStickAxisY = leftStickY;
  51027. this._rightStickAxisX = rightStickX;
  51028. this._rightStickAxisY = rightStickY;
  51029. if (this.browserGamepad.axes.length >= 2) {
  51030. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51031. }
  51032. if (this.browserGamepad.axes.length >= 4) {
  51033. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51034. }
  51035. }
  51036. Gamepad.prototype.onleftstickchanged = function (callback) {
  51037. this._onleftstickchanged = callback;
  51038. };
  51039. Gamepad.prototype.onrightstickchanged = function (callback) {
  51040. this._onrightstickchanged = callback;
  51041. };
  51042. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51043. get: function () {
  51044. return this._leftStick;
  51045. },
  51046. set: function (newValues) {
  51047. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51048. this._onleftstickchanged(newValues);
  51049. }
  51050. this._leftStick = newValues;
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51056. get: function () {
  51057. return this._rightStick;
  51058. },
  51059. set: function (newValues) {
  51060. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51061. this._onrightstickchanged(newValues);
  51062. }
  51063. this._rightStick = newValues;
  51064. },
  51065. enumerable: true,
  51066. configurable: true
  51067. });
  51068. Gamepad.prototype.update = function () {
  51069. if (this._leftStick) {
  51070. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51071. }
  51072. if (this._rightStick) {
  51073. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51074. }
  51075. };
  51076. return Gamepad;
  51077. }());
  51078. Gamepad.GAMEPAD = 0;
  51079. Gamepad.GENERIC = 1;
  51080. Gamepad.XBOX = 2;
  51081. Gamepad.POSE_ENABLED = 3;
  51082. BABYLON.Gamepad = Gamepad;
  51083. var GenericPad = (function (_super) {
  51084. __extends(GenericPad, _super);
  51085. function GenericPad(id, index, gamepad) {
  51086. var _this = _super.call(this, id, index, gamepad) || this;
  51087. _this.id = id;
  51088. _this.index = index;
  51089. _this.gamepad = gamepad;
  51090. _this.type = Gamepad.GENERIC;
  51091. _this._buttons = new Array(gamepad.buttons.length);
  51092. return _this;
  51093. }
  51094. GenericPad.prototype.onbuttondown = function (callback) {
  51095. this._onbuttondown = callback;
  51096. };
  51097. GenericPad.prototype.onbuttonup = function (callback) {
  51098. this._onbuttonup = callback;
  51099. };
  51100. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51101. if (newValue !== currentValue) {
  51102. if (this._onbuttondown && newValue === 1) {
  51103. this._onbuttondown(buttonIndex);
  51104. }
  51105. if (this._onbuttonup && newValue === 0) {
  51106. this._onbuttonup(buttonIndex);
  51107. }
  51108. }
  51109. return newValue;
  51110. };
  51111. GenericPad.prototype.update = function () {
  51112. _super.prototype.update.call(this);
  51113. for (var index = 0; index < this._buttons.length; index++) {
  51114. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51115. }
  51116. };
  51117. return GenericPad;
  51118. }(Gamepad));
  51119. BABYLON.GenericPad = GenericPad;
  51120. var Xbox360Button;
  51121. (function (Xbox360Button) {
  51122. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51123. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51124. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51125. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51126. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51127. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51128. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51129. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51130. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51131. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51132. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51133. var Xbox360Dpad;
  51134. (function (Xbox360Dpad) {
  51135. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51136. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51137. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51138. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51139. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51140. var Xbox360Pad = (function (_super) {
  51141. __extends(Xbox360Pad, _super);
  51142. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51143. if (xboxOne === void 0) { xboxOne = false; }
  51144. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51145. _this._leftTrigger = 0;
  51146. _this._rightTrigger = 0;
  51147. _this._buttonA = 0;
  51148. _this._buttonB = 0;
  51149. _this._buttonX = 0;
  51150. _this._buttonY = 0;
  51151. _this._buttonBack = 0;
  51152. _this._buttonStart = 0;
  51153. _this._buttonLB = 0;
  51154. _this._buttonRB = 0;
  51155. _this._buttonLeftStick = 0;
  51156. _this._buttonRightStick = 0;
  51157. _this._dPadUp = 0;
  51158. _this._dPadDown = 0;
  51159. _this._dPadLeft = 0;
  51160. _this._dPadRight = 0;
  51161. _this._isXboxOnePad = false;
  51162. _this.type = Gamepad.XBOX;
  51163. _this._isXboxOnePad = xboxOne;
  51164. return _this;
  51165. }
  51166. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51167. this._onlefttriggerchanged = callback;
  51168. };
  51169. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51170. this._onrighttriggerchanged = callback;
  51171. };
  51172. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51173. get: function () {
  51174. return this._leftTrigger;
  51175. },
  51176. set: function (newValue) {
  51177. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51178. this._onlefttriggerchanged(newValue);
  51179. }
  51180. this._leftTrigger = newValue;
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51186. get: function () {
  51187. return this._rightTrigger;
  51188. },
  51189. set: function (newValue) {
  51190. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51191. this._onrighttriggerchanged(newValue);
  51192. }
  51193. this._rightTrigger = newValue;
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51199. this._onbuttondown = callback;
  51200. };
  51201. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51202. this._onbuttonup = callback;
  51203. };
  51204. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51205. this._ondpaddown = callback;
  51206. };
  51207. Xbox360Pad.prototype.ondpadup = function (callback) {
  51208. this._ondpadup = callback;
  51209. };
  51210. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51211. if (newValue !== currentValue) {
  51212. if (this._onbuttondown && newValue === 1) {
  51213. this._onbuttondown(buttonType);
  51214. }
  51215. if (this._onbuttonup && newValue === 0) {
  51216. this._onbuttonup(buttonType);
  51217. }
  51218. }
  51219. return newValue;
  51220. };
  51221. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51222. if (newValue !== currentValue) {
  51223. if (this._ondpaddown && newValue === 1) {
  51224. this._ondpaddown(buttonType);
  51225. }
  51226. if (this._ondpadup && newValue === 0) {
  51227. this._ondpadup(buttonType);
  51228. }
  51229. }
  51230. return newValue;
  51231. };
  51232. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51233. get: function () {
  51234. return this._buttonA;
  51235. },
  51236. set: function (value) {
  51237. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51238. },
  51239. enumerable: true,
  51240. configurable: true
  51241. });
  51242. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51243. get: function () {
  51244. return this._buttonB;
  51245. },
  51246. set: function (value) {
  51247. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51248. },
  51249. enumerable: true,
  51250. configurable: true
  51251. });
  51252. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51253. get: function () {
  51254. return this._buttonX;
  51255. },
  51256. set: function (value) {
  51257. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51258. },
  51259. enumerable: true,
  51260. configurable: true
  51261. });
  51262. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51263. get: function () {
  51264. return this._buttonY;
  51265. },
  51266. set: function (value) {
  51267. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51268. },
  51269. enumerable: true,
  51270. configurable: true
  51271. });
  51272. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51273. get: function () {
  51274. return this._buttonStart;
  51275. },
  51276. set: function (value) {
  51277. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51278. },
  51279. enumerable: true,
  51280. configurable: true
  51281. });
  51282. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51283. get: function () {
  51284. return this._buttonBack;
  51285. },
  51286. set: function (value) {
  51287. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51288. },
  51289. enumerable: true,
  51290. configurable: true
  51291. });
  51292. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51293. get: function () {
  51294. return this._buttonLB;
  51295. },
  51296. set: function (value) {
  51297. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51298. },
  51299. enumerable: true,
  51300. configurable: true
  51301. });
  51302. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51303. get: function () {
  51304. return this._buttonRB;
  51305. },
  51306. set: function (value) {
  51307. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51308. },
  51309. enumerable: true,
  51310. configurable: true
  51311. });
  51312. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51313. get: function () {
  51314. return this._buttonLeftStick;
  51315. },
  51316. set: function (value) {
  51317. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51323. get: function () {
  51324. return this._buttonRightStick;
  51325. },
  51326. set: function (value) {
  51327. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51328. },
  51329. enumerable: true,
  51330. configurable: true
  51331. });
  51332. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51333. get: function () {
  51334. return this._dPadUp;
  51335. },
  51336. set: function (value) {
  51337. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51338. },
  51339. enumerable: true,
  51340. configurable: true
  51341. });
  51342. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51343. get: function () {
  51344. return this._dPadDown;
  51345. },
  51346. set: function (value) {
  51347. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51348. },
  51349. enumerable: true,
  51350. configurable: true
  51351. });
  51352. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51353. get: function () {
  51354. return this._dPadLeft;
  51355. },
  51356. set: function (value) {
  51357. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51358. },
  51359. enumerable: true,
  51360. configurable: true
  51361. });
  51362. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51363. get: function () {
  51364. return this._dPadRight;
  51365. },
  51366. set: function (value) {
  51367. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51368. },
  51369. enumerable: true,
  51370. configurable: true
  51371. });
  51372. Xbox360Pad.prototype.update = function () {
  51373. _super.prototype.update.call(this);
  51374. if (this._isXboxOnePad) {
  51375. this.buttonA = this.browserGamepad.buttons[0].value;
  51376. this.buttonB = this.browserGamepad.buttons[1].value;
  51377. this.buttonX = this.browserGamepad.buttons[2].value;
  51378. this.buttonY = this.browserGamepad.buttons[3].value;
  51379. this.buttonLB = this.browserGamepad.buttons[4].value;
  51380. this.buttonRB = this.browserGamepad.buttons[5].value;
  51381. this.leftTrigger = this.browserGamepad.axes[2];
  51382. this.rightTrigger = this.browserGamepad.axes[5];
  51383. this.buttonBack = this.browserGamepad.buttons[9].value;
  51384. this.buttonStart = this.browserGamepad.buttons[8].value;
  51385. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51386. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51387. this.dPadUp = this.browserGamepad.buttons[11].value;
  51388. this.dPadDown = this.browserGamepad.buttons[12].value;
  51389. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51390. this.dPadRight = this.browserGamepad.buttons[14].value;
  51391. }
  51392. else {
  51393. this.buttonA = this.browserGamepad.buttons[0].value;
  51394. this.buttonB = this.browserGamepad.buttons[1].value;
  51395. this.buttonX = this.browserGamepad.buttons[2].value;
  51396. this.buttonY = this.browserGamepad.buttons[3].value;
  51397. this.buttonLB = this.browserGamepad.buttons[4].value;
  51398. this.buttonRB = this.browserGamepad.buttons[5].value;
  51399. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51400. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51401. this.buttonBack = this.browserGamepad.buttons[8].value;
  51402. this.buttonStart = this.browserGamepad.buttons[9].value;
  51403. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51404. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51405. this.dPadUp = this.browserGamepad.buttons[12].value;
  51406. this.dPadDown = this.browserGamepad.buttons[13].value;
  51407. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51408. this.dPadRight = this.browserGamepad.buttons[15].value;
  51409. }
  51410. };
  51411. return Xbox360Pad;
  51412. }(Gamepad));
  51413. BABYLON.Xbox360Pad = Xbox360Pad;
  51414. })(BABYLON || (BABYLON = {}));
  51415. //# sourceMappingURL=babylon.gamepads.js.map
  51416. var BABYLON;
  51417. (function (BABYLON) {
  51418. var PoseEnabledControllerType;
  51419. (function (PoseEnabledControllerType) {
  51420. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51421. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51422. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  51423. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51424. var PoseEnabledControllerHelper = (function () {
  51425. function PoseEnabledControllerHelper() {
  51426. }
  51427. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51428. // for now, only Oculus and Vive are supported
  51429. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51430. return new OculusTouchController(vrGamepad);
  51431. }
  51432. else {
  51433. return new ViveController(vrGamepad);
  51434. }
  51435. };
  51436. return PoseEnabledControllerHelper;
  51437. }());
  51438. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51439. var PoseEnabledController = (function (_super) {
  51440. __extends(PoseEnabledController, _super);
  51441. function PoseEnabledController(vrGamepad) {
  51442. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51443. _this.vrGamepad = vrGamepad;
  51444. _this.deviceScaleFactor = 1;
  51445. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51446. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51447. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51448. _this.position = BABYLON.Vector3.Zero();
  51449. _this.rotationQuaternion = new BABYLON.Quaternion();
  51450. _this.devicePosition = BABYLON.Vector3.Zero();
  51451. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51452. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51453. _this._calculatedRotation = new BABYLON.Quaternion();
  51454. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51455. return _this;
  51456. }
  51457. PoseEnabledController.prototype.update = function () {
  51458. _super.prototype.update.call(this);
  51459. // update this device's offset position from the attached camera, if provided
  51460. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  51461. //this.position.copyFrom(this._poseControlledCamera.position);
  51462. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  51463. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  51464. //}
  51465. var pose = this.vrGamepad.pose;
  51466. this.updateFromDevice(pose);
  51467. if (this._mesh) {
  51468. this._mesh.position.copyFrom(this._calculatedPosition);
  51469. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51470. }
  51471. };
  51472. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51473. if (poseData) {
  51474. this.rawPose = poseData;
  51475. if (poseData.position) {
  51476. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51477. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51478. this.devicePosition.z *= -1;
  51479. }
  51480. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51481. this._calculatedPosition.addInPlace(this.position);
  51482. }
  51483. if (poseData.orientation) {
  51484. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51485. if (this._mesh) {
  51486. if (this._mesh.getScene().useRightHandedSystem) {
  51487. this.deviceRotationQuaternion.z *= -1;
  51488. this.deviceRotationQuaternion.w *= -1;
  51489. }
  51490. else {
  51491. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51492. }
  51493. }
  51494. // if the camera is set, rotate to the camera's rotation
  51495. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51496. }
  51497. }
  51498. };
  51499. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51500. if (this._mesh) {
  51501. this._mesh.parent = undefined;
  51502. }
  51503. this._mesh = mesh;
  51504. if (this._poseControlledCamera) {
  51505. this._mesh.parent = this._poseControlledCamera;
  51506. }
  51507. if (!this._mesh.rotationQuaternion) {
  51508. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51509. }
  51510. };
  51511. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51512. this._poseControlledCamera = camera;
  51513. if (this._mesh) {
  51514. this._mesh.parent = this._poseControlledCamera;
  51515. }
  51516. };
  51517. PoseEnabledController.prototype.detachMesh = function () {
  51518. this._mesh = undefined;
  51519. };
  51520. return PoseEnabledController;
  51521. }(BABYLON.Gamepad));
  51522. BABYLON.PoseEnabledController = PoseEnabledController;
  51523. var WebVRController = (function (_super) {
  51524. __extends(WebVRController, _super);
  51525. function WebVRController(vrGamepad) {
  51526. var _this = _super.call(this, vrGamepad) || this;
  51527. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  51528. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51529. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51530. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51531. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51532. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51533. _this.pad = { x: 0, y: 0 };
  51534. // avoid GC, store state in a tmp object
  51535. _this._changes = {
  51536. pressChanged: false,
  51537. touchChanged: false,
  51538. valueChanged: false,
  51539. changed: false
  51540. };
  51541. _this._buttons = new Array(vrGamepad.buttons.length);
  51542. _this.hand = vrGamepad.hand;
  51543. return _this;
  51544. }
  51545. WebVRController.prototype.onButtonStateChange = function (callback) {
  51546. this._onButtonStateChange = callback;
  51547. };
  51548. WebVRController.prototype.update = function () {
  51549. _super.prototype.update.call(this);
  51550. for (var index = 0; index < this._buttons.length; index++) {
  51551. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51552. }
  51553. ;
  51554. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51555. this.pad.x = this.leftStick.x;
  51556. this.pad.y = this.leftStick.y;
  51557. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51558. }
  51559. };
  51560. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51561. if (!currentState) {
  51562. this._buttons[buttonIndex] = {
  51563. pressed: newState.pressed,
  51564. touched: newState.touched,
  51565. value: newState.value
  51566. };
  51567. return;
  51568. }
  51569. this._checkChanges(newState, currentState);
  51570. if (this._changes.changed) {
  51571. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51572. this.handleButtonChange(buttonIndex, newState, this._changes);
  51573. }
  51574. this._buttons[buttonIndex].pressed = newState.pressed;
  51575. this._buttons[buttonIndex].touched = newState.touched;
  51576. // oculus triggers are never 0, thou not touched.
  51577. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51578. };
  51579. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51580. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51581. this._changes.touchChanged = newState.touched !== currentState.touched;
  51582. this._changes.valueChanged = newState.value !== currentState.value;
  51583. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51584. return this._changes;
  51585. };
  51586. return WebVRController;
  51587. }(PoseEnabledController));
  51588. BABYLON.WebVRController = WebVRController;
  51589. var OculusTouchController = (function (_super) {
  51590. __extends(OculusTouchController, _super);
  51591. function OculusTouchController(vrGamepad) {
  51592. var _this = _super.call(this, vrGamepad) || this;
  51593. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51594. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51595. _this.controllerType = PoseEnabledControllerType.OCULUS;
  51596. return _this;
  51597. }
  51598. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51599. var _this = this;
  51600. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51601. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51602. /*
  51603. Parent Mesh name: oculus_touch_left
  51604. - body
  51605. - trigger
  51606. - thumbstick
  51607. - grip
  51608. - button_y
  51609. - button_x
  51610. - button_enter
  51611. */
  51612. _this._defaultModel = newMeshes[1];
  51613. if (meshLoaded) {
  51614. meshLoaded(_this._defaultModel);
  51615. }
  51616. _this.attachToMesh(_this._defaultModel);
  51617. });
  51618. };
  51619. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51620. // helper getters for left and right hand.
  51621. get: function () {
  51622. if (this.hand === 'right') {
  51623. return this.onMainButtonStateChangedObservable;
  51624. }
  51625. else {
  51626. throw new Error('No A button on left hand');
  51627. }
  51628. },
  51629. enumerable: true,
  51630. configurable: true
  51631. });
  51632. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51633. get: function () {
  51634. if (this.hand === 'right') {
  51635. return this.onSecondaryButtonStateChangedObservable;
  51636. }
  51637. else {
  51638. throw new Error('No B button on left hand');
  51639. }
  51640. },
  51641. enumerable: true,
  51642. configurable: true
  51643. });
  51644. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51645. get: function () {
  51646. if (this.hand === 'left') {
  51647. return this.onMainButtonStateChangedObservable;
  51648. }
  51649. else {
  51650. throw new Error('No X button on right hand');
  51651. }
  51652. },
  51653. enumerable: true,
  51654. configurable: true
  51655. });
  51656. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51657. get: function () {
  51658. if (this.hand === 'left') {
  51659. return this.onSecondaryButtonStateChangedObservable;
  51660. }
  51661. else {
  51662. throw new Error('No Y button on right hand');
  51663. }
  51664. },
  51665. enumerable: true,
  51666. configurable: true
  51667. });
  51668. /*
  51669. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51670. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51671. 2) secondary trigger (same)
  51672. 3) A (right) X (left), touch, pressed = value
  51673. 4) B / Y
  51674. 5) thumb rest
  51675. */
  51676. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51677. var notifyObject = state; //{ state: state, changes: changes };
  51678. switch (buttonIdx) {
  51679. case 0:
  51680. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51681. return;
  51682. case 1:
  51683. if (this._defaultModel) {
  51684. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51685. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51686. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51687. }
  51688. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51689. return;
  51690. case 2:
  51691. if (this._defaultModel) {
  51692. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  51693. }
  51694. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51695. return;
  51696. case 3:
  51697. if (this._defaultModel) {
  51698. if (notifyObject.pressed) {
  51699. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51700. }
  51701. else {
  51702. (this._defaultModel.getChildren()[1]).position.y = 0;
  51703. }
  51704. }
  51705. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51706. return;
  51707. case 4:
  51708. if (this._defaultModel) {
  51709. if (notifyObject.pressed) {
  51710. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51711. }
  51712. else {
  51713. (this._defaultModel.getChildren()[2]).position.y = 0;
  51714. }
  51715. }
  51716. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51717. return;
  51718. case 5:
  51719. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51720. return;
  51721. }
  51722. };
  51723. return OculusTouchController;
  51724. }(WebVRController));
  51725. BABYLON.OculusTouchController = OculusTouchController;
  51726. var ViveController = (function (_super) {
  51727. __extends(ViveController, _super);
  51728. function ViveController(vrGamepad) {
  51729. var _this = _super.call(this, vrGamepad) || this;
  51730. _this.controllerType = PoseEnabledControllerType.VIVE;
  51731. return _this;
  51732. }
  51733. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51734. var _this = this;
  51735. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51736. /*
  51737. Parent Mesh name: ViveWand
  51738. - body
  51739. - r_gripper
  51740. - l_gripper
  51741. - menu_button
  51742. - system_button
  51743. - trackpad
  51744. - trigger
  51745. - LED
  51746. */
  51747. _this._defaultModel = newMeshes[1];
  51748. if (meshLoaded) {
  51749. meshLoaded(_this._defaultModel);
  51750. }
  51751. _this.attachToMesh(_this._defaultModel);
  51752. });
  51753. };
  51754. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51755. get: function () {
  51756. return this.onMainButtonStateChangedObservable;
  51757. },
  51758. enumerable: true,
  51759. configurable: true
  51760. });
  51761. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51762. get: function () {
  51763. return this.onMainButtonStateChangedObservable;
  51764. },
  51765. enumerable: true,
  51766. configurable: true
  51767. });
  51768. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51769. get: function () {
  51770. return this.onSecondaryButtonStateChangedObservable;
  51771. },
  51772. enumerable: true,
  51773. configurable: true
  51774. });
  51775. /**
  51776. * Vive mapping:
  51777. * 0: touchpad
  51778. * 1: trigger
  51779. * 2: left AND right buttons
  51780. * 3: menu button
  51781. */
  51782. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51783. var notifyObject = state; //{ state: state, changes: changes };
  51784. switch (buttonIdx) {
  51785. case 0:
  51786. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51787. return;
  51788. case 1:
  51789. if (this._defaultModel) {
  51790. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51791. }
  51792. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51793. return;
  51794. case 2:
  51795. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51796. return;
  51797. case 3:
  51798. if (this._defaultModel) {
  51799. if (notifyObject.pressed) {
  51800. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51801. }
  51802. else {
  51803. (this._defaultModel.getChildren()[2]).position.y = 0;
  51804. }
  51805. }
  51806. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51807. return;
  51808. }
  51809. };
  51810. return ViveController;
  51811. }(WebVRController));
  51812. BABYLON.ViveController = ViveController;
  51813. })(BABYLON || (BABYLON = {}));
  51814. //# sourceMappingURL=babylon.extendedGamepad.js.map
  51815. /// <reference path="babylon.universalCamera.ts" />
  51816. var BABYLON;
  51817. (function (BABYLON) {
  51818. // We're mainly based on the logic defined into the FreeCamera code
  51819. var GamepadCamera = (function (_super) {
  51820. __extends(GamepadCamera, _super);
  51821. //-- end properties for backward compatibility for inputs
  51822. function GamepadCamera(name, position, scene) {
  51823. return _super.call(this, name, position, scene) || this;
  51824. }
  51825. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51826. //-- Begin properties for backward compatibility for inputs
  51827. get: function () {
  51828. var gamepad = this.inputs.attached["gamepad"];
  51829. if (gamepad)
  51830. return gamepad.gamepadAngularSensibility;
  51831. },
  51832. set: function (value) {
  51833. var gamepad = this.inputs.attached["gamepad"];
  51834. if (gamepad)
  51835. gamepad.gamepadAngularSensibility = value;
  51836. },
  51837. enumerable: true,
  51838. configurable: true
  51839. });
  51840. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51841. get: function () {
  51842. var gamepad = this.inputs.attached["gamepad"];
  51843. if (gamepad)
  51844. return gamepad.gamepadMoveSensibility;
  51845. },
  51846. set: function (value) {
  51847. var gamepad = this.inputs.attached["gamepad"];
  51848. if (gamepad)
  51849. gamepad.gamepadMoveSensibility = value;
  51850. },
  51851. enumerable: true,
  51852. configurable: true
  51853. });
  51854. GamepadCamera.prototype.getClassName = function () {
  51855. return "GamepadCamera";
  51856. };
  51857. return GamepadCamera;
  51858. }(BABYLON.UniversalCamera));
  51859. BABYLON.GamepadCamera = GamepadCamera;
  51860. })(BABYLON || (BABYLON = {}));
  51861. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51862. var BABYLON;
  51863. (function (BABYLON) {
  51864. var Analyser = (function () {
  51865. function Analyser(scene) {
  51866. this.SMOOTHING = 0.75;
  51867. this.FFT_SIZE = 512;
  51868. this.BARGRAPHAMPLITUDE = 256;
  51869. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51870. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51871. this._scene = scene;
  51872. this._audioEngine = BABYLON.Engine.audioEngine;
  51873. if (this._audioEngine.canUseWebAudio) {
  51874. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51875. this._webAudioAnalyser.minDecibels = -140;
  51876. this._webAudioAnalyser.maxDecibels = 0;
  51877. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51878. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51879. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51880. }
  51881. }
  51882. Analyser.prototype.getFrequencyBinCount = function () {
  51883. if (this._audioEngine.canUseWebAudio) {
  51884. return this._webAudioAnalyser.frequencyBinCount;
  51885. }
  51886. else {
  51887. return 0;
  51888. }
  51889. };
  51890. Analyser.prototype.getByteFrequencyData = function () {
  51891. if (this._audioEngine.canUseWebAudio) {
  51892. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51893. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51894. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51895. }
  51896. return this._byteFreqs;
  51897. };
  51898. Analyser.prototype.getByteTimeDomainData = function () {
  51899. if (this._audioEngine.canUseWebAudio) {
  51900. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51901. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51902. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51903. }
  51904. return this._byteTime;
  51905. };
  51906. Analyser.prototype.getFloatFrequencyData = function () {
  51907. if (this._audioEngine.canUseWebAudio) {
  51908. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51909. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51910. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51911. }
  51912. return this._floatFreqs;
  51913. };
  51914. Analyser.prototype.drawDebugCanvas = function () {
  51915. var _this = this;
  51916. if (this._audioEngine.canUseWebAudio) {
  51917. if (!this._debugCanvas) {
  51918. this._debugCanvas = document.createElement("canvas");
  51919. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51920. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51921. this._debugCanvas.style.position = "absolute";
  51922. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51923. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51924. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51925. document.body.appendChild(this._debugCanvas);
  51926. this._registerFunc = function () {
  51927. _this.drawDebugCanvas();
  51928. };
  51929. this._scene.registerBeforeRender(this._registerFunc);
  51930. }
  51931. if (this._registerFunc) {
  51932. var workingArray = this.getByteFrequencyData();
  51933. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51934. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51935. // Draw the frequency domain chart.
  51936. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51937. var value = workingArray[i];
  51938. var percent = value / this.BARGRAPHAMPLITUDE;
  51939. var height = this.DEBUGCANVASSIZE.height * percent;
  51940. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51941. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51942. var hue = i / this.getFrequencyBinCount() * 360;
  51943. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51944. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51945. }
  51946. }
  51947. }
  51948. };
  51949. Analyser.prototype.stopDebugCanvas = function () {
  51950. if (this._debugCanvas) {
  51951. this._scene.unregisterBeforeRender(this._registerFunc);
  51952. this._registerFunc = null;
  51953. document.body.removeChild(this._debugCanvas);
  51954. this._debugCanvas = null;
  51955. this._debugCanvasContext = null;
  51956. }
  51957. };
  51958. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51959. if (this._audioEngine.canUseWebAudio) {
  51960. inputAudioNode.connect(this._webAudioAnalyser);
  51961. this._webAudioAnalyser.connect(outputAudioNode);
  51962. }
  51963. };
  51964. Analyser.prototype.dispose = function () {
  51965. if (this._audioEngine.canUseWebAudio) {
  51966. this._webAudioAnalyser.disconnect();
  51967. }
  51968. };
  51969. return Analyser;
  51970. }());
  51971. BABYLON.Analyser = Analyser;
  51972. })(BABYLON || (BABYLON = {}));
  51973. //# sourceMappingURL=babylon.analyser.js.map
  51974. var BABYLON;
  51975. (function (BABYLON) {
  51976. var DepthRenderer = (function () {
  51977. function DepthRenderer(scene, type) {
  51978. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51979. var _this = this;
  51980. this._viewMatrix = BABYLON.Matrix.Zero();
  51981. this._projectionMatrix = BABYLON.Matrix.Zero();
  51982. this._transformMatrix = BABYLON.Matrix.Zero();
  51983. this._worldViewProjection = BABYLON.Matrix.Zero();
  51984. this._scene = scene;
  51985. var engine = scene.getEngine();
  51986. // Render target
  51987. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51988. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51989. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51990. this._depthMap.refreshRate = 1;
  51991. this._depthMap.renderParticles = false;
  51992. this._depthMap.renderList = null;
  51993. // set default depth value to 1.0 (far away)
  51994. this._depthMap.onClearObservable.add(function (engine) {
  51995. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51996. });
  51997. // Custom render function
  51998. var renderSubMesh = function (subMesh) {
  51999. var mesh = subMesh.getRenderingMesh();
  52000. var scene = _this._scene;
  52001. var engine = scene.getEngine();
  52002. // Culling
  52003. engine.setState(subMesh.getMaterial().backFaceCulling);
  52004. // Managing instances
  52005. var batch = mesh._getInstancesRenderList(subMesh._id);
  52006. if (batch.mustReturn) {
  52007. return;
  52008. }
  52009. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52010. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52011. engine.enableEffect(_this._effect);
  52012. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52013. var material = subMesh.getMaterial();
  52014. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52015. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  52016. // Alpha test
  52017. if (material && material.needAlphaTesting()) {
  52018. var alphaTexture = material.getAlphaTestTexture();
  52019. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52020. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52021. }
  52022. // Bones
  52023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52024. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52025. }
  52026. // Draw
  52027. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52028. }
  52029. };
  52030. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52031. var index;
  52032. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52033. renderSubMesh(opaqueSubMeshes.data[index]);
  52034. }
  52035. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52036. renderSubMesh(alphaTestSubMeshes.data[index]);
  52037. }
  52038. };
  52039. }
  52040. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52041. var material = subMesh.getMaterial();
  52042. if (material.disableDepthWrite) {
  52043. return false;
  52044. }
  52045. var defines = [];
  52046. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52047. var mesh = subMesh.getMesh();
  52048. var scene = mesh.getScene();
  52049. // Alpha test
  52050. if (material && material.needAlphaTesting()) {
  52051. defines.push("#define ALPHATEST");
  52052. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52053. attribs.push(BABYLON.VertexBuffer.UVKind);
  52054. defines.push("#define UV1");
  52055. }
  52056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52057. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52058. defines.push("#define UV2");
  52059. }
  52060. }
  52061. // Bones
  52062. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52063. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52064. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52065. if (mesh.numBoneInfluencers > 4) {
  52066. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52067. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52068. }
  52069. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52070. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52071. }
  52072. else {
  52073. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52074. }
  52075. // Instances
  52076. if (useInstances) {
  52077. defines.push("#define INSTANCES");
  52078. attribs.push("world0");
  52079. attribs.push("world1");
  52080. attribs.push("world2");
  52081. attribs.push("world3");
  52082. }
  52083. // Get correct effect
  52084. var join = defines.join("\n");
  52085. if (this._cachedDefines !== join) {
  52086. this._cachedDefines = join;
  52087. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  52088. }
  52089. return this._effect.isReady();
  52090. };
  52091. DepthRenderer.prototype.getDepthMap = function () {
  52092. return this._depthMap;
  52093. };
  52094. // Methods
  52095. DepthRenderer.prototype.dispose = function () {
  52096. this._depthMap.dispose();
  52097. };
  52098. return DepthRenderer;
  52099. }());
  52100. BABYLON.DepthRenderer = DepthRenderer;
  52101. })(BABYLON || (BABYLON = {}));
  52102. //# sourceMappingURL=babylon.depthRenderer.js.map
  52103. var BABYLON;
  52104. (function (BABYLON) {
  52105. var SSAORenderingPipeline = (function (_super) {
  52106. __extends(SSAORenderingPipeline, _super);
  52107. /**
  52108. * @constructor
  52109. * @param {string} name - The rendering pipeline name
  52110. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52111. * @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 }
  52112. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52113. */
  52114. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52115. var _this = _super.call(this, scene.getEngine(), name) || this;
  52116. // Members
  52117. /**
  52118. * The PassPostProcess id in the pipeline that contains the original scene color
  52119. * @type {string}
  52120. */
  52121. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52122. /**
  52123. * The SSAO PostProcess id in the pipeline
  52124. * @type {string}
  52125. */
  52126. _this.SSAORenderEffect = "SSAORenderEffect";
  52127. /**
  52128. * The horizontal blur PostProcess id in the pipeline
  52129. * @type {string}
  52130. */
  52131. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52132. /**
  52133. * The vertical blur PostProcess id in the pipeline
  52134. * @type {string}
  52135. */
  52136. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52137. /**
  52138. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52139. * @type {string}
  52140. */
  52141. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52142. /**
  52143. * The output strength of the SSAO post-process. Default value is 1.0.
  52144. * @type {number}
  52145. */
  52146. _this.totalStrength = 1.0;
  52147. /**
  52148. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52149. * @type {number}
  52150. */
  52151. _this.radius = 0.0001;
  52152. /**
  52153. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52154. * Must not be equal to fallOff and superior to fallOff.
  52155. * Default value is 0.975
  52156. * @type {number}
  52157. */
  52158. _this.area = 0.0075;
  52159. /**
  52160. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52161. * Must not be equal to area and inferior to area.
  52162. * Default value is 0.0
  52163. * @type {number}
  52164. */
  52165. _this.fallOff = 0.000001;
  52166. /**
  52167. * The base color of the SSAO post-process
  52168. * The final result is "base + ssao" between [0, 1]
  52169. * @type {number}
  52170. */
  52171. _this.base = 0.5;
  52172. _this._firstUpdate = true;
  52173. _this._scene = scene;
  52174. // Set up assets
  52175. _this._createRandomTexture();
  52176. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52177. var ssaoRatio = ratio.ssaoRatio || ratio;
  52178. var combineRatio = ratio.combineRatio || ratio;
  52179. _this._ratio = {
  52180. ssaoRatio: ssaoRatio,
  52181. combineRatio: combineRatio
  52182. };
  52183. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52184. _this._createSSAOPostProcess(ssaoRatio);
  52185. _this._createBlurPostProcess(ssaoRatio);
  52186. _this._createSSAOCombinePostProcess(combineRatio);
  52187. // Set up pipeline
  52188. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52189. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52190. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52191. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52192. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52193. // Finish
  52194. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52195. if (cameras)
  52196. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52197. return _this;
  52198. }
  52199. // Public Methods
  52200. /**
  52201. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52202. */
  52203. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52204. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52205. for (var i = 0; i < this._scene.cameras.length; i++) {
  52206. var camera = this._scene.cameras[i];
  52207. this._originalColorPostProcess.dispose(camera);
  52208. this._ssaoPostProcess.dispose(camera);
  52209. this._blurHPostProcess.dispose(camera);
  52210. this._blurVPostProcess.dispose(camera);
  52211. this._ssaoCombinePostProcess.dispose(camera);
  52212. }
  52213. this._randomTexture.dispose();
  52214. if (disableDepthRender)
  52215. this._scene.disableDepthRenderer();
  52216. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52217. _super.prototype.dispose.call(this);
  52218. };
  52219. // Private Methods
  52220. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52221. var _this = this;
  52222. /*
  52223. var samplerOffsets = [
  52224. -8.0, -6.0, -4.0, -2.0,
  52225. 0.0,
  52226. 2.0, 4.0, 6.0, 8.0
  52227. ];
  52228. */
  52229. var samples = 16;
  52230. var samplerOffsets = [];
  52231. for (var i = -8; i < 8; i++) {
  52232. samplerOffsets.push(i * 2);
  52233. }
  52234. 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");
  52235. this._blurHPostProcess.onApply = function (effect) {
  52236. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52237. effect.setTexture("depthSampler", _this._depthTexture);
  52238. if (_this._firstUpdate) {
  52239. effect.setArray("samplerOffsets", samplerOffsets);
  52240. }
  52241. };
  52242. 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");
  52243. this._blurVPostProcess.onApply = function (effect) {
  52244. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52245. effect.setTexture("depthSampler", _this._depthTexture);
  52246. if (_this._firstUpdate) {
  52247. effect.setArray("samplerOffsets", samplerOffsets);
  52248. _this._firstUpdate = false;
  52249. }
  52250. };
  52251. };
  52252. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52253. var _this = this;
  52254. var numSamples = 16;
  52255. var sampleSphere = [
  52256. 0.5381, 0.1856, -0.4319,
  52257. 0.1379, 0.2486, 0.4430,
  52258. 0.3371, 0.5679, -0.0057,
  52259. -0.6999, -0.0451, -0.0019,
  52260. 0.0689, -0.1598, -0.8547,
  52261. 0.0560, 0.0069, -0.1843,
  52262. -0.0146, 0.1402, 0.0762,
  52263. 0.0100, -0.1924, -0.0344,
  52264. -0.3577, -0.5301, -0.4358,
  52265. -0.3169, 0.1063, 0.0158,
  52266. 0.0103, -0.5869, 0.0046,
  52267. -0.0897, -0.4940, 0.3287,
  52268. 0.7119, -0.0154, -0.0918,
  52269. -0.0533, 0.0596, -0.5411,
  52270. 0.0352, -0.0631, 0.5460,
  52271. -0.4776, 0.2847, -0.0271
  52272. ];
  52273. var samplesFactor = 1.0 / numSamples;
  52274. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52275. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52276. "area", "fallOff", "base", "range", "viewport"
  52277. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52278. var viewport = new BABYLON.Vector2(0, 0);
  52279. this._ssaoPostProcess.onApply = function (effect) {
  52280. if (_this._firstUpdate) {
  52281. effect.setArray3("sampleSphere", sampleSphere);
  52282. effect.setFloat("samplesFactor", samplesFactor);
  52283. effect.setFloat("randTextureTiles", 4.0);
  52284. }
  52285. effect.setFloat("totalStrength", _this.totalStrength);
  52286. effect.setFloat("radius", _this.radius);
  52287. effect.setFloat("area", _this.area);
  52288. effect.setFloat("fallOff", _this.fallOff);
  52289. effect.setFloat("base", _this.base);
  52290. effect.setTexture("textureSampler", _this._depthTexture);
  52291. effect.setTexture("randomSampler", _this._randomTexture);
  52292. };
  52293. };
  52294. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52295. var _this = this;
  52296. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52297. this._ssaoCombinePostProcess.onApply = function (effect) {
  52298. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52299. };
  52300. };
  52301. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52302. var size = 512;
  52303. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52304. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52305. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52306. var context = this._randomTexture.getContext();
  52307. var rand = function (min, max) {
  52308. return Math.random() * (max - min) + min;
  52309. };
  52310. var randVector = BABYLON.Vector3.Zero();
  52311. for (var x = 0; x < size; x++) {
  52312. for (var y = 0; y < size; y++) {
  52313. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52314. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52315. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52316. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52317. context.fillRect(x, y, 1, 1);
  52318. }
  52319. }
  52320. this._randomTexture.update(false);
  52321. };
  52322. return SSAORenderingPipeline;
  52323. }(BABYLON.PostProcessRenderPipeline));
  52324. __decorate([
  52325. BABYLON.serialize()
  52326. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52327. __decorate([
  52328. BABYLON.serialize()
  52329. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52330. __decorate([
  52331. BABYLON.serialize()
  52332. ], SSAORenderingPipeline.prototype, "area", void 0);
  52333. __decorate([
  52334. BABYLON.serialize()
  52335. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52336. __decorate([
  52337. BABYLON.serialize()
  52338. ], SSAORenderingPipeline.prototype, "base", void 0);
  52339. __decorate([
  52340. BABYLON.serialize()
  52341. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52342. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52343. })(BABYLON || (BABYLON = {}));
  52344. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52345. var BABYLON;
  52346. (function (BABYLON) {
  52347. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52348. var VolumetricLightScatteringPostProcess = (function (_super) {
  52349. __extends(VolumetricLightScatteringPostProcess, _super);
  52350. /**
  52351. * @constructor
  52352. * @param {string} name - The post-process name
  52353. * @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)
  52354. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52355. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52356. * @param {number} samples - The post-process quality, default 100
  52357. * @param {number} samplingMode - The post-process filtering mode
  52358. * @param {BABYLON.Engine} engine - The babylon engine
  52359. * @param {boolean} reusable - If the post-process is reusable
  52360. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52361. */
  52362. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52363. if (samples === void 0) { samples = 100; }
  52364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52365. 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;
  52366. _this._screenCoordinates = BABYLON.Vector2.Zero();
  52367. /**
  52368. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52369. * @type {Vector3}
  52370. */
  52371. _this.customMeshPosition = BABYLON.Vector3.Zero();
  52372. /**
  52373. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52374. * @type {boolean}
  52375. */
  52376. _this.useCustomMeshPosition = false;
  52377. /**
  52378. * If the post-process should inverse the light scattering direction
  52379. * @type {boolean}
  52380. */
  52381. _this.invert = true;
  52382. /**
  52383. * Array containing the excluded meshes not rendered in the internal pass
  52384. */
  52385. _this.excludedMeshes = new Array();
  52386. /**
  52387. * Controls the overall intensity of the post-process
  52388. * @type {number}
  52389. */
  52390. _this.exposure = 0.3;
  52391. /**
  52392. * Dissipates each sample's contribution in range [0, 1]
  52393. * @type {number}
  52394. */
  52395. _this.decay = 0.96815;
  52396. /**
  52397. * Controls the overall intensity of each sample
  52398. * @type {number}
  52399. */
  52400. _this.weight = 0.58767;
  52401. /**
  52402. * Controls the density of each sample
  52403. * @type {number}
  52404. */
  52405. _this.density = 0.926;
  52406. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52407. var engine = scene.getEngine();
  52408. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52409. // Configure mesh
  52410. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52411. // Configure
  52412. _this._createPass(scene, ratio.passRatio || ratio);
  52413. _this.onActivate = function (camera) {
  52414. if (!_this.isSupported) {
  52415. _this.dispose(camera);
  52416. }
  52417. _this.onActivate = null;
  52418. };
  52419. _this.onApplyObservable.add(function (effect) {
  52420. _this._updateMeshScreenCoordinates(scene);
  52421. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52422. effect.setFloat("exposure", _this.exposure);
  52423. effect.setFloat("decay", _this.decay);
  52424. effect.setFloat("weight", _this.weight);
  52425. effect.setFloat("density", _this.density);
  52426. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52427. });
  52428. return _this;
  52429. }
  52430. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52431. get: function () {
  52432. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52433. return false;
  52434. },
  52435. set: function (useDiffuseColor) {
  52436. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52437. },
  52438. enumerable: true,
  52439. configurable: true
  52440. });
  52441. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52442. var mesh = subMesh.getMesh();
  52443. // Render this.mesh as default
  52444. if (mesh === this.mesh) {
  52445. return mesh.material.isReady(mesh);
  52446. }
  52447. var defines = [];
  52448. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52449. var material = subMesh.getMaterial();
  52450. var needUV = false;
  52451. // Alpha test
  52452. if (material) {
  52453. if (material.needAlphaTesting()) {
  52454. defines.push("#define ALPHATEST");
  52455. }
  52456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52457. attribs.push(BABYLON.VertexBuffer.UVKind);
  52458. defines.push("#define UV1");
  52459. }
  52460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52461. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52462. defines.push("#define UV2");
  52463. }
  52464. }
  52465. // Bones
  52466. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52469. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52470. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52471. }
  52472. else {
  52473. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52474. }
  52475. // Instances
  52476. if (useInstances) {
  52477. defines.push("#define INSTANCES");
  52478. attribs.push("world0");
  52479. attribs.push("world1");
  52480. attribs.push("world2");
  52481. attribs.push("world3");
  52482. }
  52483. // Get correct effect
  52484. var join = defines.join("\n");
  52485. if (this._cachedDefines !== join) {
  52486. this._cachedDefines = join;
  52487. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52488. }
  52489. return this._volumetricLightScatteringPass.isReady();
  52490. };
  52491. /**
  52492. * Sets the new light position for light scattering effect
  52493. * @param {BABYLON.Vector3} The new custom light position
  52494. */
  52495. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52496. this.customMeshPosition = position;
  52497. };
  52498. /**
  52499. * Returns the light position for light scattering effect
  52500. * @return {BABYLON.Vector3} The custom light position
  52501. */
  52502. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52503. return this.customMeshPosition;
  52504. };
  52505. /**
  52506. * Disposes the internal assets and detaches the post-process from the camera
  52507. */
  52508. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52509. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52510. if (rttIndex !== -1) {
  52511. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52512. }
  52513. this._volumetricLightScatteringRTT.dispose();
  52514. _super.prototype.dispose.call(this, camera);
  52515. };
  52516. /**
  52517. * Returns the render target texture used by the post-process
  52518. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52519. */
  52520. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52521. return this._volumetricLightScatteringRTT;
  52522. };
  52523. // Private methods
  52524. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52525. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52526. return true;
  52527. }
  52528. return false;
  52529. };
  52530. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52531. var _this = this;
  52532. var engine = scene.getEngine();
  52533. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52534. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52535. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52536. this._volumetricLightScatteringRTT.renderList = null;
  52537. this._volumetricLightScatteringRTT.renderParticles = false;
  52538. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52539. // Custom render function for submeshes
  52540. var renderSubMesh = function (subMesh) {
  52541. var mesh = subMesh.getRenderingMesh();
  52542. if (_this._meshExcluded(mesh)) {
  52543. return;
  52544. }
  52545. var scene = mesh.getScene();
  52546. var engine = scene.getEngine();
  52547. // Culling
  52548. engine.setState(subMesh.getMaterial().backFaceCulling);
  52549. // Managing instances
  52550. var batch = mesh._getInstancesRenderList(subMesh._id);
  52551. if (batch.mustReturn) {
  52552. return;
  52553. }
  52554. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52555. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52556. var effect = _this._volumetricLightScatteringPass;
  52557. if (mesh === _this.mesh) {
  52558. effect = subMesh.getMaterial().getEffect();
  52559. }
  52560. engine.enableEffect(effect);
  52561. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52562. if (mesh === _this.mesh) {
  52563. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52564. }
  52565. else {
  52566. var material = subMesh.getMaterial();
  52567. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52568. // Alpha test
  52569. if (material && material.needAlphaTesting()) {
  52570. var alphaTexture = material.getAlphaTestTexture();
  52571. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52572. if (alphaTexture) {
  52573. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52574. }
  52575. }
  52576. // Bones
  52577. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52578. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52579. }
  52580. }
  52581. // Draw
  52582. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52583. }
  52584. };
  52585. // Render target texture callbacks
  52586. var savedSceneClearColor;
  52587. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52588. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52589. savedSceneClearColor = scene.clearColor;
  52590. scene.clearColor = sceneClearColor;
  52591. });
  52592. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52593. scene.clearColor = savedSceneClearColor;
  52594. });
  52595. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52596. var engine = scene.getEngine();
  52597. var index;
  52598. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52599. renderSubMesh(opaqueSubMeshes.data[index]);
  52600. }
  52601. engine.setAlphaTesting(true);
  52602. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52603. renderSubMesh(alphaTestSubMeshes.data[index]);
  52604. }
  52605. engine.setAlphaTesting(false);
  52606. if (transparentSubMeshes.length) {
  52607. // Sort sub meshes
  52608. for (index = 0; index < transparentSubMeshes.length; index++) {
  52609. var submesh = transparentSubMeshes.data[index];
  52610. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52611. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52612. }
  52613. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52614. sortedArray.sort(function (a, b) {
  52615. // Alpha index first
  52616. if (a._alphaIndex > b._alphaIndex) {
  52617. return 1;
  52618. }
  52619. if (a._alphaIndex < b._alphaIndex) {
  52620. return -1;
  52621. }
  52622. // Then distance to camera
  52623. if (a._distanceToCamera < b._distanceToCamera) {
  52624. return 1;
  52625. }
  52626. if (a._distanceToCamera > b._distanceToCamera) {
  52627. return -1;
  52628. }
  52629. return 0;
  52630. });
  52631. // Render sub meshes
  52632. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52633. for (index = 0; index < sortedArray.length; index++) {
  52634. renderSubMesh(sortedArray[index]);
  52635. }
  52636. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52637. }
  52638. };
  52639. };
  52640. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52641. var transform = scene.getTransformMatrix();
  52642. var meshPosition;
  52643. if (this.useCustomMeshPosition) {
  52644. meshPosition = this.customMeshPosition;
  52645. }
  52646. else if (this.attachedNode) {
  52647. meshPosition = this.attachedNode.position;
  52648. }
  52649. else {
  52650. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52651. }
  52652. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52653. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52654. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52655. if (this.invert)
  52656. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52657. };
  52658. // Static methods
  52659. /**
  52660. * Creates a default mesh for the Volumeric Light Scattering post-process
  52661. * @param {string} The mesh name
  52662. * @param {BABYLON.Scene} The scene where to create the mesh
  52663. * @return {BABYLON.Mesh} the default mesh
  52664. */
  52665. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52666. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52667. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52668. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52669. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52670. mesh.material = material;
  52671. return mesh;
  52672. };
  52673. return VolumetricLightScatteringPostProcess;
  52674. }(BABYLON.PostProcess));
  52675. __decorate([
  52676. BABYLON.serializeAsVector3()
  52677. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52678. __decorate([
  52679. BABYLON.serialize()
  52680. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52681. __decorate([
  52682. BABYLON.serialize()
  52683. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52684. __decorate([
  52685. BABYLON.serializeAsMeshReference()
  52686. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52687. __decorate([
  52688. BABYLON.serialize()
  52689. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52690. __decorate([
  52691. BABYLON.serialize()
  52692. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52693. __decorate([
  52694. BABYLON.serialize()
  52695. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52696. __decorate([
  52697. BABYLON.serialize()
  52698. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52699. __decorate([
  52700. BABYLON.serialize()
  52701. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52702. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52703. })(BABYLON || (BABYLON = {}));
  52704. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52705. // BABYLON.JS Chromatic Aberration GLSL Shader
  52706. // Author: Olivier Guyot
  52707. // Separates very slightly R, G and B colors on the edges of the screen
  52708. // Inspired by Francois Tarlier & Martins Upitis
  52709. var BABYLON;
  52710. (function (BABYLON) {
  52711. var LensRenderingPipeline = (function (_super) {
  52712. __extends(LensRenderingPipeline, _super);
  52713. /**
  52714. * @constructor
  52715. *
  52716. * Effect parameters are as follow:
  52717. * {
  52718. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52719. * edge_blur: number; // from 0 to x (1 for realism)
  52720. * distortion: number; // from 0 to x (1 for realism)
  52721. * grain_amount: number; // from 0 to 1
  52722. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52723. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52724. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52725. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52726. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52727. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52728. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52729. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52730. * }
  52731. * Note: if an effect parameter is unset, effect is disabled
  52732. *
  52733. * @param {string} name - The rendering pipeline name
  52734. * @param {object} parameters - An object containing all parameters (see above)
  52735. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52736. * @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)
  52737. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52738. */
  52739. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52740. if (ratio === void 0) { ratio = 1.0; }
  52741. var _this = _super.call(this, scene.getEngine(), name) || this;
  52742. // Lens effects can be of the following:
  52743. // - chromatic aberration (slight shift of RGB colors)
  52744. // - blur on the edge of the lens
  52745. // - lens distortion
  52746. // - depth-of-field blur & highlights enhancing
  52747. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52748. // - grain effect (noise or custom texture)
  52749. // Two additional texture samplers are needed:
  52750. // - depth map (for depth-of-field)
  52751. // - grain texture
  52752. /**
  52753. * The chromatic aberration PostProcess id in the pipeline
  52754. * @type {string}
  52755. */
  52756. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52757. /**
  52758. * The highlights enhancing PostProcess id in the pipeline
  52759. * @type {string}
  52760. */
  52761. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52762. /**
  52763. * The depth-of-field PostProcess id in the pipeline
  52764. * @type {string}
  52765. */
  52766. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52767. _this._scene = scene;
  52768. // Fetch texture samplers
  52769. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52770. if (parameters.grain_texture) {
  52771. _this._grainTexture = parameters.grain_texture;
  52772. }
  52773. else {
  52774. _this._createGrainTexture();
  52775. }
  52776. // save parameters
  52777. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52778. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52779. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52780. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52781. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52782. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52783. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52784. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52785. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52786. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52787. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52788. // Create effects
  52789. _this._createChromaticAberrationPostProcess(ratio);
  52790. _this._createHighlightsPostProcess(ratio);
  52791. _this._createDepthOfFieldPostProcess(ratio / 4);
  52792. // Set up pipeline
  52793. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52794. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52795. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52796. if (_this._highlightsGain === -1) {
  52797. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52798. }
  52799. // Finish
  52800. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52801. if (cameras) {
  52802. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52803. }
  52804. return _this;
  52805. }
  52806. // public methods (self explanatory)
  52807. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52808. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52809. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52810. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52811. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52812. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52813. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52814. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52815. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52816. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52817. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52818. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52819. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52820. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52821. };
  52822. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52823. this._highlightsPostProcess.updateEffect();
  52824. };
  52825. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52826. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52827. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52828. this._highlightsGain = amount;
  52829. };
  52830. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52831. if (this._highlightsGain === -1) {
  52832. this._highlightsGain = 1.0;
  52833. }
  52834. this._highlightsThreshold = amount;
  52835. };
  52836. LensRenderingPipeline.prototype.disableHighlights = function () {
  52837. this._highlightsGain = -1;
  52838. };
  52839. /**
  52840. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52841. */
  52842. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52843. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52844. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52845. this._chromaticAberrationPostProcess = undefined;
  52846. this._highlightsPostProcess = undefined;
  52847. this._depthOfFieldPostProcess = undefined;
  52848. this._grainTexture.dispose();
  52849. if (disableDepthRender)
  52850. this._scene.disableDepthRenderer();
  52851. };
  52852. // colors shifting and distortion
  52853. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52854. var _this = this;
  52855. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52856. [], // samplers
  52857. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52858. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52859. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52860. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52861. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52862. };
  52863. };
  52864. // highlights enhancing
  52865. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52866. var _this = this;
  52867. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52868. [], // samplers
  52869. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52870. this._highlightsPostProcess.onApply = function (effect) {
  52871. effect.setFloat('gain', _this._highlightsGain);
  52872. effect.setFloat('threshold', _this._highlightsThreshold);
  52873. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52874. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52875. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52876. };
  52877. };
  52878. // colors shifting and distortion
  52879. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52880. var _this = this;
  52881. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52882. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52883. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52884. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52885. this._depthOfFieldPostProcess.onApply = function (effect) {
  52886. effect.setTexture("depthSampler", _this._depthTexture);
  52887. effect.setTexture("grainSampler", _this._grainTexture);
  52888. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52889. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52890. effect.setFloat('grain_amount', _this._grainAmount);
  52891. effect.setBool('blur_noise', _this._blurNoise);
  52892. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52893. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52894. effect.setFloat('distortion', _this._distortion);
  52895. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52896. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52897. effect.setFloat('aperture', _this._dofAperture);
  52898. effect.setFloat('darken', _this._dofDarken);
  52899. effect.setFloat('edge_blur', _this._edgeBlur);
  52900. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52901. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52902. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52903. };
  52904. };
  52905. // creates a black and white random noise texture, 512x512
  52906. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52907. var size = 512;
  52908. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52909. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52910. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52911. var context = this._grainTexture.getContext();
  52912. var rand = function (min, max) {
  52913. return Math.random() * (max - min) + min;
  52914. };
  52915. var value;
  52916. for (var x = 0; x < size; x++) {
  52917. for (var y = 0; y < size; y++) {
  52918. value = Math.floor(rand(0.42, 0.58) * 255);
  52919. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52920. context.fillRect(x, y, 1, 1);
  52921. }
  52922. }
  52923. this._grainTexture.update(false);
  52924. };
  52925. return LensRenderingPipeline;
  52926. }(BABYLON.PostProcessRenderPipeline));
  52927. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52928. })(BABYLON || (BABYLON = {}));
  52929. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52930. //
  52931. // This post-process allows the modification of rendered colors by using
  52932. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52933. //
  52934. // The object needs to be provided an url to a texture containing the color
  52935. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52936. // Use an image editing software to tweak the LUT to match your needs.
  52937. //
  52938. // For an example of a color LUT, see here:
  52939. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52940. // For explanations on color grading, see here:
  52941. // http://udn.epicgames.com/Three/ColorGrading.html
  52942. //
  52943. var BABYLON;
  52944. (function (BABYLON) {
  52945. var ColorCorrectionPostProcess = (function (_super) {
  52946. __extends(ColorCorrectionPostProcess, _super);
  52947. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52948. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52949. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52950. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52951. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52952. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52953. _this.onApply = function (effect) {
  52954. effect.setTexture("colorTable", _this._colorTableTexture);
  52955. };
  52956. return _this;
  52957. }
  52958. return ColorCorrectionPostProcess;
  52959. }(BABYLON.PostProcess));
  52960. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52961. })(BABYLON || (BABYLON = {}));
  52962. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52963. /// <reference path="babylon.freeCamera.ts" />
  52964. /// <reference path="babylon.arcRotateCamera.ts" />
  52965. /// <reference path="babylon.gamepadCamera.ts" />
  52966. /// <reference path="babylon.universalCamera.ts" />
  52967. var BABYLON;
  52968. (function (BABYLON) {
  52969. var AnaglyphFreeCamera = (function (_super) {
  52970. __extends(AnaglyphFreeCamera, _super);
  52971. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  52972. var _this = _super.call(this, name, position, scene) || this;
  52973. _this.interaxialDistance = interaxialDistance;
  52974. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52975. return _this;
  52976. }
  52977. AnaglyphFreeCamera.prototype.getClassName = function () {
  52978. return "AnaglyphFreeCamera";
  52979. };
  52980. return AnaglyphFreeCamera;
  52981. }(BABYLON.FreeCamera));
  52982. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  52983. var AnaglyphArcRotateCamera = (function (_super) {
  52984. __extends(AnaglyphArcRotateCamera, _super);
  52985. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  52986. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52987. _this.interaxialDistance = interaxialDistance;
  52988. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52989. return _this;
  52990. }
  52991. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  52992. return "AnaglyphArcRotateCamera";
  52993. };
  52994. return AnaglyphArcRotateCamera;
  52995. }(BABYLON.ArcRotateCamera));
  52996. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  52997. var AnaglyphGamepadCamera = (function (_super) {
  52998. __extends(AnaglyphGamepadCamera, _super);
  52999. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  53000. var _this = _super.call(this, name, position, scene) || this;
  53001. _this.interaxialDistance = interaxialDistance;
  53002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53003. return _this;
  53004. }
  53005. AnaglyphGamepadCamera.prototype.getClassName = function () {
  53006. return "AnaglyphGamepadCamera";
  53007. };
  53008. return AnaglyphGamepadCamera;
  53009. }(BABYLON.GamepadCamera));
  53010. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  53011. var AnaglyphUniversalCamera = (function (_super) {
  53012. __extends(AnaglyphUniversalCamera, _super);
  53013. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  53014. var _this = _super.call(this, name, position, scene) || this;
  53015. _this.interaxialDistance = interaxialDistance;
  53016. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53017. return _this;
  53018. }
  53019. AnaglyphUniversalCamera.prototype.getClassName = function () {
  53020. return "AnaglyphUniversalCamera";
  53021. };
  53022. return AnaglyphUniversalCamera;
  53023. }(BABYLON.UniversalCamera));
  53024. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  53025. var StereoscopicFreeCamera = (function (_super) {
  53026. __extends(StereoscopicFreeCamera, _super);
  53027. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53028. var _this = _super.call(this, name, position, scene) || this;
  53029. _this.interaxialDistance = interaxialDistance;
  53030. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53031. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53032. return _this;
  53033. }
  53034. StereoscopicFreeCamera.prototype.getClassName = function () {
  53035. return "StereoscopicFreeCamera";
  53036. };
  53037. return StereoscopicFreeCamera;
  53038. }(BABYLON.FreeCamera));
  53039. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  53040. var StereoscopicArcRotateCamera = (function (_super) {
  53041. __extends(StereoscopicArcRotateCamera, _super);
  53042. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  53043. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  53044. _this.interaxialDistance = interaxialDistance;
  53045. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53046. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53047. return _this;
  53048. }
  53049. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  53050. return "StereoscopicArcRotateCamera";
  53051. };
  53052. return StereoscopicArcRotateCamera;
  53053. }(BABYLON.ArcRotateCamera));
  53054. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  53055. var StereoscopicGamepadCamera = (function (_super) {
  53056. __extends(StereoscopicGamepadCamera, _super);
  53057. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53058. var _this = _super.call(this, name, position, scene) || this;
  53059. _this.interaxialDistance = interaxialDistance;
  53060. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53061. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53062. return _this;
  53063. }
  53064. StereoscopicGamepadCamera.prototype.getClassName = function () {
  53065. return "StereoscopicGamepadCamera";
  53066. };
  53067. return StereoscopicGamepadCamera;
  53068. }(BABYLON.GamepadCamera));
  53069. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  53070. var StereoscopicUniversalCamera = (function (_super) {
  53071. __extends(StereoscopicUniversalCamera, _super);
  53072. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53073. var _this = _super.call(this, name, position, scene) || this;
  53074. _this.interaxialDistance = interaxialDistance;
  53075. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53076. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53077. return _this;
  53078. }
  53079. StereoscopicUniversalCamera.prototype.getClassName = function () {
  53080. return "StereoscopicUniversalCamera";
  53081. };
  53082. return StereoscopicUniversalCamera;
  53083. }(BABYLON.UniversalCamera));
  53084. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  53085. })(BABYLON || (BABYLON = {}));
  53086. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  53087. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  53088. var BABYLON;
  53089. (function (BABYLON) {
  53090. var HDRRenderingPipeline = (function (_super) {
  53091. __extends(HDRRenderingPipeline, _super);
  53092. /**
  53093. * @constructor
  53094. * @param {string} name - The rendering pipeline name
  53095. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53096. * @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)
  53097. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53098. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53099. */
  53100. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53101. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53102. var _this = _super.call(this, scene.getEngine(), name) || this;
  53103. /**
  53104. * Public members
  53105. */
  53106. // Gaussian Blur
  53107. /**
  53108. * Gaussian blur coefficient
  53109. * @type {number}
  53110. */
  53111. _this.gaussCoeff = 0.3;
  53112. /**
  53113. * Gaussian blur mean
  53114. * @type {number}
  53115. */
  53116. _this.gaussMean = 1.0;
  53117. /**
  53118. * Gaussian blur standard deviation
  53119. * @type {number}
  53120. */
  53121. _this.gaussStandDev = 0.8;
  53122. /**
  53123. * Gaussian blur multiplier. Multiplies the blur effect
  53124. * @type {number}
  53125. */
  53126. _this.gaussMultiplier = 4.0;
  53127. // HDR
  53128. /**
  53129. * Exposure, controls the overall intensity of the pipeline
  53130. * @type {number}
  53131. */
  53132. _this.exposure = 1.0;
  53133. /**
  53134. * Minimum luminance that the post-process can output. Luminance is >= 0
  53135. * @type {number}
  53136. */
  53137. _this.minimumLuminance = 1.0;
  53138. /**
  53139. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  53140. * @type {number}
  53141. */
  53142. _this.maximumLuminance = 1e20;
  53143. /**
  53144. * Increase rate for luminance: eye adaptation speed to dark
  53145. * @type {number}
  53146. */
  53147. _this.luminanceIncreaserate = 0.5;
  53148. /**
  53149. * Decrease rate for luminance: eye adaptation speed to bright
  53150. * @type {number}
  53151. */
  53152. _this.luminanceDecreaseRate = 0.5;
  53153. // Bright pass
  53154. /**
  53155. * Minimum luminance needed to compute HDR
  53156. * @type {number}
  53157. */
  53158. _this.brightThreshold = 0.8;
  53159. _this._needUpdate = true;
  53160. _this._scene = scene;
  53161. // Bright pass
  53162. _this._createBrightPassPostProcess(scene, ratio);
  53163. // Down sample X4
  53164. _this._createDownSampleX4PostProcess(scene, ratio);
  53165. // Create gaussian blur post-processes
  53166. _this._createGaussianBlurPostProcess(scene, ratio);
  53167. // Texture adder
  53168. _this._createTextureAdderPostProcess(scene, ratio);
  53169. // Luminance generator
  53170. _this._createLuminanceGeneratorPostProcess(scene);
  53171. // HDR
  53172. _this._createHDRPostProcess(scene, ratio);
  53173. // Pass postprocess
  53174. if (originalPostProcess === null) {
  53175. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53176. }
  53177. else {
  53178. _this._originalPostProcess = originalPostProcess;
  53179. }
  53180. // Configure pipeline
  53181. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  53182. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  53183. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  53184. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  53185. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  53186. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  53187. var addDownSamplerPostProcess = function (id) {
  53188. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  53189. };
  53190. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53191. addDownSamplerPostProcess(i);
  53192. }
  53193. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  53194. // Finish
  53195. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53196. if (cameras !== null) {
  53197. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53198. }
  53199. _this.update();
  53200. return _this;
  53201. }
  53202. /**
  53203. * Tells the pipeline to update its post-processes
  53204. */
  53205. HDRRenderingPipeline.prototype.update = function () {
  53206. this._needUpdate = true;
  53207. };
  53208. /**
  53209. * Returns the current calculated luminance
  53210. */
  53211. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  53212. return this._hdrCurrentLuminance;
  53213. };
  53214. /**
  53215. * Returns the currently drawn luminance
  53216. */
  53217. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  53218. return this._hdrOutputLuminance;
  53219. };
  53220. /**
  53221. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  53222. */
  53223. HDRRenderingPipeline.prototype.dispose = function () {
  53224. for (var i = 0; i < this._scene.cameras.length; i++) {
  53225. var camera = this._scene.cameras[i];
  53226. this._originalPostProcess.dispose(camera);
  53227. this._brightPassPostProcess.dispose(camera);
  53228. this._downSampleX4PostProcess.dispose(camera);
  53229. this._guassianBlurHPostProcess.dispose(camera);
  53230. this._guassianBlurVPostProcess.dispose(camera);
  53231. this._textureAdderPostProcess.dispose(camera);
  53232. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  53233. this._downSamplePostProcesses[j].dispose(camera);
  53234. }
  53235. this._hdrPostProcess.dispose(camera);
  53236. }
  53237. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53238. _super.prototype.dispose.call(this);
  53239. };
  53240. /**
  53241. * Creates the HDR post-process and computes the luminance adaptation
  53242. */
  53243. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  53244. var _this = this;
  53245. var hdrLastLuminance = 0.0;
  53246. this._hdrOutputLuminance = -1.0;
  53247. this._hdrCurrentLuminance = 1.0;
  53248. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  53249. this._hdrPostProcess.onApply = function (effect) {
  53250. if (_this._hdrOutputLuminance < 0.0) {
  53251. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53252. }
  53253. else {
  53254. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  53255. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  53256. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  53257. }
  53258. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  53259. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  53260. }
  53261. else {
  53262. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53263. }
  53264. }
  53265. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  53266. hdrLastLuminance += scene.getEngine().getDeltaTime();
  53267. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53268. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53269. effect.setFloat("exposure", _this.exposure);
  53270. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  53271. _this._needUpdate = false;
  53272. };
  53273. };
  53274. /**
  53275. * Texture Adder post-process
  53276. */
  53277. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53278. var _this = this;
  53279. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  53280. this._textureAdderPostProcess.onApply = function (effect) {
  53281. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53282. };
  53283. };
  53284. /**
  53285. * Down sample X4 post-process
  53286. */
  53287. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53288. var _this = this;
  53289. var downSampleX4Offsets = new Array(32);
  53290. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  53291. this._downSampleX4PostProcess.onApply = function (effect) {
  53292. if (_this._needUpdate) {
  53293. var id = 0;
  53294. for (var i = -2; i < 2; i++) {
  53295. for (var j = -2; j < 2; j++) {
  53296. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  53297. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  53298. id += 2;
  53299. }
  53300. }
  53301. }
  53302. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53303. };
  53304. };
  53305. /**
  53306. * Bright pass post-process
  53307. */
  53308. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53309. var _this = this;
  53310. var brightOffsets = new Array(8);
  53311. var brightPassCallback = function (effect) {
  53312. if (_this._needUpdate) {
  53313. var sU = (1.0 / _this._brightPassPostProcess.width);
  53314. var sV = (1.0 / _this._brightPassPostProcess.height);
  53315. brightOffsets[0] = -0.5 * sU;
  53316. brightOffsets[1] = 0.5 * sV;
  53317. brightOffsets[2] = 0.5 * sU;
  53318. brightOffsets[3] = 0.5 * sV;
  53319. brightOffsets[4] = -0.5 * sU;
  53320. brightOffsets[5] = -0.5 * sV;
  53321. brightOffsets[6] = 0.5 * sU;
  53322. brightOffsets[7] = -0.5 * sV;
  53323. }
  53324. effect.setArray2("dsOffsets", brightOffsets);
  53325. effect.setFloat("brightThreshold", _this.brightThreshold);
  53326. };
  53327. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  53328. this._brightPassPostProcess.onApply = brightPassCallback;
  53329. };
  53330. /**
  53331. * Luminance generator. Creates the luminance post-process and down sample post-processes
  53332. */
  53333. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  53334. var _this = this;
  53335. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  53336. var luminanceOffsets = new Array(8);
  53337. var downSampleOffsets = new Array(18);
  53338. var halfDestPixelSize;
  53339. this._downSamplePostProcesses = new Array(lumSteps);
  53340. // Utils for luminance
  53341. var luminanceUpdateSourceOffsets = function (width, height) {
  53342. var sU = (1.0 / width);
  53343. var sV = (1.0 / height);
  53344. luminanceOffsets[0] = -0.5 * sU;
  53345. luminanceOffsets[1] = 0.5 * sV;
  53346. luminanceOffsets[2] = 0.5 * sU;
  53347. luminanceOffsets[3] = 0.5 * sV;
  53348. luminanceOffsets[4] = -0.5 * sU;
  53349. luminanceOffsets[5] = -0.5 * sV;
  53350. luminanceOffsets[6] = 0.5 * sU;
  53351. luminanceOffsets[7] = -0.5 * sV;
  53352. };
  53353. var luminanceUpdateDestOffsets = function (width, height) {
  53354. var id = 0;
  53355. for (var x = -1; x < 2; x++) {
  53356. for (var y = -1; y < 2; y++) {
  53357. downSampleOffsets[id] = (x) / width;
  53358. downSampleOffsets[id + 1] = (y) / height;
  53359. id += 2;
  53360. }
  53361. }
  53362. };
  53363. // Luminance callback
  53364. var luminanceCallback = function (effect) {
  53365. if (_this._needUpdate) {
  53366. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  53367. }
  53368. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53369. effect.setArray2("lumOffsets", luminanceOffsets);
  53370. };
  53371. // Down sample callbacks
  53372. var downSampleCallback = function (indice) {
  53373. var i = indice;
  53374. return function (effect) {
  53375. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53376. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53377. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  53378. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  53379. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  53380. effect.setArray2("dsOffsets", downSampleOffsets);
  53381. };
  53382. };
  53383. var downSampleAfterRenderCallback = function (effect) {
  53384. // Unpack result
  53385. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53386. 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);
  53387. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53388. };
  53389. // Create luminance post-process
  53390. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  53391. 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);
  53392. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  53393. // Create down sample post-processes
  53394. for (var i = lumSteps - 2; i >= 0; i--) {
  53395. var length = Math.pow(3, i);
  53396. ratio = { width: length, height: length };
  53397. var defines = "#define DOWN_SAMPLE\n";
  53398. if (i === 0) {
  53399. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  53400. }
  53401. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53402. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  53403. if (i === 0) {
  53404. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  53405. }
  53406. }
  53407. };
  53408. /**
  53409. * Gaussian blur post-processes. Horizontal and Vertical
  53410. */
  53411. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  53412. var _this = this;
  53413. var blurOffsetsW = new Array(9);
  53414. var blurOffsetsH = new Array(9);
  53415. var blurWeights = new Array(9);
  53416. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  53417. // Utils for gaussian blur
  53418. var calculateBlurOffsets = function (height) {
  53419. var lastOutputDimensions = {
  53420. width: scene.getEngine().getRenderWidth(),
  53421. height: scene.getEngine().getRenderHeight()
  53422. };
  53423. for (var i = 0; i < 9; i++) {
  53424. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53425. if (height) {
  53426. blurOffsetsH[i] = value;
  53427. }
  53428. else {
  53429. blurOffsetsW[i] = value;
  53430. }
  53431. }
  53432. };
  53433. var calculateWeights = function () {
  53434. var x = 0.0;
  53435. for (var i = 0; i < 9; i++) {
  53436. x = (i - 4.0) / 4.0;
  53437. 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));
  53438. }
  53439. };
  53440. // Callback
  53441. var gaussianBlurCallback = function (height) {
  53442. return function (effect) {
  53443. if (_this._needUpdate) {
  53444. calculateWeights();
  53445. calculateBlurOffsets(height);
  53446. }
  53447. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  53448. effect.setArray("blurWeights", blurWeights);
  53449. effect.setFloat("multiplier", _this.gaussMultiplier);
  53450. };
  53451. };
  53452. // Create horizontal gaussian blur post-processes
  53453. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  53454. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  53455. // Create vertical gaussian blur post-process
  53456. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  53457. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  53458. };
  53459. return HDRRenderingPipeline;
  53460. }(BABYLON.PostProcessRenderPipeline));
  53461. // Luminance generator
  53462. HDRRenderingPipeline.LUM_STEPS = 6;
  53463. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  53464. })(BABYLON || (BABYLON = {}));
  53465. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  53466. var BABYLON;
  53467. (function (BABYLON) {
  53468. var FaceAdjacencies = (function () {
  53469. function FaceAdjacencies() {
  53470. this.edges = new Array();
  53471. this.edgesConnectedCount = 0;
  53472. }
  53473. return FaceAdjacencies;
  53474. }());
  53475. var EdgesRenderer = (function () {
  53476. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  53477. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  53478. if (epsilon === void 0) { epsilon = 0.95; }
  53479. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  53480. this.edgesWidthScalerForOrthographic = 1000.0;
  53481. this.edgesWidthScalerForPerspective = 50.0;
  53482. this._linesPositions = new Array();
  53483. this._linesNormals = new Array();
  53484. this._linesIndices = new Array();
  53485. this._buffers = {};
  53486. this._checkVerticesInsteadOfIndices = false;
  53487. this._source = source;
  53488. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  53489. this._epsilon = epsilon;
  53490. this._prepareRessources();
  53491. this._generateEdgesLines();
  53492. }
  53493. EdgesRenderer.prototype._prepareRessources = function () {
  53494. if (this._lineShader) {
  53495. return;
  53496. }
  53497. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  53498. attributes: ["position", "normal"],
  53499. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  53500. });
  53501. this._lineShader.disableDepthWrite = true;
  53502. this._lineShader.backFaceCulling = false;
  53503. };
  53504. EdgesRenderer.prototype.dispose = function () {
  53505. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  53506. if (buffer) {
  53507. buffer.dispose();
  53508. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  53509. }
  53510. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  53511. if (buffer) {
  53512. buffer.dispose();
  53513. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  53514. }
  53515. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  53516. this._lineShader.dispose();
  53517. };
  53518. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  53519. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53520. return 0;
  53521. }
  53522. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53523. return 1;
  53524. }
  53525. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53526. return 2;
  53527. }
  53528. return -1;
  53529. };
  53530. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53531. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53532. return 0;
  53533. }
  53534. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53535. return 1;
  53536. }
  53537. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53538. return 2;
  53539. }
  53540. return -1;
  53541. };
  53542. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53543. var needToCreateLine;
  53544. if (edge === undefined) {
  53545. needToCreateLine = true;
  53546. }
  53547. else {
  53548. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53549. needToCreateLine = dotProduct < this._epsilon;
  53550. }
  53551. if (needToCreateLine) {
  53552. var offset = this._linesPositions.length / 3;
  53553. var normal = p0.subtract(p1);
  53554. normal.normalize();
  53555. // Positions
  53556. this._linesPositions.push(p0.x);
  53557. this._linesPositions.push(p0.y);
  53558. this._linesPositions.push(p0.z);
  53559. this._linesPositions.push(p0.x);
  53560. this._linesPositions.push(p0.y);
  53561. this._linesPositions.push(p0.z);
  53562. this._linesPositions.push(p1.x);
  53563. this._linesPositions.push(p1.y);
  53564. this._linesPositions.push(p1.z);
  53565. this._linesPositions.push(p1.x);
  53566. this._linesPositions.push(p1.y);
  53567. this._linesPositions.push(p1.z);
  53568. // Normals
  53569. this._linesNormals.push(p1.x);
  53570. this._linesNormals.push(p1.y);
  53571. this._linesNormals.push(p1.z);
  53572. this._linesNormals.push(-1);
  53573. this._linesNormals.push(p1.x);
  53574. this._linesNormals.push(p1.y);
  53575. this._linesNormals.push(p1.z);
  53576. this._linesNormals.push(1);
  53577. this._linesNormals.push(p0.x);
  53578. this._linesNormals.push(p0.y);
  53579. this._linesNormals.push(p0.z);
  53580. this._linesNormals.push(-1);
  53581. this._linesNormals.push(p0.x);
  53582. this._linesNormals.push(p0.y);
  53583. this._linesNormals.push(p0.z);
  53584. this._linesNormals.push(1);
  53585. // Indices
  53586. this._linesIndices.push(offset);
  53587. this._linesIndices.push(offset + 1);
  53588. this._linesIndices.push(offset + 2);
  53589. this._linesIndices.push(offset);
  53590. this._linesIndices.push(offset + 2);
  53591. this._linesIndices.push(offset + 3);
  53592. }
  53593. };
  53594. EdgesRenderer.prototype._generateEdgesLines = function () {
  53595. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53596. var indices = this._source.getIndices();
  53597. // First let's find adjacencies
  53598. var adjacencies = new Array();
  53599. var faceNormals = new Array();
  53600. var index;
  53601. var faceAdjacencies;
  53602. // Prepare faces
  53603. for (index = 0; index < indices.length; index += 3) {
  53604. faceAdjacencies = new FaceAdjacencies();
  53605. var p0Index = indices[index];
  53606. var p1Index = indices[index + 1];
  53607. var p2Index = indices[index + 2];
  53608. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53609. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53610. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53611. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53612. faceNormal.normalize();
  53613. faceNormals.push(faceNormal);
  53614. adjacencies.push(faceAdjacencies);
  53615. }
  53616. // Scan
  53617. for (index = 0; index < adjacencies.length; index++) {
  53618. faceAdjacencies = adjacencies[index];
  53619. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53620. var otherFaceAdjacencies = adjacencies[otherIndex];
  53621. if (faceAdjacencies.edgesConnectedCount === 3) {
  53622. break;
  53623. }
  53624. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53625. continue;
  53626. }
  53627. var otherP0 = indices[otherIndex * 3];
  53628. var otherP1 = indices[otherIndex * 3 + 1];
  53629. var otherP2 = indices[otherIndex * 3 + 2];
  53630. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53631. var otherEdgeIndex;
  53632. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53633. continue;
  53634. }
  53635. switch (edgeIndex) {
  53636. case 0:
  53637. if (this._checkVerticesInsteadOfIndices) {
  53638. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53639. }
  53640. else {
  53641. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53642. }
  53643. break;
  53644. case 1:
  53645. if (this._checkVerticesInsteadOfIndices) {
  53646. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53647. }
  53648. else {
  53649. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53650. }
  53651. break;
  53652. case 2:
  53653. if (this._checkVerticesInsteadOfIndices) {
  53654. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53655. }
  53656. else {
  53657. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53658. }
  53659. break;
  53660. }
  53661. if (otherEdgeIndex === -1) {
  53662. continue;
  53663. }
  53664. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53665. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53666. faceAdjacencies.edgesConnectedCount++;
  53667. otherFaceAdjacencies.edgesConnectedCount++;
  53668. if (faceAdjacencies.edgesConnectedCount === 3) {
  53669. break;
  53670. }
  53671. }
  53672. }
  53673. }
  53674. // Create lines
  53675. for (index = 0; index < adjacencies.length; index++) {
  53676. // 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
  53677. var current = adjacencies[index];
  53678. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53679. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53680. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53681. }
  53682. // Merge into a single mesh
  53683. var engine = this._source.getScene().getEngine();
  53684. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53685. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53686. this._ib = engine.createIndexBuffer(this._linesIndices);
  53687. this._indicesCount = this._linesIndices.length;
  53688. };
  53689. EdgesRenderer.prototype.render = function () {
  53690. if (!this._lineShader.isReady()) {
  53691. return;
  53692. }
  53693. var scene = this._source.getScene();
  53694. var engine = scene.getEngine();
  53695. this._lineShader._preBind();
  53696. // VBOs
  53697. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53698. scene.resetCachedMaterial();
  53699. this._lineShader.setColor4("color", this._source.edgesColor);
  53700. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53701. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53702. }
  53703. else {
  53704. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53705. }
  53706. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53707. this._lineShader.bind(this._source.getWorldMatrix());
  53708. // Draw order
  53709. engine.draw(true, 0, this._indicesCount);
  53710. this._lineShader.unbind();
  53711. engine.setDepthWrite(true);
  53712. };
  53713. return EdgesRenderer;
  53714. }());
  53715. BABYLON.EdgesRenderer = EdgesRenderer;
  53716. })(BABYLON || (BABYLON = {}));
  53717. //# sourceMappingURL=babylon.edgesRenderer.js.map
  53718. var BABYLON;
  53719. (function (BABYLON) {
  53720. var TonemappingOperator;
  53721. (function (TonemappingOperator) {
  53722. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53723. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53724. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53725. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53726. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53727. ;
  53728. var TonemapPostProcess = (function (_super) {
  53729. __extends(TonemapPostProcess, _super);
  53730. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53732. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53733. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53734. _this._operator = _operator;
  53735. _this.exposureAdjustment = exposureAdjustment;
  53736. var defines = "#define ";
  53737. if (_this._operator === TonemappingOperator.Hable)
  53738. defines += "HABLE_TONEMAPPING";
  53739. else if (_this._operator === TonemappingOperator.Reinhard)
  53740. defines += "REINHARD_TONEMAPPING";
  53741. else if (_this._operator === TonemappingOperator.HejiDawson)
  53742. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53743. else if (_this._operator === TonemappingOperator.Photographic)
  53744. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53745. //sadly a second call to create the effect.
  53746. _this.updateEffect(defines);
  53747. _this.onApply = function (effect) {
  53748. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53749. };
  53750. return _this;
  53751. }
  53752. return TonemapPostProcess;
  53753. }(BABYLON.PostProcess));
  53754. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53755. })(BABYLON || (BABYLON = {}));
  53756. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53757. var BABYLON;
  53758. (function (BABYLON) {
  53759. var ReflectionProbe = (function () {
  53760. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53761. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53762. var _this = this;
  53763. this.name = name;
  53764. this._viewMatrix = BABYLON.Matrix.Identity();
  53765. this._target = BABYLON.Vector3.Zero();
  53766. this._add = BABYLON.Vector3.Zero();
  53767. this.invertYAxis = false;
  53768. this.position = BABYLON.Vector3.Zero();
  53769. this._scene = scene;
  53770. this._scene.reflectionProbes.push(this);
  53771. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53772. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53773. switch (faceIndex) {
  53774. case 0:
  53775. _this._add.copyFromFloats(1, 0, 0);
  53776. break;
  53777. case 1:
  53778. _this._add.copyFromFloats(-1, 0, 0);
  53779. break;
  53780. case 2:
  53781. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53782. break;
  53783. case 3:
  53784. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53785. break;
  53786. case 4:
  53787. _this._add.copyFromFloats(0, 0, 1);
  53788. break;
  53789. case 5:
  53790. _this._add.copyFromFloats(0, 0, -1);
  53791. break;
  53792. }
  53793. if (_this._attachedMesh) {
  53794. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53795. }
  53796. _this.position.addToRef(_this._add, _this._target);
  53797. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53798. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53799. });
  53800. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53801. scene.updateTransformMatrix(true);
  53802. });
  53803. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53804. }
  53805. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  53806. get: function () {
  53807. return this._renderTargetTexture.samples;
  53808. },
  53809. set: function (value) {
  53810. this._renderTargetTexture.samples = value;
  53811. },
  53812. enumerable: true,
  53813. configurable: true
  53814. });
  53815. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53816. get: function () {
  53817. return this._renderTargetTexture.refreshRate;
  53818. },
  53819. set: function (value) {
  53820. this._renderTargetTexture.refreshRate = value;
  53821. },
  53822. enumerable: true,
  53823. configurable: true
  53824. });
  53825. ReflectionProbe.prototype.getScene = function () {
  53826. return this._scene;
  53827. };
  53828. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  53829. get: function () {
  53830. return this._renderTargetTexture;
  53831. },
  53832. enumerable: true,
  53833. configurable: true
  53834. });
  53835. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  53836. get: function () {
  53837. return this._renderTargetTexture.renderList;
  53838. },
  53839. enumerable: true,
  53840. configurable: true
  53841. });
  53842. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  53843. this._attachedMesh = mesh;
  53844. };
  53845. ReflectionProbe.prototype.dispose = function () {
  53846. var index = this._scene.reflectionProbes.indexOf(this);
  53847. if (index !== -1) {
  53848. // Remove from the scene if found
  53849. this._scene.reflectionProbes.splice(index, 1);
  53850. }
  53851. if (this._renderTargetTexture) {
  53852. this._renderTargetTexture.dispose();
  53853. this._renderTargetTexture = null;
  53854. }
  53855. };
  53856. return ReflectionProbe;
  53857. }());
  53858. BABYLON.ReflectionProbe = ReflectionProbe;
  53859. })(BABYLON || (BABYLON = {}));
  53860. //# sourceMappingURL=babylon.reflectionProbe.js.map
  53861. var BABYLON;
  53862. (function (BABYLON) {
  53863. var SolidParticle = (function () {
  53864. /**
  53865. * Creates a Solid Particle object.
  53866. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53867. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53868. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53869. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  53870. * `shapeId` (integer) is the model shape identifier in the SPS.
  53871. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53872. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  53873. */
  53874. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53875. this.idx = 0; // particle global index
  53876. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  53877. this.position = BABYLON.Vector3.Zero(); // position
  53878. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53879. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  53880. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  53881. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53882. this.alive = true; // alive
  53883. this.isVisible = true; // visibility
  53884. this._pos = 0; // index of this particle in the global "positions" array
  53885. this.shapeId = 0; // model shape id
  53886. this.idxInShape = 0; // index of the particle in its shape id
  53887. this.idx = particleIndex;
  53888. this._pos = positionIndex;
  53889. this._model = model;
  53890. this.shapeId = shapeId;
  53891. this.idxInShape = idxInShape;
  53892. this._sps = sps;
  53893. if (modelBoundingInfo) {
  53894. this._modelBoundingInfo = modelBoundingInfo;
  53895. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53896. }
  53897. }
  53898. Object.defineProperty(SolidParticle.prototype, "scale", {
  53899. /**
  53900. * legacy support, changed scale to scaling
  53901. */
  53902. get: function () {
  53903. return this.scaling;
  53904. },
  53905. set: function (scale) {
  53906. this.scaling = scale;
  53907. },
  53908. enumerable: true,
  53909. configurable: true
  53910. });
  53911. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53912. /**
  53913. * legacy support, changed quaternion to rotationQuaternion
  53914. */
  53915. get: function () {
  53916. return this.rotationQuaternion;
  53917. },
  53918. set: function (q) {
  53919. this.rotationQuaternion = q;
  53920. },
  53921. enumerable: true,
  53922. configurable: true
  53923. });
  53924. /**
  53925. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53926. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53927. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  53928. */
  53929. SolidParticle.prototype.intersectsMesh = function (target) {
  53930. if (!this._boundingInfo || !target._boundingInfo) {
  53931. return false;
  53932. }
  53933. if (this._sps._bSphereOnly) {
  53934. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53935. }
  53936. return this._boundingInfo.intersects(target._boundingInfo, false);
  53937. };
  53938. return SolidParticle;
  53939. }());
  53940. BABYLON.SolidParticle = SolidParticle;
  53941. var ModelShape = (function () {
  53942. /**
  53943. * 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.
  53944. * SPS internal tool, don't use it manually.
  53945. */
  53946. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  53947. this.shapeID = id;
  53948. this._shape = shape;
  53949. this._shapeUV = shapeUV;
  53950. this._positionFunction = posFunction;
  53951. this._vertexFunction = vtxFunction;
  53952. }
  53953. return ModelShape;
  53954. }());
  53955. BABYLON.ModelShape = ModelShape;
  53956. })(BABYLON || (BABYLON = {}));
  53957. //# sourceMappingURL=babylon.solidParticle.js.map
  53958. var BABYLON;
  53959. (function (BABYLON) {
  53960. /**
  53961. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53962. */
  53963. var SolidParticleSystem = (function () {
  53964. /**
  53965. * Creates a SPS (Solid Particle System) object.
  53966. * `name` (String) is the SPS name, this will be the underlying mesh name.
  53967. * `scene` (Scene) is the scene in which the SPS is added.
  53968. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  53969. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  53970. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  53971. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53972. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53973. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53974. */
  53975. function SolidParticleSystem(name, scene, options) {
  53976. // public members
  53977. /**
  53978. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53979. * Example : var p = SPS.particles[i];
  53980. */
  53981. this.particles = new Array();
  53982. /**
  53983. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53984. */
  53985. this.nbParticles = 0;
  53986. /**
  53987. * If the particles must ever face the camera (default false). Useful for planar particles.
  53988. */
  53989. this.billboard = false;
  53990. /**
  53991. * Recompute normals when adding a shape
  53992. */
  53993. this.recomputeNormals = true;
  53994. /**
  53995. * This a counter ofr your own usage. It's not set by any SPS functions.
  53996. */
  53997. this.counter = 0;
  53998. /**
  53999. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54000. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54001. */
  54002. this.vars = {};
  54003. this._positions = new Array();
  54004. this._indices = new Array();
  54005. this._normals = new Array();
  54006. this._colors = new Array();
  54007. this._uvs = new Array();
  54008. this._index = 0; // indices index
  54009. this._updatable = true;
  54010. this._pickable = false;
  54011. this._isVisibilityBoxLocked = false;
  54012. this._alwaysVisible = false;
  54013. this._shapeCounter = 0;
  54014. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  54015. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54016. this._computeParticleColor = true;
  54017. this._computeParticleTexture = true;
  54018. this._computeParticleRotation = true;
  54019. this._computeParticleVertex = false;
  54020. this._computeBoundingBox = false;
  54021. this._cam_axisZ = BABYLON.Vector3.Zero();
  54022. this._cam_axisY = BABYLON.Vector3.Zero();
  54023. this._cam_axisX = BABYLON.Vector3.Zero();
  54024. this._axisX = BABYLON.Axis.X;
  54025. this._axisY = BABYLON.Axis.Y;
  54026. this._axisZ = BABYLON.Axis.Z;
  54027. this._camDir = BABYLON.Vector3.Zero();
  54028. this._rotMatrix = new BABYLON.Matrix();
  54029. this._invertMatrix = new BABYLON.Matrix();
  54030. this._rotated = BABYLON.Vector3.Zero();
  54031. this._quaternion = new BABYLON.Quaternion();
  54032. this._vertex = BABYLON.Vector3.Zero();
  54033. this._normal = BABYLON.Vector3.Zero();
  54034. this._yaw = 0.0;
  54035. this._pitch = 0.0;
  54036. this._roll = 0.0;
  54037. this._halfroll = 0.0;
  54038. this._halfpitch = 0.0;
  54039. this._halfyaw = 0.0;
  54040. this._sinRoll = 0.0;
  54041. this._cosRoll = 0.0;
  54042. this._sinPitch = 0.0;
  54043. this._cosPitch = 0.0;
  54044. this._sinYaw = 0.0;
  54045. this._cosYaw = 0.0;
  54046. this._w = 0.0;
  54047. this._mustUnrotateFixedNormals = false;
  54048. this._minimum = BABYLON.Tmp.Vector3[0];
  54049. this._maximum = BABYLON.Tmp.Vector3[1];
  54050. this._scale = BABYLON.Tmp.Vector3[2];
  54051. this._translation = BABYLON.Tmp.Vector3[3];
  54052. this._minBbox = BABYLON.Tmp.Vector3[4];
  54053. this._maxBbox = BABYLON.Tmp.Vector3[5];
  54054. this._particlesIntersect = false;
  54055. this._bSphereOnly = false;
  54056. this._bSphereRadiusFactor = 1.0;
  54057. this.name = name;
  54058. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54059. this._camera = scene.activeCamera;
  54060. this._pickable = options ? options.isPickable : false;
  54061. this._particlesIntersect = options ? options.particleIntersection : false;
  54062. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54063. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54064. if (options && options.updatable) {
  54065. this._updatable = options.updatable;
  54066. }
  54067. else {
  54068. this._updatable = true;
  54069. }
  54070. if (this._pickable) {
  54071. this.pickedParticles = [];
  54072. }
  54073. }
  54074. /**
  54075. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54076. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54077. */
  54078. SolidParticleSystem.prototype.buildMesh = function () {
  54079. if (this.nbParticles === 0) {
  54080. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54081. this.addShape(triangle, 1);
  54082. triangle.dispose();
  54083. }
  54084. this._positions32 = new Float32Array(this._positions);
  54085. this._uvs32 = new Float32Array(this._uvs);
  54086. this._colors32 = new Float32Array(this._colors);
  54087. if (this.recomputeNormals) {
  54088. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  54089. }
  54090. this._normals32 = new Float32Array(this._normals);
  54091. this._fixedNormal32 = new Float32Array(this._normals);
  54092. if (this._mustUnrotateFixedNormals) {
  54093. this._unrotateFixedNormals();
  54094. }
  54095. var vertexData = new BABYLON.VertexData();
  54096. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54097. vertexData.indices = this._indices;
  54098. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54099. if (this._uvs32) {
  54100. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54101. ;
  54102. }
  54103. if (this._colors32) {
  54104. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54105. }
  54106. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54107. vertexData.applyToMesh(mesh, this._updatable);
  54108. this.mesh = mesh;
  54109. this.mesh.isPickable = this._pickable;
  54110. // free memory
  54111. this._positions = null;
  54112. this._normals = null;
  54113. this._uvs = null;
  54114. this._colors = null;
  54115. if (!this._updatable) {
  54116. this.particles.length = 0;
  54117. }
  54118. return mesh;
  54119. };
  54120. /**
  54121. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54122. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54123. * Thus the particles generated from `digest()` have their property `position` set yet.
  54124. * `mesh` ( Mesh ) is the mesh to be digested
  54125. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  54126. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54127. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54128. */
  54129. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54130. var size = (options && options.facetNb) || 1;
  54131. var number = (options && options.number);
  54132. var delta = (options && options.delta) || 0;
  54133. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54134. var meshInd = mesh.getIndices();
  54135. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54136. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54137. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54138. var f = 0; // facet counter
  54139. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54140. // compute size from number
  54141. if (number) {
  54142. number = (number > totalFacets) ? totalFacets : number;
  54143. size = Math.round(totalFacets / number);
  54144. delta = 0;
  54145. }
  54146. else {
  54147. size = (size > totalFacets) ? totalFacets : size;
  54148. }
  54149. var facetPos = []; // submesh positions
  54150. var facetInd = []; // submesh indices
  54151. var facetUV = []; // submesh UV
  54152. var facetCol = []; // submesh colors
  54153. var barycenter = BABYLON.Tmp.Vector3[0];
  54154. var rand;
  54155. var sizeO = size;
  54156. while (f < totalFacets) {
  54157. size = sizeO + Math.floor((1 + delta) * Math.random());
  54158. if (f > totalFacets - size) {
  54159. size = totalFacets - f;
  54160. }
  54161. // reset temp arrays
  54162. facetPos.length = 0;
  54163. facetInd.length = 0;
  54164. facetUV.length = 0;
  54165. facetCol.length = 0;
  54166. // iterate over "size" facets
  54167. var fi = 0;
  54168. for (var j = f * 3; j < (f + size) * 3; j++) {
  54169. facetInd.push(fi);
  54170. var i = meshInd[j];
  54171. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54172. if (meshUV) {
  54173. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54174. }
  54175. if (meshCol) {
  54176. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54177. }
  54178. fi++;
  54179. }
  54180. // create a model shape for each single particle
  54181. var idx = this.nbParticles;
  54182. var shape = this._posToShape(facetPos);
  54183. var shapeUV = this._uvsToShapeUV(facetUV);
  54184. // compute the barycenter of the shape
  54185. var v;
  54186. for (v = 0; v < shape.length; v++) {
  54187. barycenter.addInPlace(shape[v]);
  54188. }
  54189. barycenter.scaleInPlace(1 / shape.length);
  54190. // shift the shape from its barycenter to the origin
  54191. for (v = 0; v < shape.length; v++) {
  54192. shape[v].subtractInPlace(barycenter);
  54193. }
  54194. var bInfo;
  54195. if (this._particlesIntersect) {
  54196. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54197. }
  54198. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  54199. // add the particle in the SPS
  54200. var currentPos = this._positions.length;
  54201. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54202. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  54203. // initialize the particle position
  54204. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54205. this._index += shape.length;
  54206. idx++;
  54207. this.nbParticles++;
  54208. this._shapeCounter++;
  54209. f += size;
  54210. }
  54211. return this;
  54212. };
  54213. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54214. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54215. var index = 0;
  54216. var idx = 0;
  54217. for (var p = 0; p < this.particles.length; p++) {
  54218. this._particle = this.particles[p];
  54219. this._shape = this._particle._model._shape;
  54220. if (this._particle.rotationQuaternion) {
  54221. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54222. }
  54223. else {
  54224. this._yaw = this._particle.rotation.y;
  54225. this._pitch = this._particle.rotation.x;
  54226. this._roll = this._particle.rotation.z;
  54227. this._quaternionRotationYPR();
  54228. }
  54229. this._quaternionToRotationMatrix();
  54230. this._rotMatrix.invertToRef(this._invertMatrix);
  54231. for (var pt = 0; pt < this._shape.length; pt++) {
  54232. idx = index + pt * 3;
  54233. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54234. this._fixedNormal32[idx] = this._normal.x;
  54235. this._fixedNormal32[idx + 1] = this._normal.y;
  54236. this._fixedNormal32[idx + 2] = this._normal.z;
  54237. }
  54238. index = idx + 3;
  54239. }
  54240. };
  54241. //reset copy
  54242. SolidParticleSystem.prototype._resetCopy = function () {
  54243. this._copy.position.x = 0;
  54244. this._copy.position.y = 0;
  54245. this._copy.position.z = 0;
  54246. this._copy.rotation.x = 0;
  54247. this._copy.rotation.y = 0;
  54248. this._copy.rotation.z = 0;
  54249. this._copy.rotationQuaternion = null;
  54250. this._copy.scaling.x = 1;
  54251. this._copy.scaling.y = 1;
  54252. this._copy.scaling.z = 1;
  54253. this._copy.uvs.x = 0;
  54254. this._copy.uvs.y = 0;
  54255. this._copy.uvs.z = 1;
  54256. this._copy.uvs.w = 1;
  54257. this._copy.color = null;
  54258. };
  54259. // _meshBuilder : inserts the shape model in the global SPS mesh
  54260. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54261. var i;
  54262. var u = 0;
  54263. var c = 0;
  54264. var n = 0;
  54265. this._resetCopy();
  54266. if (options && options.positionFunction) {
  54267. options.positionFunction(this._copy, idx, idxInShape);
  54268. this._mustUnrotateFixedNormals = true;
  54269. }
  54270. if (this._copy.rotationQuaternion) {
  54271. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54272. }
  54273. else {
  54274. this._yaw = this._copy.rotation.y;
  54275. this._pitch = this._copy.rotation.x;
  54276. this._roll = this._copy.rotation.z;
  54277. this._quaternionRotationYPR();
  54278. }
  54279. this._quaternionToRotationMatrix();
  54280. for (i = 0; i < shape.length; i++) {
  54281. this._vertex.x = shape[i].x;
  54282. this._vertex.y = shape[i].y;
  54283. this._vertex.z = shape[i].z;
  54284. if (options && options.vertexFunction) {
  54285. options.vertexFunction(this._copy, this._vertex, i);
  54286. }
  54287. this._vertex.x *= this._copy.scaling.x;
  54288. this._vertex.y *= this._copy.scaling.y;
  54289. this._vertex.z *= this._copy.scaling.z;
  54290. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54291. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54292. if (meshUV) {
  54293. 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);
  54294. u += 2;
  54295. }
  54296. if (this._copy.color) {
  54297. this._color = this._copy.color;
  54298. }
  54299. else if (meshCol && meshCol[c] !== undefined) {
  54300. this._color.r = meshCol[c];
  54301. this._color.g = meshCol[c + 1];
  54302. this._color.b = meshCol[c + 2];
  54303. this._color.a = meshCol[c + 3];
  54304. }
  54305. else {
  54306. this._color.r = 1;
  54307. this._color.g = 1;
  54308. this._color.b = 1;
  54309. this._color.a = 1;
  54310. }
  54311. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54312. c += 4;
  54313. if (!this.recomputeNormals && meshNor) {
  54314. this._normal.x = meshNor[n];
  54315. this._normal.y = meshNor[n + 1];
  54316. this._normal.z = meshNor[n + 2];
  54317. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54318. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54319. n += 3;
  54320. }
  54321. }
  54322. for (i = 0; i < meshInd.length; i++) {
  54323. indices.push(p + meshInd[i]);
  54324. }
  54325. if (this._pickable) {
  54326. var nbfaces = meshInd.length / 3;
  54327. for (i = 0; i < nbfaces; i++) {
  54328. this.pickedParticles.push({ idx: idx, faceId: i });
  54329. }
  54330. }
  54331. return this._copy;
  54332. };
  54333. // returns a shape array from positions array
  54334. SolidParticleSystem.prototype._posToShape = function (positions) {
  54335. var shape = [];
  54336. for (var i = 0; i < positions.length; i += 3) {
  54337. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54338. }
  54339. return shape;
  54340. };
  54341. // returns a shapeUV array from a Vector4 uvs
  54342. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54343. var shapeUV = [];
  54344. if (uvs) {
  54345. for (var i = 0; i < uvs.length; i++)
  54346. shapeUV.push(uvs[i]);
  54347. }
  54348. return shapeUV;
  54349. };
  54350. // adds a new particle object in the particles array
  54351. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  54352. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  54353. this.particles.push(sp);
  54354. return sp;
  54355. };
  54356. /**
  54357. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54358. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54359. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  54360. * `nb` (positive integer) the number of particles to be created from this model
  54361. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  54362. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  54363. */
  54364. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54365. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54366. var meshInd = mesh.getIndices();
  54367. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54368. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54369. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54370. var bbInfo;
  54371. if (this._particlesIntersect) {
  54372. bbInfo = mesh.getBoundingInfo();
  54373. }
  54374. var shape = this._posToShape(meshPos);
  54375. var shapeUV = this._uvsToShapeUV(meshUV);
  54376. var posfunc = options ? options.positionFunction : null;
  54377. var vtxfunc = options ? options.vertexFunction : null;
  54378. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  54379. // particles
  54380. var sp;
  54381. var currentCopy;
  54382. var idx = this.nbParticles;
  54383. for (var i = 0; i < nb; i++) {
  54384. var currentPos = this._positions.length;
  54385. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54386. if (this._updatable) {
  54387. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  54388. sp.position.copyFrom(currentCopy.position);
  54389. sp.rotation.copyFrom(currentCopy.rotation);
  54390. if (currentCopy.rotationQuaternion) {
  54391. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54392. }
  54393. if (currentCopy.color) {
  54394. sp.color.copyFrom(currentCopy.color);
  54395. }
  54396. sp.scaling.copyFrom(currentCopy.scaling);
  54397. sp.uvs.copyFrom(currentCopy.uvs);
  54398. }
  54399. this._index += shape.length;
  54400. idx++;
  54401. }
  54402. this.nbParticles += nb;
  54403. this._shapeCounter++;
  54404. return this._shapeCounter - 1;
  54405. };
  54406. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54407. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54408. this._resetCopy();
  54409. if (particle._model._positionFunction) {
  54410. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54411. }
  54412. if (this._copy.rotationQuaternion) {
  54413. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54414. }
  54415. else {
  54416. this._yaw = this._copy.rotation.y;
  54417. this._pitch = this._copy.rotation.x;
  54418. this._roll = this._copy.rotation.z;
  54419. this._quaternionRotationYPR();
  54420. }
  54421. this._quaternionToRotationMatrix();
  54422. this._shape = particle._model._shape;
  54423. for (var pt = 0; pt < this._shape.length; pt++) {
  54424. this._vertex.x = this._shape[pt].x;
  54425. this._vertex.y = this._shape[pt].y;
  54426. this._vertex.z = this._shape[pt].z;
  54427. if (particle._model._vertexFunction) {
  54428. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54429. }
  54430. this._vertex.x *= this._copy.scaling.x;
  54431. this._vertex.y *= this._copy.scaling.y;
  54432. this._vertex.z *= this._copy.scaling.z;
  54433. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54434. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54435. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54436. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54437. }
  54438. particle.position.x = 0.0;
  54439. particle.position.y = 0.0;
  54440. particle.position.z = 0.0;
  54441. particle.rotation.x = 0.0;
  54442. particle.rotation.y = 0.0;
  54443. particle.rotation.z = 0.0;
  54444. particle.rotationQuaternion = null;
  54445. particle.scaling.x = 1.0;
  54446. particle.scaling.y = 1.0;
  54447. particle.scaling.z = 1.0;
  54448. };
  54449. /**
  54450. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54451. * Returns the SPS.
  54452. */
  54453. SolidParticleSystem.prototype.rebuildMesh = function () {
  54454. for (var p = 0; p < this.particles.length; p++) {
  54455. this._rebuildParticle(this.particles[p]);
  54456. }
  54457. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54458. return this;
  54459. };
  54460. /**
  54461. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54462. * This method calls `updateParticle()` for each particle of the SPS.
  54463. * For an animated SPS, it is usually called within the render loop.
  54464. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54465. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54466. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54467. * Returns the SPS.
  54468. */
  54469. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54470. if (start === void 0) { start = 0; }
  54471. if (end === void 0) { end = this.nbParticles - 1; }
  54472. if (update === void 0) { update = true; }
  54473. if (!this._updatable) {
  54474. return;
  54475. }
  54476. // custom beforeUpdate
  54477. this.beforeUpdateParticles(start, end, update);
  54478. this._cam_axisX.x = 1.0;
  54479. this._cam_axisX.y = 0.0;
  54480. this._cam_axisX.z = 0.0;
  54481. this._cam_axisY.x = 0.0;
  54482. this._cam_axisY.y = 1.0;
  54483. this._cam_axisY.z = 0.0;
  54484. this._cam_axisZ.x = 0.0;
  54485. this._cam_axisZ.y = 0.0;
  54486. this._cam_axisZ.z = 1.0;
  54487. // if the particles will always face the camera
  54488. if (this.billboard) {
  54489. this.mesh.computeWorldMatrix(true);
  54490. // compute the camera position and un-rotate it by the current mesh rotation
  54491. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  54492. this._quaternionToRotationMatrix();
  54493. this._rotMatrix.invertToRef(this._invertMatrix);
  54494. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  54495. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54496. this._cam_axisZ.normalize();
  54497. // same for camera up vector extracted from the cam view matrix
  54498. var view = this._camera.getViewMatrix(true);
  54499. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54500. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54501. this._cam_axisY.normalize();
  54502. this._cam_axisX.normalize();
  54503. }
  54504. }
  54505. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54506. var idx = 0; // current position index in the global array positions32
  54507. var index = 0; // position start index in the global array positions32 of the current particle
  54508. var colidx = 0; // current color index in the global array colors32
  54509. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54510. var uvidx = 0; // current uv index in the global array uvs32
  54511. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54512. var pt = 0; // current index in the particle model shape
  54513. if (this.mesh.isFacetDataEnabled) {
  54514. this._computeBoundingBox = true;
  54515. }
  54516. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54517. if (this._computeBoundingBox) {
  54518. if (start == 0 && end == this.nbParticles - 1) {
  54519. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54520. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54521. }
  54522. else {
  54523. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54524. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54525. }
  54526. }
  54527. // particle loop
  54528. index = this.particles[start]._pos;
  54529. var vpos = (index / 3) | 0;
  54530. colorIndex = vpos * 4;
  54531. uvIndex = vpos * 2;
  54532. for (var p = start; p <= end; p++) {
  54533. this._particle = this.particles[p];
  54534. this._shape = this._particle._model._shape;
  54535. this._shapeUV = this._particle._model._shapeUV;
  54536. // call to custom user function to update the particle properties
  54537. this.updateParticle(this._particle);
  54538. if (this._particle.isVisible) {
  54539. // particle rotation matrix
  54540. if (this.billboard) {
  54541. this._particle.rotation.x = 0.0;
  54542. this._particle.rotation.y = 0.0;
  54543. }
  54544. if (this._computeParticleRotation || this.billboard) {
  54545. if (this._particle.rotationQuaternion) {
  54546. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54547. }
  54548. else {
  54549. this._yaw = this._particle.rotation.y;
  54550. this._pitch = this._particle.rotation.x;
  54551. this._roll = this._particle.rotation.z;
  54552. this._quaternionRotationYPR();
  54553. }
  54554. this._quaternionToRotationMatrix();
  54555. }
  54556. // particle vertex loop
  54557. for (pt = 0; pt < this._shape.length; pt++) {
  54558. idx = index + pt * 3;
  54559. colidx = colorIndex + pt * 4;
  54560. uvidx = uvIndex + pt * 2;
  54561. this._vertex.x = this._shape[pt].x;
  54562. this._vertex.y = this._shape[pt].y;
  54563. this._vertex.z = this._shape[pt].z;
  54564. if (this._computeParticleVertex) {
  54565. this.updateParticleVertex(this._particle, this._vertex, pt);
  54566. }
  54567. // positions
  54568. this._vertex.x *= this._particle.scaling.x;
  54569. this._vertex.y *= this._particle.scaling.y;
  54570. this._vertex.z *= this._particle.scaling.z;
  54571. 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];
  54572. 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;
  54573. 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;
  54574. 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;
  54575. 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;
  54576. 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;
  54577. 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;
  54578. if (this._computeBoundingBox) {
  54579. if (this._positions32[idx] < this._minimum.x) {
  54580. this._minimum.x = this._positions32[idx];
  54581. }
  54582. if (this._positions32[idx] > this._maximum.x) {
  54583. this._maximum.x = this._positions32[idx];
  54584. }
  54585. if (this._positions32[idx + 1] < this._minimum.y) {
  54586. this._minimum.y = this._positions32[idx + 1];
  54587. }
  54588. if (this._positions32[idx + 1] > this._maximum.y) {
  54589. this._maximum.y = this._positions32[idx + 1];
  54590. }
  54591. if (this._positions32[idx + 2] < this._minimum.z) {
  54592. this._minimum.z = this._positions32[idx + 2];
  54593. }
  54594. if (this._positions32[idx + 2] > this._maximum.z) {
  54595. this._maximum.z = this._positions32[idx + 2];
  54596. }
  54597. }
  54598. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54599. if (!this._computeParticleVertex) {
  54600. this._normal.x = this._fixedNormal32[idx];
  54601. this._normal.y = this._fixedNormal32[idx + 1];
  54602. this._normal.z = this._fixedNormal32[idx + 2];
  54603. 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]);
  54604. 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]);
  54605. 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]);
  54606. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54607. 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;
  54608. 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;
  54609. }
  54610. if (this._computeParticleColor) {
  54611. this._colors32[colidx] = this._particle.color.r;
  54612. this._colors32[colidx + 1] = this._particle.color.g;
  54613. this._colors32[colidx + 2] = this._particle.color.b;
  54614. this._colors32[colidx + 3] = this._particle.color.a;
  54615. }
  54616. if (this._computeParticleTexture) {
  54617. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54618. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54619. }
  54620. }
  54621. }
  54622. else {
  54623. for (pt = 0; pt < this._shape.length; pt++) {
  54624. idx = index + pt * 3;
  54625. colidx = colorIndex + pt * 4;
  54626. uvidx = uvIndex + pt * 2;
  54627. this._positions32[idx] = this._camera.position.x;
  54628. this._positions32[idx + 1] = this._camera.position.y;
  54629. this._positions32[idx + 2] = this._camera.position.z;
  54630. this._normals32[idx] = 0.0;
  54631. this._normals32[idx + 1] = 0.0;
  54632. this._normals32[idx + 2] = 0.0;
  54633. if (this._computeParticleColor) {
  54634. this._colors32[colidx] = this._particle.color.r;
  54635. this._colors32[colidx + 1] = this._particle.color.g;
  54636. this._colors32[colidx + 2] = this._particle.color.b;
  54637. this._colors32[colidx + 3] = this._particle.color.a;
  54638. }
  54639. if (this._computeParticleTexture) {
  54640. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54641. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54642. }
  54643. }
  54644. }
  54645. // if the particle intersections must be computed : update the bbInfo
  54646. if (this._particlesIntersect) {
  54647. var bInfo = this._particle._boundingInfo;
  54648. var bBox = bInfo.boundingBox;
  54649. var bSphere = bInfo.boundingSphere;
  54650. if (!this._bSphereOnly) {
  54651. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54652. for (var b = 0; b < bBox.vectors.length; b++) {
  54653. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54654. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54655. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54656. 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];
  54657. 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;
  54658. 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;
  54659. 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;
  54660. 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;
  54661. 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;
  54662. 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;
  54663. }
  54664. bBox._update(this.mesh._worldMatrix);
  54665. }
  54666. // place and scale the particle bouding sphere in the SPS local system, then update it
  54667. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54668. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54669. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54670. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54671. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54672. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54673. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54674. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54675. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54676. 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));
  54677. bSphere._update(this.mesh._worldMatrix);
  54678. }
  54679. // increment indexes for the next particle
  54680. index = idx + 3;
  54681. colorIndex = colidx + 4;
  54682. uvIndex = uvidx + 2;
  54683. }
  54684. // if the VBO must be updated
  54685. if (update) {
  54686. if (this._computeParticleColor) {
  54687. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54688. }
  54689. if (this._computeParticleTexture) {
  54690. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54691. }
  54692. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54693. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54694. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54695. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54696. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54697. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  54698. for (var i = 0; i < this._normals32.length; i++) {
  54699. this._fixedNormal32[i] = this._normals32[i];
  54700. }
  54701. }
  54702. if (!this.mesh.areNormalsFrozen) {
  54703. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54704. }
  54705. }
  54706. }
  54707. if (this._computeBoundingBox) {
  54708. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54709. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54710. }
  54711. this.afterUpdateParticles(start, end, update);
  54712. return this;
  54713. };
  54714. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54715. this._halfroll = this._roll * 0.5;
  54716. this._halfpitch = this._pitch * 0.5;
  54717. this._halfyaw = this._yaw * 0.5;
  54718. this._sinRoll = Math.sin(this._halfroll);
  54719. this._cosRoll = Math.cos(this._halfroll);
  54720. this._sinPitch = Math.sin(this._halfpitch);
  54721. this._cosPitch = Math.cos(this._halfpitch);
  54722. this._sinYaw = Math.sin(this._halfyaw);
  54723. this._cosYaw = Math.cos(this._halfyaw);
  54724. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54725. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54726. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54727. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54728. };
  54729. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54730. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54731. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54732. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54733. this._rotMatrix.m[3] = 0;
  54734. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54735. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54736. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54737. this._rotMatrix.m[7] = 0;
  54738. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54739. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54740. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54741. this._rotMatrix.m[11] = 0;
  54742. this._rotMatrix.m[12] = 0;
  54743. this._rotMatrix.m[13] = 0;
  54744. this._rotMatrix.m[14] = 0;
  54745. this._rotMatrix.m[15] = 1.0;
  54746. };
  54747. /**
  54748. * Disposes the SPS.
  54749. * Returns nothing.
  54750. */
  54751. SolidParticleSystem.prototype.dispose = function () {
  54752. this.mesh.dispose();
  54753. this.vars = null;
  54754. // drop references to internal big arrays for the GC
  54755. this._positions = null;
  54756. this._indices = null;
  54757. this._normals = null;
  54758. this._uvs = null;
  54759. this._colors = null;
  54760. this._positions32 = null;
  54761. this._normals32 = null;
  54762. this._fixedNormal32 = null;
  54763. this._uvs32 = null;
  54764. this._colors32 = null;
  54765. this.pickedParticles = null;
  54766. };
  54767. /**
  54768. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54769. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54770. * Returns the SPS.
  54771. */
  54772. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54773. if (!this._isVisibilityBoxLocked) {
  54774. this.mesh.refreshBoundingInfo();
  54775. }
  54776. return this;
  54777. };
  54778. /**
  54779. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54780. * @param size the size (float) of the visibility box
  54781. * note : this doesn't lock the SPS mesh bounding box.
  54782. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54783. */
  54784. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54785. var vis = size / 2;
  54786. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54787. };
  54788. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54789. // getter and setter
  54790. get: function () {
  54791. return this._alwaysVisible;
  54792. },
  54793. /**
  54794. * Sets the SPS as always visible or not
  54795. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54796. */
  54797. set: function (val) {
  54798. this._alwaysVisible = val;
  54799. this.mesh.alwaysSelectAsActiveMesh = val;
  54800. },
  54801. enumerable: true,
  54802. configurable: true
  54803. });
  54804. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54805. get: function () {
  54806. return this._isVisibilityBoxLocked;
  54807. },
  54808. /**
  54809. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54810. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54811. */
  54812. set: function (val) {
  54813. this._isVisibilityBoxLocked = val;
  54814. this.mesh.getBoundingInfo().isLocked = val;
  54815. },
  54816. enumerable: true,
  54817. configurable: true
  54818. });
  54819. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54820. // getters
  54821. get: function () {
  54822. return this._computeParticleRotation;
  54823. },
  54824. // Optimizer setters
  54825. /**
  54826. * Tells to `setParticles()` to compute the particle rotations or not.
  54827. * Default value : true. The SPS is faster when it's set to false.
  54828. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54829. */
  54830. set: function (val) {
  54831. this._computeParticleRotation = val;
  54832. },
  54833. enumerable: true,
  54834. configurable: true
  54835. });
  54836. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54837. get: function () {
  54838. return this._computeParticleColor;
  54839. },
  54840. /**
  54841. * Tells to `setParticles()` to compute the particle colors or not.
  54842. * Default value : true. The SPS is faster when it's set to false.
  54843. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54844. */
  54845. set: function (val) {
  54846. this._computeParticleColor = val;
  54847. },
  54848. enumerable: true,
  54849. configurable: true
  54850. });
  54851. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54852. get: function () {
  54853. return this._computeParticleTexture;
  54854. },
  54855. /**
  54856. * Tells to `setParticles()` to compute the particle textures or not.
  54857. * Default value : true. The SPS is faster when it's set to false.
  54858. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54859. */
  54860. set: function (val) {
  54861. this._computeParticleTexture = val;
  54862. },
  54863. enumerable: true,
  54864. configurable: true
  54865. });
  54866. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54867. get: function () {
  54868. return this._computeParticleVertex;
  54869. },
  54870. /**
  54871. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54872. * Default value : false. The SPS is faster when it's set to false.
  54873. * Note : the particle custom vertex positions aren't stored values.
  54874. */
  54875. set: function (val) {
  54876. this._computeParticleVertex = val;
  54877. },
  54878. enumerable: true,
  54879. configurable: true
  54880. });
  54881. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54882. get: function () {
  54883. return this._computeBoundingBox;
  54884. },
  54885. /**
  54886. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54887. */
  54888. set: function (val) {
  54889. this._computeBoundingBox = val;
  54890. },
  54891. enumerable: true,
  54892. configurable: true
  54893. });
  54894. // =======================================================================
  54895. // Particle behavior logic
  54896. // these following methods may be overwritten by the user to fit his needs
  54897. /**
  54898. * This function does nothing. It may be overwritten to set all the particle first values.
  54899. * The SPS doesn't call this function, you may have to call it by your own.
  54900. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54901. */
  54902. SolidParticleSystem.prototype.initParticles = function () {
  54903. };
  54904. /**
  54905. * This function does nothing. It may be overwritten to recycle a particle.
  54906. * The SPS doesn't call this function, you may have to call it by your own.
  54907. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54908. */
  54909. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54910. return particle;
  54911. };
  54912. /**
  54913. * Updates a particle : this function should be overwritten by the user.
  54914. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54915. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54916. * ex : just set a particle position or velocity and recycle conditions
  54917. */
  54918. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54919. return particle;
  54920. };
  54921. /**
  54922. * Updates a vertex of a particle : it can be overwritten by the user.
  54923. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54924. * @param particle the current particle
  54925. * @param vertex the current index of the current particle
  54926. * @param pt the index of the current vertex in the particle shape
  54927. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54928. * ex : just set a vertex particle position
  54929. */
  54930. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54931. return vertex;
  54932. };
  54933. /**
  54934. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54935. * This does nothing and may be overwritten by the user.
  54936. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54937. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54938. * @param update the boolean update value actually passed to setParticles()
  54939. */
  54940. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54941. };
  54942. /**
  54943. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54944. * This will be passed three parameters.
  54945. * This does nothing and may be overwritten by the user.
  54946. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54947. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54948. * @param update the boolean update value actually passed to setParticles()
  54949. */
  54950. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54951. };
  54952. return SolidParticleSystem;
  54953. }());
  54954. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54955. })(BABYLON || (BABYLON = {}));
  54956. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54957. var BABYLON;
  54958. (function (BABYLON) {
  54959. var Internals;
  54960. (function (Internals) {
  54961. var FileFaceOrientation = (function () {
  54962. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54963. this.name = name;
  54964. this.worldAxisForNormal = worldAxisForNormal;
  54965. this.worldAxisForFileX = worldAxisForFileX;
  54966. this.worldAxisForFileY = worldAxisForFileY;
  54967. }
  54968. return FileFaceOrientation;
  54969. }());
  54970. ;
  54971. /**
  54972. * Helper class dealing with the extraction of spherical polynomial dataArray
  54973. * from a cube map.
  54974. */
  54975. var CubeMapToSphericalPolynomialTools = (function () {
  54976. function CubeMapToSphericalPolynomialTools() {
  54977. }
  54978. /**
  54979. * Converts a cubemap to the according Spherical Polynomial data.
  54980. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54981. *
  54982. * @param cubeInfo The Cube map to extract the information from.
  54983. * @return The Spherical Polynomial data.
  54984. */
  54985. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54986. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54987. var totalSolidAngle = 0.0;
  54988. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54989. var du = 2.0 / cubeInfo.size;
  54990. var dv = du;
  54991. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54992. var minUV = du * 0.5 - 1.0;
  54993. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54994. var fileFace = this.FileFaces[faceIndex];
  54995. var dataArray = cubeInfo[fileFace.name];
  54996. var v = minUV;
  54997. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54998. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54999. // Because SP is still linear, so summation is fine in that basis.
  55000. for (var y = 0; y < cubeInfo.size; y++) {
  55001. var u = minUV;
  55002. for (var x = 0; x < cubeInfo.size; x++) {
  55003. // World direction (not normalised)
  55004. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  55005. worldDirection.normalize();
  55006. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  55007. if (1) {
  55008. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  55009. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  55010. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  55011. var color = new BABYLON.Color3(r, g, b);
  55012. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55013. }
  55014. else {
  55015. if (faceIndex == 0) {
  55016. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55017. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55018. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55019. }
  55020. else if (faceIndex == 1) {
  55021. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55022. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55023. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55024. }
  55025. else if (faceIndex == 2) {
  55026. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55027. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55028. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55029. }
  55030. else if (faceIndex == 3) {
  55031. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55032. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55033. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55034. }
  55035. else if (faceIndex == 4) {
  55036. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55037. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55038. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55039. }
  55040. else if (faceIndex == 5) {
  55041. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55042. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55043. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55044. }
  55045. 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]);
  55046. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55047. }
  55048. totalSolidAngle += deltaSolidAngle;
  55049. u += du;
  55050. }
  55051. v += dv;
  55052. }
  55053. }
  55054. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  55055. var correction = correctSolidAngle / totalSolidAngle;
  55056. sphericalHarmonics.scale(correction);
  55057. // Additionally scale by pi -- audit needed
  55058. sphericalHarmonics.scale(1.0 / Math.PI);
  55059. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  55060. };
  55061. return CubeMapToSphericalPolynomialTools;
  55062. }());
  55063. CubeMapToSphericalPolynomialTools.FileFaces = [
  55064. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55065. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55066. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55067. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55068. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55069. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55070. ];
  55071. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55072. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55073. })(BABYLON || (BABYLON = {}));
  55074. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  55075. var BABYLON;
  55076. (function (BABYLON) {
  55077. var Internals;
  55078. (function (Internals) {
  55079. /**
  55080. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55081. */
  55082. var PanoramaToCubeMapTools = (function () {
  55083. function PanoramaToCubeMapTools() {
  55084. }
  55085. /**
  55086. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55087. *
  55088. * @param float32Array The source data.
  55089. * @param inputWidth The width of the input panorama.
  55090. * @param inputhHeight The height of the input panorama.
  55091. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55092. * @return The cubemap data
  55093. */
  55094. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55095. if (!float32Array) {
  55096. throw "ConvertPanoramaToCubemap: input cannot be null";
  55097. }
  55098. if (float32Array.length != inputWidth * inputHeight * 3) {
  55099. throw "ConvertPanoramaToCubemap: input size is wrong";
  55100. }
  55101. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55102. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55103. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55104. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55105. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55106. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55107. return {
  55108. front: textureFront,
  55109. back: textureBack,
  55110. left: textureLeft,
  55111. right: textureRight,
  55112. up: textureUp,
  55113. down: textureDown,
  55114. size: size
  55115. };
  55116. };
  55117. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55118. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55119. var textureArray = new Float32Array(buffer);
  55120. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55121. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55122. var dy = 1 / texSize;
  55123. var fy = 0;
  55124. for (var y = 0; y < texSize; y++) {
  55125. var xv1 = faceData[0];
  55126. var xv2 = faceData[2];
  55127. for (var x = 0; x < texSize; x++) {
  55128. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55129. v.normalize();
  55130. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55131. // 3 channels per pixels
  55132. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55133. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55134. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55135. xv1 = xv1.add(rotDX1);
  55136. xv2 = xv2.add(rotDX2);
  55137. }
  55138. fy += dy;
  55139. }
  55140. return textureArray;
  55141. };
  55142. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55143. var theta = Math.atan2(vDir.z, vDir.x);
  55144. var phi = Math.acos(vDir.y);
  55145. while (theta < -Math.PI)
  55146. theta += 2 * Math.PI;
  55147. while (theta > Math.PI)
  55148. theta -= 2 * Math.PI;
  55149. var dx = theta / Math.PI;
  55150. var dy = phi / Math.PI;
  55151. // recenter.
  55152. dx = dx * 0.5 + 0.5;
  55153. var px = Math.round(dx * inputWidth);
  55154. if (px < 0)
  55155. px = 0;
  55156. else if (px >= inputWidth)
  55157. px = inputWidth - 1;
  55158. var py = Math.round(dy * inputHeight);
  55159. if (py < 0)
  55160. py = 0;
  55161. else if (py >= inputHeight)
  55162. py = inputHeight - 1;
  55163. var inputY = (inputHeight - py - 1);
  55164. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55165. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55166. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55167. return {
  55168. r: r,
  55169. g: g,
  55170. b: b
  55171. };
  55172. };
  55173. return PanoramaToCubeMapTools;
  55174. }());
  55175. PanoramaToCubeMapTools.FACE_FRONT = [
  55176. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55177. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55178. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55179. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55180. ];
  55181. PanoramaToCubeMapTools.FACE_BACK = [
  55182. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55183. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55184. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55185. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55186. ];
  55187. PanoramaToCubeMapTools.FACE_RIGHT = [
  55188. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55189. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55190. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55191. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55192. ];
  55193. PanoramaToCubeMapTools.FACE_LEFT = [
  55194. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55195. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55196. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55197. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55198. ];
  55199. PanoramaToCubeMapTools.FACE_DOWN = [
  55200. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55201. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55202. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55203. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55204. ];
  55205. PanoramaToCubeMapTools.FACE_UP = [
  55206. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55207. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55208. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55209. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55210. ];
  55211. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55212. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55213. })(BABYLON || (BABYLON = {}));
  55214. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  55215. var BABYLON;
  55216. (function (BABYLON) {
  55217. var Internals;
  55218. (function (Internals) {
  55219. ;
  55220. /**
  55221. * This groups tools to convert HDR texture to native colors array.
  55222. */
  55223. var HDRTools = (function () {
  55224. function HDRTools() {
  55225. }
  55226. HDRTools.Ldexp = function (mantissa, exponent) {
  55227. if (exponent > 1023) {
  55228. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55229. }
  55230. if (exponent < -1074) {
  55231. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55232. }
  55233. return mantissa * Math.pow(2, exponent);
  55234. };
  55235. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55236. if (exponent > 0) {
  55237. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55238. float32array[index + 0] = red * exponent;
  55239. float32array[index + 1] = green * exponent;
  55240. float32array[index + 2] = blue * exponent;
  55241. }
  55242. else {
  55243. float32array[index + 0] = 0;
  55244. float32array[index + 1] = 0;
  55245. float32array[index + 2] = 0;
  55246. }
  55247. };
  55248. HDRTools.readStringLine = function (uint8array, startIndex) {
  55249. var line = "";
  55250. var character = "";
  55251. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55252. character = String.fromCharCode(uint8array[i]);
  55253. if (character == "\n") {
  55254. break;
  55255. }
  55256. line += character;
  55257. }
  55258. return line;
  55259. };
  55260. /**
  55261. * Reads header information from an RGBE texture stored in a native array.
  55262. * More information on this format are available here:
  55263. * https://en.wikipedia.org/wiki/RGBE_image_format
  55264. *
  55265. * @param uint8array The binary file stored in native array.
  55266. * @return The header information.
  55267. */
  55268. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55269. var height = 0;
  55270. var width = 0;
  55271. var line = this.readStringLine(uint8array, 0);
  55272. if (line[0] != '#' || line[1] != '?') {
  55273. throw "Bad HDR Format.";
  55274. }
  55275. var endOfHeader = false;
  55276. var findFormat = false;
  55277. var lineIndex = 0;
  55278. do {
  55279. lineIndex += (line.length + 1);
  55280. line = this.readStringLine(uint8array, lineIndex);
  55281. if (line == "FORMAT=32-bit_rle_rgbe") {
  55282. findFormat = true;
  55283. }
  55284. else if (line.length == 0) {
  55285. endOfHeader = true;
  55286. }
  55287. } while (!endOfHeader);
  55288. if (!findFormat) {
  55289. throw "HDR Bad header format, unsupported FORMAT";
  55290. }
  55291. lineIndex += (line.length + 1);
  55292. line = this.readStringLine(uint8array, lineIndex);
  55293. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55294. var match = sizeRegexp.exec(line);
  55295. // TODO. Support +Y and -X if needed.
  55296. if (match.length < 3) {
  55297. throw "HDR Bad header format, no size";
  55298. }
  55299. width = parseInt(match[2]);
  55300. height = parseInt(match[1]);
  55301. if (width < 8 || width > 0x7fff) {
  55302. throw "HDR Bad header format, unsupported size";
  55303. }
  55304. lineIndex += (line.length + 1);
  55305. return {
  55306. height: height,
  55307. width: width,
  55308. dataPosition: lineIndex
  55309. };
  55310. };
  55311. /**
  55312. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55313. * This RGBE texture needs to store the information as a panorama.
  55314. *
  55315. * More information on this format are available here:
  55316. * https://en.wikipedia.org/wiki/RGBE_image_format
  55317. *
  55318. * @param buffer The binary file stored in an array buffer.
  55319. * @param size The expected size of the extracted cubemap.
  55320. * @return The Cube Map information.
  55321. */
  55322. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55323. var uint8array = new Uint8Array(buffer);
  55324. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55325. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55326. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55327. return cubeMapData;
  55328. };
  55329. /**
  55330. * Returns the pixels data extracted from an RGBE texture.
  55331. * This pixels will be stored left to right up to down in the R G B order in one array.
  55332. *
  55333. * More information on this format are available here:
  55334. * https://en.wikipedia.org/wiki/RGBE_image_format
  55335. *
  55336. * @param uint8array The binary file stored in an array buffer.
  55337. * @param hdrInfo The header information of the file.
  55338. * @return The pixels data in RGB right to left up to down order.
  55339. */
  55340. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55341. // Keep for multi format supports.
  55342. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55343. };
  55344. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55345. var num_scanlines = hdrInfo.height;
  55346. var scanline_width = hdrInfo.width;
  55347. var a, b, c, d, count;
  55348. var dataIndex = hdrInfo.dataPosition;
  55349. var index = 0, endIndex = 0, i = 0;
  55350. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55351. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55352. // 3 channels of 4 bytes per pixel in float.
  55353. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55354. var resultArray = new Float32Array(resultBuffer);
  55355. // read in each successive scanline
  55356. while (num_scanlines > 0) {
  55357. a = uint8array[dataIndex++];
  55358. b = uint8array[dataIndex++];
  55359. c = uint8array[dataIndex++];
  55360. d = uint8array[dataIndex++];
  55361. if (a != 2 || b != 2 || (c & 0x80)) {
  55362. // this file is not run length encoded
  55363. throw "HDR Bad header format, not RLE";
  55364. }
  55365. if (((c << 8) | d) != scanline_width) {
  55366. throw "HDR Bad header format, wrong scan line width";
  55367. }
  55368. index = 0;
  55369. // read each of the four channels for the scanline into the buffer
  55370. for (i = 0; i < 4; i++) {
  55371. endIndex = (i + 1) * scanline_width;
  55372. while (index < endIndex) {
  55373. a = uint8array[dataIndex++];
  55374. b = uint8array[dataIndex++];
  55375. if (a > 128) {
  55376. // a run of the same value
  55377. count = a - 128;
  55378. if ((count == 0) || (count > endIndex - index)) {
  55379. throw "HDR Bad Format, bad scanline data (run)";
  55380. }
  55381. while (count-- > 0) {
  55382. scanLineArray[index++] = b;
  55383. }
  55384. }
  55385. else {
  55386. // a non-run
  55387. count = a;
  55388. if ((count == 0) || (count > endIndex - index)) {
  55389. throw "HDR Bad Format, bad scanline data (non-run)";
  55390. }
  55391. scanLineArray[index++] = b;
  55392. if (--count > 0) {
  55393. for (var j = 0; j < count; j++) {
  55394. scanLineArray[index++] = uint8array[dataIndex++];
  55395. }
  55396. }
  55397. }
  55398. }
  55399. }
  55400. // now convert data from buffer into floats
  55401. for (i = 0; i < scanline_width; i++) {
  55402. a = scanLineArray[i];
  55403. b = scanLineArray[i + scanline_width];
  55404. c = scanLineArray[i + 2 * scanline_width];
  55405. d = scanLineArray[i + 3 * scanline_width];
  55406. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55407. }
  55408. num_scanlines--;
  55409. }
  55410. return resultArray;
  55411. };
  55412. return HDRTools;
  55413. }());
  55414. Internals.HDRTools = HDRTools;
  55415. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55416. })(BABYLON || (BABYLON = {}));
  55417. //# sourceMappingURL=babylon.tools.hdr.js.map
  55418. //_______________________________________________________________
  55419. // Extracted from CubeMapGen:
  55420. // https://code.google.com/archive/p/cubemapgen/
  55421. //
  55422. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55423. //_______________________________________________________________
  55424. var BABYLON;
  55425. (function (BABYLON) {
  55426. var Internals;
  55427. (function (Internals) {
  55428. /**
  55429. * The bounding box information used during the conversion process.
  55430. */
  55431. var CMGBoundinBox = (function () {
  55432. function CMGBoundinBox() {
  55433. this.min = new BABYLON.Vector3(0, 0, 0);
  55434. this.max = new BABYLON.Vector3(0, 0, 0);
  55435. this.clear();
  55436. }
  55437. CMGBoundinBox.prototype.clear = function () {
  55438. this.min.x = CMGBoundinBox.MAX;
  55439. this.min.y = CMGBoundinBox.MAX;
  55440. this.min.z = CMGBoundinBox.MAX;
  55441. this.max.x = CMGBoundinBox.MIN;
  55442. this.max.y = CMGBoundinBox.MIN;
  55443. this.max.z = CMGBoundinBox.MIN;
  55444. };
  55445. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55446. this.min.x = Math.min(this.min.x, x);
  55447. this.min.y = Math.min(this.min.y, y);
  55448. this.min.z = Math.min(this.min.z, z);
  55449. this.max.x = Math.max(this.max.x, x);
  55450. this.max.y = Math.max(this.max.y, y);
  55451. this.max.z = Math.max(this.max.z, z);
  55452. };
  55453. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55454. this.min.x = Math.max(this.min.x, x);
  55455. this.min.y = Math.max(this.min.y, y);
  55456. this.min.z = Math.max(this.min.z, z);
  55457. };
  55458. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55459. this.max.x = Math.min(this.max.x, x);
  55460. this.max.y = Math.min(this.max.y, y);
  55461. this.max.z = Math.min(this.max.z, z);
  55462. };
  55463. CMGBoundinBox.prototype.empty = function () {
  55464. if ((this.min.x > this.max.y) ||
  55465. (this.min.y > this.max.y) ||
  55466. (this.min.z > this.max.y)) {
  55467. return true;
  55468. }
  55469. else {
  55470. return false;
  55471. }
  55472. };
  55473. return CMGBoundinBox;
  55474. }());
  55475. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55476. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55477. /**
  55478. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55479. * required by the glossinees of a material.
  55480. *
  55481. * This only supports the cosine drop power as well as Warp fixup generation method.
  55482. *
  55483. * This is using the process from CubeMapGen described here:
  55484. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55485. */
  55486. var PMREMGenerator = (function () {
  55487. /**
  55488. * Constructor of the generator.
  55489. *
  55490. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55491. * @param inputSize The size of the cubemap faces
  55492. * @param outputSize The size of the output cubemap faces
  55493. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55494. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55495. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55496. * @param specularPower The max specular level of the desired cubemap
  55497. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55498. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55499. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55500. */
  55501. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55502. this.input = input;
  55503. this.inputSize = inputSize;
  55504. this.outputSize = outputSize;
  55505. this.maxNumMipLevels = maxNumMipLevels;
  55506. this.numChannels = numChannels;
  55507. this.isFloat = isFloat;
  55508. this.specularPower = specularPower;
  55509. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55510. this.excludeBase = excludeBase;
  55511. this.fixup = fixup;
  55512. this._outputSurface = [];
  55513. this._numMipLevels = 0;
  55514. }
  55515. /**
  55516. * Launches the filter process and return the result.
  55517. *
  55518. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55519. */
  55520. PMREMGenerator.prototype.filterCubeMap = function () {
  55521. // Init cubemap processor
  55522. this.init();
  55523. // Filters the cubemap
  55524. this.filterCubeMapMipChain();
  55525. // Returns the filtered mips.
  55526. return this._outputSurface;
  55527. };
  55528. PMREMGenerator.prototype.init = function () {
  55529. var i;
  55530. var j;
  55531. var mipLevelSize;
  55532. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55533. if (this.maxNumMipLevels == 0) {
  55534. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55535. }
  55536. //first miplevel size
  55537. mipLevelSize = this.outputSize;
  55538. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55539. for (j = 0; j < this.maxNumMipLevels; j++) {
  55540. this._outputSurface.length++;
  55541. this._outputSurface[j] = [];
  55542. //Iterate over faces for output images
  55543. for (i = 0; i < 6; i++) {
  55544. this._outputSurface[j].length++;
  55545. // Initializes a new array for the output.
  55546. if (this.isFloat) {
  55547. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55548. }
  55549. else {
  55550. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55551. }
  55552. }
  55553. //next mip level is half size
  55554. mipLevelSize >>= 1;
  55555. this._numMipLevels++;
  55556. //terminate if mip chain becomes too small
  55557. if (mipLevelSize == 0) {
  55558. this.maxNumMipLevels = j;
  55559. return;
  55560. }
  55561. }
  55562. };
  55563. //--------------------------------------------------------------------------------------
  55564. //Cube map filtering and mip chain generation.
  55565. // the cube map filtereing is specified using a number of parameters:
  55566. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55567. // indicates the region of the hemisphere to filter over for each tap.
  55568. //
  55569. // Note that the top mip level is also a filtered version of the original input images
  55570. // as well in order to create mip chains for diffuse environment illumination.
  55571. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55572. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55573. //
  55574. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55575. // is a_InitialMipAngle
  55576. //
  55577. // The angle for the subsequent levels of the mip chain are specified by their parents
  55578. // filtering angle and a per-level scale and bias
  55579. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55580. //
  55581. //--------------------------------------------------------------------------------------
  55582. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55583. // First, take count of the lighting model to modify SpecularPower
  55584. // 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;
  55585. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55586. //Cone angle start (for generating subsequent mip levels)
  55587. var currentSpecularPower = this.specularPower;
  55588. //Build filter lookup tables based on the source miplevel size
  55589. this.precomputeFilterLookupTables(this.inputSize);
  55590. // Note that we need to filter the first level before generating mipmap
  55591. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55592. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55593. // TODO : Write a function to copy and scale the base mipmap in output
  55594. // I am just lazy here and just put a high specular power value, and do some if.
  55595. if (this.excludeBase && (levelIndex == 0)) {
  55596. // 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).
  55597. currentSpecularPower = 100000.0;
  55598. }
  55599. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55600. var srcCubeImage = this.input;
  55601. var dstCubeImage = this._outputSurface[levelIndex];
  55602. var dstSize = this.outputSize >> levelIndex;
  55603. // Compute required angle.
  55604. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55605. // filter cube surfaces
  55606. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55607. // fix seams
  55608. if (this.fixup) {
  55609. this.fixupCubeEdges(dstCubeImage, dstSize);
  55610. }
  55611. // Decrease the specular power to generate the mipmap chain
  55612. // TODO : Use another method for Exclude (see first comment at start of the function
  55613. if (this.excludeBase && (levelIndex == 0)) {
  55614. currentSpecularPower = this.specularPower;
  55615. }
  55616. currentSpecularPower *= this.cosinePowerDropPerMip;
  55617. }
  55618. };
  55619. //--------------------------------------------------------------------------------------
  55620. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55621. // It allow to optimize the texel to access base on the specular power.
  55622. //--------------------------------------------------------------------------------------
  55623. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55624. // We want to find the alpha such that:
  55625. // cos(alpha)^cosinePower = epsilon
  55626. // That's: acos(epsilon^(1/cosinePower))
  55627. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55628. var angle = 180.0;
  55629. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55630. angle *= 180.0 / Math.PI; // Convert to degree
  55631. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55632. return angle;
  55633. };
  55634. //--------------------------------------------------------------------------------------
  55635. //Builds the following lookup tables prior to filtering:
  55636. // -normalizer cube map
  55637. // -tap weight lookup table
  55638. //
  55639. //--------------------------------------------------------------------------------------
  55640. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55641. var srcTexelAngle;
  55642. var iCubeFace;
  55643. //clear pre-existing normalizer cube map
  55644. this._normCubeMap = [];
  55645. //Normalized vectors per cubeface and per-texel solid angle
  55646. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55647. };
  55648. //--------------------------------------------------------------------------------------
  55649. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55650. //
  55651. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55652. //
  55653. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55654. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55655. // below
  55656. //--------------------------------------------------------------------------------------
  55657. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55658. var iCubeFace;
  55659. var u;
  55660. var v;
  55661. //iterate over cube faces
  55662. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55663. //First three channels for norm cube, and last channel for solid angle
  55664. this._normCubeMap.push(new Float32Array(size * size * 4));
  55665. //fast texture walk, build normalizer cube map
  55666. var facesData = this.input[iCubeFace];
  55667. for (v = 0; v < size; v++) {
  55668. for (u = 0; u < size; u++) {
  55669. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55670. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55671. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55672. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55673. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55674. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55675. }
  55676. }
  55677. }
  55678. };
  55679. //--------------------------------------------------------------------------------------
  55680. // Convert cubemap face texel coordinates and face idx to 3D vector
  55681. // note the U and V coords are integer coords and range from 0 to size-1
  55682. // this routine can be used to generate a normalizer cube map
  55683. //--------------------------------------------------------------------------------------
  55684. // SL BEGIN
  55685. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55686. var nvcU;
  55687. var nvcV;
  55688. var tempVec;
  55689. // Change from original AMD code
  55690. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55691. // + 0.5f is for texel center addressing
  55692. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55693. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55694. // warp fixup
  55695. if (fixup && size > 1) {
  55696. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55697. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55698. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55699. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55700. }
  55701. // Get current vector
  55702. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55703. // U contribution
  55704. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55705. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55706. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55707. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55708. // V contribution and Sum
  55709. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55710. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55711. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55712. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55713. //add face axis
  55714. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55715. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55716. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55717. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55718. //normalize vector
  55719. PMREMGenerator._vectorTemp.normalize();
  55720. return PMREMGenerator._vectorTemp;
  55721. };
  55722. //--------------------------------------------------------------------------------------
  55723. // Convert 3D vector to cubemap face texel coordinates and face idx
  55724. // note the U and V coords are integer coords and range from 0 to size-1
  55725. // this routine can be used to generate a normalizer cube map
  55726. //
  55727. // returns face IDX and texel coords
  55728. //--------------------------------------------------------------------------------------
  55729. // SL BEGIN
  55730. /*
  55731. Mapping Texture Coordinates to Cube Map Faces
  55732. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55733. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55734. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55735. map arrangement in Pixar's RenderMan package.
  55736. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55737. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55738. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55739. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55740. the major axis direction). The target column in the table below explains how the major axis direction
  55741. maps to the 2D image of a particular cube map target.
  55742. major axis
  55743. direction target sc tc ma
  55744. ---------- --------------------------------- --- --- ---
  55745. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55746. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55747. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55748. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55749. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55750. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55751. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55752. an updated (s,t) is calculated as follows
  55753. s = ( sc/|ma| + 1 ) / 2
  55754. t = ( tc/|ma| + 1 ) / 2
  55755. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55756. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55757. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55758. */
  55759. // Note this method return U and V in range from 0 to size-1
  55760. // SL END
  55761. // Store the information in vector3 for convenience (faceindex, u, v)
  55762. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55763. var maxCoord;
  55764. var faceIdx;
  55765. //absolute value 3
  55766. var absX = Math.abs(x);
  55767. var absY = Math.abs(y);
  55768. var absZ = Math.abs(z);
  55769. if (absX >= absY && absX >= absZ) {
  55770. maxCoord = absX;
  55771. if (x >= 0) {
  55772. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55773. }
  55774. else {
  55775. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55776. }
  55777. }
  55778. else if (absY >= absX && absY >= absZ) {
  55779. maxCoord = absY;
  55780. if (y >= 0) {
  55781. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55782. }
  55783. else {
  55784. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55785. }
  55786. }
  55787. else {
  55788. maxCoord = absZ;
  55789. if (z >= 0) {
  55790. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55791. }
  55792. else {
  55793. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55794. }
  55795. }
  55796. //divide through by max coord so face vector lies on cube face
  55797. var scale = 1 / maxCoord;
  55798. x *= scale;
  55799. y *= scale;
  55800. z *= scale;
  55801. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55802. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55803. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55804. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55805. // Modify original AMD code to return value from 0 to Size - 1
  55806. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55807. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55808. PMREMGenerator._vectorTemp.x = faceIdx;
  55809. PMREMGenerator._vectorTemp.y = u;
  55810. PMREMGenerator._vectorTemp.z = v;
  55811. return PMREMGenerator._vectorTemp;
  55812. };
  55813. //--------------------------------------------------------------------------------------
  55814. //Original code from Ignacio CastaÒo
  55815. // This formula is from Manne ÷hrstrˆm's thesis.
  55816. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55817. // cube face and return the area of the projection of that portion on the
  55818. // surface of the sphere.
  55819. //--------------------------------------------------------------------------------------
  55820. PMREMGenerator.prototype.areaElement = function (x, y) {
  55821. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55822. };
  55823. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55824. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55825. // (+ 0.5f is for texel center addressing)
  55826. u = (2.0 * (u + 0.5) / size) - 1.0;
  55827. v = (2.0 * (v + 0.5) / size) - 1.0;
  55828. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55829. var invResolution = 1.0 / size;
  55830. // U and V are the -1..1 texture coordinate on the current face.
  55831. // Get projected area for this texel
  55832. var x0 = u - invResolution;
  55833. var y0 = v - invResolution;
  55834. var x1 = u + invResolution;
  55835. var y1 = v + invResolution;
  55836. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55837. return solidAngle;
  55838. };
  55839. //--------------------------------------------------------------------------------------
  55840. //The key to the speed of these filtering routines is to quickly define a per-face
  55841. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55842. // Later these pixels are selectively processed based on their dot products to see if
  55843. // they reside within the filtering cone.
  55844. //
  55845. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55846. // of the number of texels needed to be covered in width and height order to filter the
  55847. // region. the bounding box for the center taps face is defined first, and if the
  55848. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55849. // defined next
  55850. //--------------------------------------------------------------------------------------
  55851. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55852. // note that pixels within these regions may be rejected
  55853. // based on the anlge
  55854. var iCubeFace;
  55855. var u;
  55856. var v;
  55857. // bounding box per face to specify region to process
  55858. var filterExtents = [];
  55859. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55860. filterExtents.push(new CMGBoundinBox());
  55861. }
  55862. // min angle a src texel can cover (in degrees)
  55863. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55864. // angle about center tap to define filter cone
  55865. // filter angle is 1/2 the cone angle
  55866. var filterAngle = filterConeAngle / 2.0;
  55867. //ensure filter angle is larger than a texel
  55868. if (filterAngle < srcTexelAngle) {
  55869. filterAngle = srcTexelAngle;
  55870. }
  55871. //ensure filter cone is always smaller than the hemisphere
  55872. if (filterAngle > 90.0) {
  55873. filterAngle = 90.0;
  55874. }
  55875. // the maximum number of texels in 1D the filter cone angle will cover
  55876. // used to determine bounding box size for filter extents
  55877. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55878. // ensure conservative region always covers at least one texel
  55879. if (filterSize < 1) {
  55880. filterSize = 1;
  55881. }
  55882. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55883. // reside within the cone angle
  55884. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55885. // process required faces
  55886. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55887. //iterate over dst cube map face texel
  55888. for (v = 0; v < dstSize; v++) {
  55889. for (u = 0; u < dstSize; u++) {
  55890. //get center tap direction
  55891. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55892. //clear old per-face filter extents
  55893. this.clearFilterExtents(filterExtents);
  55894. //define per-face filter extents
  55895. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55896. //perform filtering of src faces using filter extents
  55897. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55898. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55899. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55900. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55901. }
  55902. }
  55903. }
  55904. };
  55905. //--------------------------------------------------------------------------------------
  55906. //Clear filter extents for the 6 cube map faces
  55907. //--------------------------------------------------------------------------------------
  55908. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55909. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55910. filterExtents[iCubeFaces].clear();
  55911. }
  55912. };
  55913. //--------------------------------------------------------------------------------------
  55914. //Define per-face bounding box filter extents
  55915. //
  55916. // These define conservative texel regions in each of the faces the filter can possibly
  55917. // process. When the pixels in the regions are actually processed, the dot product
  55918. // between the tap vector and the center tap vector is used to determine the weight of
  55919. // the tap and whether or not the tap is within the cone.
  55920. //
  55921. //--------------------------------------------------------------------------------------
  55922. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55923. //neighboring face and bleed over amount, and width of BBOX for
  55924. // left, right, top, and bottom edges of this face
  55925. var bleedOverAmount = [0, 0, 0, 0];
  55926. var bleedOverBBoxMin = [0, 0, 0, 0];
  55927. var bleedOverBBoxMax = [0, 0, 0, 0];
  55928. var neighborFace;
  55929. var neighborEdge;
  55930. var oppositeFaceIdx;
  55931. //get face idx, and u, v info from center tap dir
  55932. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55933. var faceIdx = result.x;
  55934. var u = result.y;
  55935. var v = result.z;
  55936. //define bbox size within face
  55937. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55938. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55939. filterExtents[faceIdx].clampMin(0, 0, 0);
  55940. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55941. //u and v extent in face corresponding to center tap
  55942. var minU = filterExtents[faceIdx].min.x;
  55943. var minV = filterExtents[faceIdx].min.y;
  55944. var maxU = filterExtents[faceIdx].max.x;
  55945. var maxV = filterExtents[faceIdx].max.y;
  55946. //bleed over amounts for face across u=0 edge (left)
  55947. bleedOverAmount[0] = (bboxSize - u);
  55948. bleedOverBBoxMin[0] = minV;
  55949. bleedOverBBoxMax[0] = maxV;
  55950. //bleed over amounts for face across u=1 edge (right)
  55951. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55952. bleedOverBBoxMin[1] = minV;
  55953. bleedOverBBoxMax[1] = maxV;
  55954. //bleed over to face across v=0 edge (up)
  55955. bleedOverAmount[2] = (bboxSize - v);
  55956. bleedOverBBoxMin[2] = minU;
  55957. bleedOverBBoxMax[2] = maxU;
  55958. //bleed over to face across v=1 edge (down)
  55959. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55960. bleedOverBBoxMin[3] = minU;
  55961. bleedOverBBoxMax[3] = maxU;
  55962. //compute bleed over regions in neighboring faces
  55963. for (var i = 0; i < 4; i++) {
  55964. if (bleedOverAmount[i] > 0) {
  55965. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55966. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55967. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55968. // be flipped: the cases are
  55969. // if a left edge mates with a left or bottom edge on the neighbor
  55970. // if a top edge mates with a top or right edge on the neighbor
  55971. // if a right edge mates with a right or top edge on the neighbor
  55972. // if a bottom edge mates with a bottom or left edge on the neighbor
  55973. //Seeing as the edges are enumerated as follows
  55974. // left =0
  55975. // right =1
  55976. // top =2
  55977. // bottom =3
  55978. //
  55979. // so if the edge enums are the same, or the sum of the enums == 3,
  55980. // the bbox needs to be flipped
  55981. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55982. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55983. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55984. }
  55985. //The way the bounding box is extended onto the neighboring face
  55986. // depends on which edge of neighboring face abuts with this one
  55987. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55988. case PMREMGenerator.CP_EDGE_LEFT:
  55989. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55990. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55991. break;
  55992. case PMREMGenerator.CP_EDGE_RIGHT:
  55993. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55994. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55995. break;
  55996. case PMREMGenerator.CP_EDGE_TOP:
  55997. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55998. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55999. break;
  56000. case PMREMGenerator.CP_EDGE_BOTTOM:
  56001. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  56002. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  56003. break;
  56004. }
  56005. //clamp filter extents in non-center tap faces to remain within surface
  56006. filterExtents[neighborFace].clampMin(0, 0, 0);
  56007. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  56008. }
  56009. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  56010. // from the center tap face, then process the opposite face entirely for now.
  56011. //Note that the cases in which this happens, what usually happens is that
  56012. // more than one edge bleeds onto the opposite face, and the bounding box
  56013. // encompasses the entire cube map face.
  56014. if (bleedOverAmount[i] > srcSize) {
  56015. //determine opposite face
  56016. switch (faceIdx) {
  56017. case PMREMGenerator.CP_FACE_X_POS:
  56018. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56019. break;
  56020. case PMREMGenerator.CP_FACE_X_NEG:
  56021. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  56022. break;
  56023. case PMREMGenerator.CP_FACE_Y_POS:
  56024. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56025. break;
  56026. case PMREMGenerator.CP_FACE_Y_NEG:
  56027. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56028. break;
  56029. case PMREMGenerator.CP_FACE_Z_POS:
  56030. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56031. break;
  56032. case PMREMGenerator.CP_FACE_Z_NEG:
  56033. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56034. break;
  56035. default:
  56036. break;
  56037. }
  56038. //just encompass entire face for now
  56039. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  56040. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  56041. }
  56042. }
  56043. };
  56044. //--------------------------------------------------------------------------------------
  56045. //ProcessFilterExtents
  56046. // Process bounding box in each cube face
  56047. //
  56048. //--------------------------------------------------------------------------------------
  56049. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  56050. //accumulators are 64-bit floats in order to have the precision needed
  56051. // over a summation of a large number of pixels
  56052. var dstAccum = [0, 0, 0, 0];
  56053. var weightAccum = 0;
  56054. var k = 0;
  56055. var nSrcChannels = this.numChannels;
  56056. // norm cube map and srcCubeMap have same face width
  56057. var faceWidth = srcSize;
  56058. //amount to add to pointer to move to next scanline in images
  56059. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  56060. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  56061. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  56062. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  56063. // iterate over cubefaces
  56064. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  56065. //if bbox is non empty
  56066. if (!filterExtents[iFaceIdx].empty()) {
  56067. var uStart = filterExtents[iFaceIdx].min.x;
  56068. var vStart = filterExtents[iFaceIdx].min.y;
  56069. var uEnd = filterExtents[iFaceIdx].max.x;
  56070. var vEnd = filterExtents[iFaceIdx].max.y;
  56071. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56072. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56073. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56074. for (var v = vStart; v <= vEnd; v++) {
  56075. var normCubeRowWalk = 0;
  56076. var srcCubeRowWalk = 0;
  56077. for (var u = uStart; u <= uEnd; u++) {
  56078. //pointer to direction in cube map associated with texel
  56079. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56080. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56081. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56082. //check dot product to see if texel is within cone
  56083. var tapDotProd = texelVectX * centerTapDir.x +
  56084. texelVectY * centerTapDir.y +
  56085. texelVectZ * centerTapDir.z;
  56086. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56087. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56088. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56089. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56090. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56091. // so just adding one to specularpower do the trick.
  56092. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56093. //iterate over channels
  56094. for (k = 0; k < nSrcChannels; k++) {
  56095. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56096. srcCubeRowWalk++;
  56097. }
  56098. weightAccum += weight; //accumulate weight
  56099. }
  56100. else {
  56101. //step across source pixel
  56102. srcCubeRowWalk += nSrcChannels;
  56103. }
  56104. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56105. }
  56106. startIndexNormCubeMap += normCubePitch;
  56107. startIndexSrcCubeMap += srcCubePitch;
  56108. }
  56109. }
  56110. }
  56111. //divide through by weights if weight is non zero
  56112. if (weightAccum != 0.0) {
  56113. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56114. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56115. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56116. if (this.numChannels > 3) {
  56117. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56118. }
  56119. }
  56120. else {
  56121. // otherwise sample nearest
  56122. // get face idx and u, v texel coordinate in face
  56123. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56124. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56125. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56126. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56127. if (this.numChannels > 3) {
  56128. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56129. }
  56130. }
  56131. return PMREMGenerator._vectorTemp;
  56132. };
  56133. //--------------------------------------------------------------------------------------
  56134. // Fixup cube edges
  56135. //
  56136. // average texels on cube map faces across the edges
  56137. // WARP/BENT Method Only.
  56138. //--------------------------------------------------------------------------------------
  56139. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56140. var k;
  56141. var j;
  56142. var i;
  56143. var iFace;
  56144. var iCorner = 0;
  56145. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56146. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56147. // note that if functionality to filter across the three texels for each corner, then
  56148. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56149. var cornerPtr = [
  56150. [[], [], []],
  56151. [[], [], []],
  56152. [[], [], []],
  56153. [[], [], []],
  56154. [[], [], []],
  56155. [[], [], []],
  56156. [[], [], []],
  56157. [[], [], []]
  56158. ];
  56159. //if there is no fixup, or fixup width = 0, do nothing
  56160. if (cubeMapSize < 1) {
  56161. return;
  56162. }
  56163. //special case 1x1 cubemap, average face colors
  56164. if (cubeMapSize == 1) {
  56165. //iterate over channels
  56166. for (k = 0; k < this.numChannels; k++) {
  56167. var accum = 0.0;
  56168. //iterate over faces to accumulate face colors
  56169. for (iFace = 0; iFace < 6; iFace++) {
  56170. accum += cubeMap[iFace][k];
  56171. }
  56172. //compute average over 6 face colors
  56173. accum /= 6.0;
  56174. //iterate over faces to distribute face colors
  56175. for (iFace = 0; iFace < 6; iFace++) {
  56176. cubeMap[iFace][k] = accum;
  56177. }
  56178. }
  56179. return;
  56180. }
  56181. //iterate over faces to collect list of corner texel pointers
  56182. for (iFace = 0; iFace < 6; iFace++) {
  56183. //the 4 corner pointers for this face
  56184. faceCornerStartIndicies[0] = [iFace, 0];
  56185. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56186. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56187. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56188. //iterate over face corners to collect cube corner pointers
  56189. for (iCorner = 0; iCorner < 4; iCorner++) {
  56190. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56191. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56192. cornerNumPtrs[corner]++;
  56193. }
  56194. }
  56195. //iterate over corners to average across corner tap values
  56196. for (iCorner = 0; iCorner < 8; iCorner++) {
  56197. for (k = 0; k < this.numChannels; k++) {
  56198. var cornerTapAccum = 0.0;
  56199. //iterate over corner texels and average results
  56200. for (i = 0; i < 3; i++) {
  56201. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56202. }
  56203. //divide by 3 to compute average of corner tap values
  56204. cornerTapAccum *= (1.0 / 3.0);
  56205. //iterate over corner texels and average results
  56206. for (i = 0; i < 3; i++) {
  56207. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56208. }
  56209. }
  56210. }
  56211. //iterate over the twelve edges of the cube to average across edges
  56212. for (i = 0; i < 12; i++) {
  56213. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56214. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56215. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56216. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56217. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56218. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56219. var edgeWalk = 0;
  56220. var neighborEdgeWalk = 0;
  56221. //Determine walking pointers based on edge type
  56222. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56223. switch (edge) {
  56224. case PMREMGenerator.CP_EDGE_LEFT:
  56225. // no change to faceEdgeStartPtr
  56226. edgeWalk = this.numChannels * cubeMapSize;
  56227. break;
  56228. case PMREMGenerator.CP_EDGE_RIGHT:
  56229. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56230. edgeWalk = this.numChannels * cubeMapSize;
  56231. break;
  56232. case PMREMGenerator.CP_EDGE_TOP:
  56233. // no change to faceEdgeStartPtr
  56234. edgeWalk = this.numChannels;
  56235. break;
  56236. case PMREMGenerator.CP_EDGE_BOTTOM:
  56237. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56238. edgeWalk = this.numChannels;
  56239. break;
  56240. }
  56241. //For certain types of edge abutments, the neighbor edge walk needs to
  56242. // be flipped: the cases are
  56243. // if a left edge mates with a left or bottom edge on the neighbor
  56244. // if a top edge mates with a top or right edge on the neighbor
  56245. // if a right edge mates with a right or top edge on the neighbor
  56246. // if a bottom edge mates with a bottom or left edge on the neighbor
  56247. //Seeing as the edges are enumerated as follows
  56248. // left =0
  56249. // right =1
  56250. // top =2
  56251. // bottom =3
  56252. //
  56253. //If the edge enums are the same, or the sum of the enums == 3,
  56254. // the neighbor edge walk needs to be flipped
  56255. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56256. switch (neighborEdge) {
  56257. case PMREMGenerator.CP_EDGE_LEFT:
  56258. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56259. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56260. break;
  56261. case PMREMGenerator.CP_EDGE_RIGHT:
  56262. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56263. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56264. break;
  56265. case PMREMGenerator.CP_EDGE_TOP:
  56266. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56267. neighborEdgeWalk = -this.numChannels;
  56268. break;
  56269. case PMREMGenerator.CP_EDGE_BOTTOM:
  56270. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56271. neighborEdgeWalk = -this.numChannels;
  56272. break;
  56273. }
  56274. }
  56275. else {
  56276. //swapped direction neighbor edge walk
  56277. switch (neighborEdge) {
  56278. case PMREMGenerator.CP_EDGE_LEFT:
  56279. //no change to neighborEdgeStartPtr for this case since it points
  56280. // to the upper left corner already
  56281. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56282. break;
  56283. case PMREMGenerator.CP_EDGE_RIGHT:
  56284. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56285. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56286. break;
  56287. case PMREMGenerator.CP_EDGE_TOP:
  56288. //no change to neighborEdgeStartPtr for this case since it points
  56289. // to the upper left corner already
  56290. neighborEdgeWalk = this.numChannels;
  56291. break;
  56292. case PMREMGenerator.CP_EDGE_BOTTOM:
  56293. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56294. neighborEdgeWalk = this.numChannels;
  56295. break;
  56296. }
  56297. }
  56298. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56299. //nearby neighborhood
  56300. //step ahead one texel on edge
  56301. edgeStartIndex += edgeWalk;
  56302. neighborEdgeStartIndex += neighborEdgeWalk;
  56303. // note that this loop does not process the corner texels, since they have already been
  56304. // averaged across faces across earlier
  56305. for (j = 1; j < (cubeMapSize - 1); j++) {
  56306. //for each set of taps along edge, average them
  56307. // and rewrite the results into the edges
  56308. for (k = 0; k < this.numChannels; k++) {
  56309. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56310. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56311. //compute average of tap intensity values
  56312. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56313. //propagate average of taps to edge taps
  56314. cubeMap[face][edgeStartIndex + k] = avgTap;
  56315. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56316. }
  56317. edgeStartIndex += edgeWalk;
  56318. neighborEdgeStartIndex += neighborEdgeWalk;
  56319. }
  56320. }
  56321. };
  56322. return PMREMGenerator;
  56323. }());
  56324. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56325. PMREMGenerator.CP_UDIR = 0;
  56326. PMREMGenerator.CP_VDIR = 1;
  56327. PMREMGenerator.CP_FACEAXIS = 2;
  56328. //used to index cube faces
  56329. PMREMGenerator.CP_FACE_X_POS = 0;
  56330. PMREMGenerator.CP_FACE_X_NEG = 1;
  56331. PMREMGenerator.CP_FACE_Y_POS = 2;
  56332. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56333. PMREMGenerator.CP_FACE_Z_POS = 4;
  56334. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56335. //used to index image edges
  56336. // NOTE.. the actual number corresponding to the edge is important
  56337. // do not change these, or the code will break
  56338. //
  56339. // CP_EDGE_LEFT is u = 0
  56340. // CP_EDGE_RIGHT is u = width-1
  56341. // CP_EDGE_TOP is v = 0
  56342. // CP_EDGE_BOTTOM is v = height-1
  56343. PMREMGenerator.CP_EDGE_LEFT = 0;
  56344. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56345. PMREMGenerator.CP_EDGE_TOP = 2;
  56346. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56347. //corners of CUBE map (P or N specifys if it corresponds to the
  56348. // positive or negative direction each of X, Y, and Z
  56349. PMREMGenerator.CP_CORNER_NNN = 0;
  56350. PMREMGenerator.CP_CORNER_NNP = 1;
  56351. PMREMGenerator.CP_CORNER_NPN = 2;
  56352. PMREMGenerator.CP_CORNER_NPP = 3;
  56353. PMREMGenerator.CP_CORNER_PNN = 4;
  56354. PMREMGenerator.CP_CORNER_PNP = 5;
  56355. PMREMGenerator.CP_CORNER_PPN = 6;
  56356. PMREMGenerator.CP_CORNER_PPP = 7;
  56357. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56358. //3x2 matrices that map cube map indexing vectors in 3d
  56359. // (after face selection and divide through by the
  56360. // _ABSOLUTE VALUE_ of the max coord)
  56361. // into NVC space
  56362. //Note this currently assumes the D3D cube face ordering and orientation
  56363. PMREMGenerator._sgFace2DMapping = [
  56364. //XPOS face
  56365. [[0, 0, -1],
  56366. [0, -1, 0],
  56367. [1, 0, 0]],
  56368. //XNEG face
  56369. [[0, 0, 1],
  56370. [0, -1, 0],
  56371. [-1, 0, 0]],
  56372. //YPOS face
  56373. [[1, 0, 0],
  56374. [0, 0, 1],
  56375. [0, 1, 0]],
  56376. //YNEG face
  56377. [[1, 0, 0],
  56378. [0, 0, -1],
  56379. [0, -1, 0]],
  56380. //ZPOS face
  56381. [[1, 0, 0],
  56382. [0, -1, 0],
  56383. [0, 0, 1]],
  56384. //ZNEG face
  56385. [[-1, 0, 0],
  56386. [0, -1, 0],
  56387. [0, 0, -1]],
  56388. ];
  56389. //------------------------------------------------------------------------------
  56390. // D3D cube map face specification
  56391. // mapping from 3D x,y,z cube map lookup coordinates
  56392. // to 2D within face u,v coordinates
  56393. //
  56394. // --------------------> U direction
  56395. // | (within-face texture space)
  56396. // | _____
  56397. // | | |
  56398. // | | +Y |
  56399. // | _____|_____|_____ _____
  56400. // | | | | | |
  56401. // | | -X | +Z | +X | -Z |
  56402. // | |_____|_____|_____|_____|
  56403. // | | |
  56404. // | | -Y |
  56405. // | |_____|
  56406. // |
  56407. // v V direction
  56408. // (within-face texture space)
  56409. //------------------------------------------------------------------------------
  56410. //Information about neighbors and how texture coorrdinates change across faces
  56411. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56412. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56413. //Note this currently assumes the D3D cube face ordering and orientation
  56414. PMREMGenerator._sgCubeNgh = [
  56415. //XPOS face
  56416. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56417. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56418. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56419. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56420. //XNEG face
  56421. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56422. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56423. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56424. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56425. //YPOS face
  56426. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56427. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56428. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56429. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56430. //YNEG face
  56431. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56432. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56433. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56434. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56435. //ZPOS face
  56436. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56437. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56438. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56439. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56440. //ZNEG face
  56441. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56442. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56443. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56444. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56445. ];
  56446. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56447. // this table is used to average over the edges.
  56448. PMREMGenerator._sgCubeEdgeList = [
  56449. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56450. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56451. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56452. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56453. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56454. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56455. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56456. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56457. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56458. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56459. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56460. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56461. ];
  56462. //Information about which of the 8 cube corners are correspond to the
  56463. // the 4 corners in each cube face
  56464. // the order is upper left, upper right, lower left, lower right
  56465. PMREMGenerator._sgCubeCornerList = [
  56466. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56467. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56468. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56469. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56470. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56471. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56472. ];
  56473. Internals.PMREMGenerator = PMREMGenerator;
  56474. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56475. })(BABYLON || (BABYLON = {}));
  56476. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  56477. var BABYLON;
  56478. (function (BABYLON) {
  56479. /**
  56480. * This represents a texture coming from an HDR input.
  56481. *
  56482. * The only supported format is currently panorama picture stored in RGBE format.
  56483. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56484. */
  56485. var HDRCubeTexture = (function (_super) {
  56486. __extends(HDRCubeTexture, _super);
  56487. /**
  56488. * Instantiates an HDRTexture from the following parameters.
  56489. *
  56490. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56491. * @param scene The scene the texture will be used in
  56492. * @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.
  56493. * @param noMipmap Forces to not generate the mipmap if true
  56494. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56495. * @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)
  56496. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56497. */
  56498. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56499. if (noMipmap === void 0) { noMipmap = false; }
  56500. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56501. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56502. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56503. if (onLoad === void 0) { onLoad = null; }
  56504. if (onError === void 0) { onError = null; }
  56505. var _this = _super.call(this, scene) || this;
  56506. _this._useInGammaSpace = false;
  56507. _this._generateHarmonics = true;
  56508. _this._isBABYLONPreprocessed = false;
  56509. _this._onLoad = null;
  56510. _this._onError = null;
  56511. /**
  56512. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56513. */
  56514. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56515. /**
  56516. * The spherical polynomial data extracted from the texture.
  56517. */
  56518. _this.sphericalPolynomial = null;
  56519. /**
  56520. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56521. * This is usefull at run time to apply the good shader.
  56522. */
  56523. _this.isPMREM = false;
  56524. if (!url) {
  56525. return _this;
  56526. }
  56527. _this.name = url;
  56528. _this.url = url;
  56529. _this.hasAlpha = false;
  56530. _this.isCube = true;
  56531. _this._textureMatrix = BABYLON.Matrix.Identity();
  56532. _this._onLoad = onLoad;
  56533. _this._onError = onError;
  56534. if (size) {
  56535. _this._isBABYLONPreprocessed = false;
  56536. _this._noMipmap = noMipmap;
  56537. _this._size = size;
  56538. _this._useInGammaSpace = useInGammaSpace;
  56539. _this._usePMREMGenerator = usePMREMGenerator &&
  56540. scene.getEngine().getCaps().textureLOD &&
  56541. _this.getScene().getEngine().getCaps().textureFloat &&
  56542. !_this._useInGammaSpace;
  56543. }
  56544. else {
  56545. _this._isBABYLONPreprocessed = true;
  56546. _this._noMipmap = false;
  56547. _this._useInGammaSpace = false;
  56548. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56549. _this.getScene().getEngine().getCaps().textureFloat &&
  56550. !_this._useInGammaSpace;
  56551. }
  56552. _this.isPMREM = _this._usePMREMGenerator;
  56553. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56554. if (!_this._texture) {
  56555. if (!scene.useDelayedTextureLoading) {
  56556. _this.loadTexture();
  56557. }
  56558. else {
  56559. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56560. }
  56561. }
  56562. return _this;
  56563. }
  56564. /**
  56565. * Occurs when the file is a preprocessed .babylon.hdr file.
  56566. */
  56567. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56568. var _this = this;
  56569. var mipLevels = 0;
  56570. var floatArrayView = null;
  56571. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56572. var mips = [];
  56573. var startIndex = 30;
  56574. for (var level = 0; level < mipLevels; level++) {
  56575. mips.push([]);
  56576. // Fill each pixel of the mip level.
  56577. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56578. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56579. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56580. mips[level].push(faceData);
  56581. startIndex += faceSize;
  56582. }
  56583. }
  56584. return mips;
  56585. } : null;
  56586. var callback = function (buffer) {
  56587. // Create Native Array Views
  56588. var intArrayView = new Int32Array(buffer);
  56589. floatArrayView = new Float32Array(buffer);
  56590. // Fill header.
  56591. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56592. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56593. // Update Texture Information.
  56594. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56595. // Fill polynomial information.
  56596. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56597. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56598. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56599. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56600. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56601. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56602. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56603. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56604. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56605. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56606. // Fill pixel data.
  56607. mipLevels = intArrayView[29]; // Number of mip levels.
  56608. var startIndex = 30;
  56609. var data = [];
  56610. var faceSize = Math.pow(_this._size, 2) * 3;
  56611. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56612. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56613. startIndex += faceSize;
  56614. }
  56615. var results = [];
  56616. var byteArray = null;
  56617. // Push each faces.
  56618. for (var k = 0; k < 6; k++) {
  56619. var dataFace = null;
  56620. // If special cases.
  56621. if (!mipmapGenerator) {
  56622. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56623. dataFace = data[j];
  56624. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56625. // 3 channels of 1 bytes per pixel in bytes.
  56626. var byteBuffer = new ArrayBuffer(faceSize);
  56627. byteArray = new Uint8Array(byteBuffer);
  56628. }
  56629. for (var i = 0; i < _this._size * _this._size; i++) {
  56630. // Put in gamma space if requested.
  56631. if (_this._useInGammaSpace) {
  56632. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56633. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56634. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56635. }
  56636. // Convert to int texture for fallback.
  56637. if (byteArray) {
  56638. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56639. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56640. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56641. // May use luminance instead if the result is not accurate.
  56642. var max = Math.max(Math.max(r, g), b);
  56643. if (max > 255) {
  56644. var scale = 255 / max;
  56645. r *= scale;
  56646. g *= scale;
  56647. b *= scale;
  56648. }
  56649. byteArray[(i * 3) + 0] = r;
  56650. byteArray[(i * 3) + 1] = g;
  56651. byteArray[(i * 3) + 2] = b;
  56652. }
  56653. }
  56654. }
  56655. else {
  56656. dataFace = data[k];
  56657. }
  56658. // Fill the array accordingly.
  56659. if (byteArray) {
  56660. results.push(byteArray);
  56661. }
  56662. else {
  56663. results.push(dataFace);
  56664. }
  56665. }
  56666. return results;
  56667. };
  56668. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  56669. };
  56670. /**
  56671. * Occurs when the file is raw .hdr file.
  56672. */
  56673. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56674. var _this = this;
  56675. var callback = function (buffer) {
  56676. // Extract the raw linear data.
  56677. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56678. // Generate harmonics if needed.
  56679. if (_this._generateHarmonics) {
  56680. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56681. }
  56682. var results = [];
  56683. var byteArray = null;
  56684. // Push each faces.
  56685. for (var j = 0; j < 6; j++) {
  56686. // Create uintarray fallback.
  56687. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56688. // 3 channels of 1 bytes per pixel in bytes.
  56689. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56690. byteArray = new Uint8Array(byteBuffer);
  56691. }
  56692. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56693. // If special cases.
  56694. if (_this._useInGammaSpace || byteArray) {
  56695. for (var i = 0; i < _this._size * _this._size; i++) {
  56696. // Put in gamma space if requested.
  56697. if (_this._useInGammaSpace) {
  56698. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56699. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56700. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56701. }
  56702. // Convert to int texture for fallback.
  56703. if (byteArray) {
  56704. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56705. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56706. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56707. // May use luminance instead if the result is not accurate.
  56708. var max = Math.max(Math.max(r, g), b);
  56709. if (max > 255) {
  56710. var scale = 255 / max;
  56711. r *= scale;
  56712. g *= scale;
  56713. b *= scale;
  56714. }
  56715. byteArray[(i * 3) + 0] = r;
  56716. byteArray[(i * 3) + 1] = g;
  56717. byteArray[(i * 3) + 2] = b;
  56718. }
  56719. }
  56720. }
  56721. if (byteArray) {
  56722. results.push(byteArray);
  56723. }
  56724. else {
  56725. results.push(dataFace);
  56726. }
  56727. }
  56728. return results;
  56729. };
  56730. var mipmapGenerator = null;
  56731. if (!this._noMipmap &&
  56732. this._usePMREMGenerator) {
  56733. mipmapGenerator = function (data) {
  56734. // Custom setup of the generator matching with the PBR shader values.
  56735. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56736. return generator.filterCubeMap();
  56737. };
  56738. }
  56739. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  56740. };
  56741. /**
  56742. * Starts the loading process of the texture.
  56743. */
  56744. HDRCubeTexture.prototype.loadTexture = function () {
  56745. if (this._isBABYLONPreprocessed) {
  56746. this.loadBabylonTexture();
  56747. }
  56748. else {
  56749. this.loadHDRTexture();
  56750. }
  56751. };
  56752. HDRCubeTexture.prototype.clone = function () {
  56753. var size = this._isBABYLONPreprocessed ? null : this._size;
  56754. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56755. // Base texture
  56756. newTexture.level = this.level;
  56757. newTexture.wrapU = this.wrapU;
  56758. newTexture.wrapV = this.wrapV;
  56759. newTexture.coordinatesIndex = this.coordinatesIndex;
  56760. newTexture.coordinatesMode = this.coordinatesMode;
  56761. return newTexture;
  56762. };
  56763. // Methods
  56764. HDRCubeTexture.prototype.delayLoad = function () {
  56765. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56766. return;
  56767. }
  56768. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56769. this._texture = this._getFromCache(this.url, this._noMipmap);
  56770. if (!this._texture) {
  56771. this.loadTexture();
  56772. }
  56773. };
  56774. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56775. return this._textureMatrix;
  56776. };
  56777. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56778. var texture = null;
  56779. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56780. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56781. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56782. texture.name = parsedTexture.name;
  56783. texture.hasAlpha = parsedTexture.hasAlpha;
  56784. texture.level = parsedTexture.level;
  56785. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56786. }
  56787. return texture;
  56788. };
  56789. HDRCubeTexture.prototype.serialize = function () {
  56790. if (!this.name) {
  56791. return null;
  56792. }
  56793. var serializationObject = {};
  56794. serializationObject.name = this.name;
  56795. serializationObject.hasAlpha = this.hasAlpha;
  56796. serializationObject.isCube = true;
  56797. serializationObject.level = this.level;
  56798. serializationObject.size = this._size;
  56799. serializationObject.coordinatesMode = this.coordinatesMode;
  56800. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56801. serializationObject.generateHarmonics = this._generateHarmonics;
  56802. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56803. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56804. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56805. serializationObject.noMipmap = this._noMipmap;
  56806. return serializationObject;
  56807. };
  56808. /**
  56809. * Saves as a file the data contained in the texture in a binary format.
  56810. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56811. * as the spherical used in the lighting.
  56812. * @param url The HDR file url.
  56813. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56814. * @param onError Method called if any error happens during download.
  56815. * @return The packed binary data.
  56816. */
  56817. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56818. if (onError === void 0) { onError = null; }
  56819. var callback = function (buffer) {
  56820. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56821. // Returns a URL you can use as a href.
  56822. var objUrl = window.URL.createObjectURL(data);
  56823. // Simulates a link to it and click to dowload.
  56824. var a = document.createElement("a");
  56825. document.body.appendChild(a);
  56826. a.style.display = "none";
  56827. a.href = objUrl;
  56828. a.download = "envmap.babylon.hdr";
  56829. a.click();
  56830. };
  56831. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56832. };
  56833. /**
  56834. * Serializes the data contained in the texture in a binary format.
  56835. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56836. * as the spherical used in the lighting.
  56837. * @param url The HDR file url.
  56838. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56839. * @param onError Method called if any error happens during download.
  56840. * @return The packed binary data.
  56841. */
  56842. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56843. if (onError === void 0) { onError = null; }
  56844. // Needs the url tho create the texture.
  56845. if (!url) {
  56846. return null;
  56847. }
  56848. // Check Power of two size.
  56849. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56850. return null;
  56851. }
  56852. var getDataCallback = function (dataBuffer) {
  56853. // Extract the raw linear data.
  56854. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56855. // Generate harmonics if needed.
  56856. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56857. // Generate seamless faces
  56858. var mipGeneratorArray = [];
  56859. // Data are known to be in +X +Y +Z -X -Y -Z
  56860. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56861. mipGeneratorArray.push(cubeData.right); // +X
  56862. mipGeneratorArray.push(cubeData.left); // -X
  56863. mipGeneratorArray.push(cubeData.up); // +Y
  56864. mipGeneratorArray.push(cubeData.down); // -Y
  56865. mipGeneratorArray.push(cubeData.front); // +Z
  56866. mipGeneratorArray.push(cubeData.back); // -Z
  56867. // Custom setup of the generator matching with the PBR shader values.
  56868. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56869. var mippedData = generator.filterCubeMap();
  56870. // Compute required byte length.
  56871. var byteLength = 1 * 4; // Raw Data Version int32.
  56872. byteLength += 4; // CubeMap max mip face size int32.
  56873. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56874. // Add data size.
  56875. byteLength += 4; // Number of mip levels int32.
  56876. for (var level = 0; level < mippedData.length; level++) {
  56877. var mipSize = size >> level;
  56878. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56879. }
  56880. // Prepare binary structure.
  56881. var buffer = new ArrayBuffer(byteLength);
  56882. var intArrayView = new Int32Array(buffer);
  56883. var floatArrayView = new Float32Array(buffer);
  56884. // Fill header.
  56885. intArrayView[0] = 1; // Version 1.
  56886. intArrayView[1] = size; // CubeMap max mip face size.
  56887. // Fill polynomial information.
  56888. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56889. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56890. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56891. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56892. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56893. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56894. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56895. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56896. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56897. // Fill pixel data.
  56898. intArrayView[29] = mippedData.length; // Number of mip levels.
  56899. var startIndex = 30;
  56900. for (var level = 0; level < mippedData.length; level++) {
  56901. // Fill each pixel of the mip level.
  56902. var faceSize = Math.pow(size >> level, 2) * 3;
  56903. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56904. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56905. startIndex += faceSize;
  56906. }
  56907. }
  56908. // Callback.
  56909. callback(buffer);
  56910. };
  56911. // Download and process.
  56912. BABYLON.Tools.LoadFile(url, function (data) {
  56913. getDataCallback(data);
  56914. }, null, null, true, onError);
  56915. };
  56916. return HDRCubeTexture;
  56917. }(BABYLON.BaseTexture));
  56918. HDRCubeTexture._facesMapping = [
  56919. "right",
  56920. "up",
  56921. "front",
  56922. "left",
  56923. "down",
  56924. "back"
  56925. ];
  56926. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56927. })(BABYLON || (BABYLON = {}));
  56928. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56929. var BABYLON;
  56930. (function (BABYLON) {
  56931. var Debug;
  56932. (function (Debug) {
  56933. /**
  56934. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56935. */
  56936. var SkeletonViewer = (function () {
  56937. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56938. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56939. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56940. this.skeleton = skeleton;
  56941. this.mesh = mesh;
  56942. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56943. this.renderingGroupId = renderingGroupId;
  56944. this.color = BABYLON.Color3.White();
  56945. this._debugLines = [];
  56946. this._isEnabled = false;
  56947. this._scene = scene;
  56948. this.update();
  56949. this._renderFunction = this.update.bind(this);
  56950. }
  56951. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56952. get: function () {
  56953. return this._isEnabled;
  56954. },
  56955. set: function (value) {
  56956. if (this._isEnabled === value) {
  56957. return;
  56958. }
  56959. this._isEnabled = value;
  56960. if (value) {
  56961. this._scene.registerBeforeRender(this._renderFunction);
  56962. }
  56963. else {
  56964. this._scene.unregisterBeforeRender(this._renderFunction);
  56965. }
  56966. },
  56967. enumerable: true,
  56968. configurable: true
  56969. });
  56970. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56971. if (x === void 0) { x = 0; }
  56972. if (y === void 0) { y = 0; }
  56973. if (z === void 0) { z = 0; }
  56974. var tmat = BABYLON.Tmp.Matrix[0];
  56975. var parentBone = bone.getParent();
  56976. tmat.copyFrom(bone.getLocalMatrix());
  56977. if (x !== 0 || y !== 0 || z !== 0) {
  56978. var tmat2 = BABYLON.Tmp.Matrix[1];
  56979. BABYLON.Matrix.IdentityToRef(tmat2);
  56980. tmat2.m[12] = x;
  56981. tmat2.m[13] = y;
  56982. tmat2.m[14] = z;
  56983. tmat2.multiplyToRef(tmat, tmat);
  56984. }
  56985. if (parentBone) {
  56986. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56987. }
  56988. tmat.multiplyToRef(meshMat, tmat);
  56989. position.x = tmat.m[12];
  56990. position.y = tmat.m[13];
  56991. position.z = tmat.m[14];
  56992. };
  56993. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56994. var len = bones.length;
  56995. for (var i = 0; i < len; i++) {
  56996. var bone = bones[i];
  56997. var points = this._debugLines[i];
  56998. if (!points) {
  56999. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57000. this._debugLines[i] = points;
  57001. }
  57002. this._getBonePosition(points[0], bone, meshMat);
  57003. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  57004. }
  57005. };
  57006. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  57007. var len = bones.length;
  57008. var boneNum = 0;
  57009. for (var i = len - 1; i >= 0; i--) {
  57010. var childBone = bones[i];
  57011. var parentBone = childBone.getParent();
  57012. if (!parentBone) {
  57013. continue;
  57014. }
  57015. var points = this._debugLines[boneNum];
  57016. if (!points) {
  57017. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57018. this._debugLines[boneNum] = points;
  57019. }
  57020. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  57021. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  57022. boneNum++;
  57023. }
  57024. };
  57025. SkeletonViewer.prototype.update = function () {
  57026. if (this.autoUpdateBonesMatrices) {
  57027. this.skeleton.computeAbsoluteTransforms();
  57028. }
  57029. if (this.skeleton.bones[0].length === undefined) {
  57030. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57031. }
  57032. else {
  57033. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57034. }
  57035. if (!this._debugMesh) {
  57036. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  57037. this._debugMesh.renderingGroupId = this.renderingGroupId;
  57038. }
  57039. else {
  57040. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  57041. }
  57042. this._debugMesh.color = this.color;
  57043. };
  57044. SkeletonViewer.prototype.dispose = function () {
  57045. if (this._debugMesh) {
  57046. this.isEnabled = false;
  57047. this._debugMesh.dispose();
  57048. this._debugMesh = null;
  57049. }
  57050. };
  57051. return SkeletonViewer;
  57052. }());
  57053. Debug.SkeletonViewer = SkeletonViewer;
  57054. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57055. })(BABYLON || (BABYLON = {}));
  57056. //# sourceMappingURL=babylon.skeletonViewer.js.map
  57057. var BABYLON;
  57058. (function (BABYLON) {
  57059. var Debug;
  57060. (function (Debug) {
  57061. var AxesViewer = (function () {
  57062. function AxesViewer(scene, scaleLines) {
  57063. if (scaleLines === void 0) { scaleLines = 1; }
  57064. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57065. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57066. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57067. this.scaleLines = 1;
  57068. this.scaleLines = scaleLines;
  57069. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  57070. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  57071. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  57072. this._xmesh.renderingGroupId = 2;
  57073. this._ymesh.renderingGroupId = 2;
  57074. this._zmesh.renderingGroupId = 2;
  57075. this._xmesh.material.checkReadyOnlyOnce = true;
  57076. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  57077. this._ymesh.material.checkReadyOnlyOnce = true;
  57078. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  57079. this._zmesh.material.checkReadyOnlyOnce = true;
  57080. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  57081. this.scene = scene;
  57082. }
  57083. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  57084. var scaleLines = this.scaleLines;
  57085. var point1 = this._xline[0];
  57086. var point2 = this._xline[1];
  57087. point1.x = position.x;
  57088. point1.y = position.y;
  57089. point1.z = position.z;
  57090. point2.x = point1.x + xaxis.x * scaleLines;
  57091. point2.y = point1.y + xaxis.y * scaleLines;
  57092. point2.z = point1.z + xaxis.z * scaleLines;
  57093. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  57094. point1 = this._yline[0];
  57095. point2 = this._yline[1];
  57096. point1.x = position.x;
  57097. point1.y = position.y;
  57098. point1.z = position.z;
  57099. point2.x = point1.x + yaxis.x * scaleLines;
  57100. point2.y = point1.y + yaxis.y * scaleLines;
  57101. point2.z = point1.z + yaxis.z * scaleLines;
  57102. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  57103. point1 = this._zline[0];
  57104. point2 = this._zline[1];
  57105. point1.x = position.x;
  57106. point1.y = position.y;
  57107. point1.z = position.z;
  57108. point2.x = point1.x + zaxis.x * scaleLines;
  57109. point2.y = point1.y + zaxis.y * scaleLines;
  57110. point2.z = point1.z + zaxis.z * scaleLines;
  57111. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  57112. };
  57113. AxesViewer.prototype.dispose = function () {
  57114. if (this._xmesh) {
  57115. this._xmesh.dispose();
  57116. this._ymesh.dispose();
  57117. this._zmesh.dispose();
  57118. this._xmesh = null;
  57119. this._ymesh = null;
  57120. this._zmesh = null;
  57121. this._xline = null;
  57122. this._yline = null;
  57123. this._zline = null;
  57124. this.scene = null;
  57125. }
  57126. };
  57127. return AxesViewer;
  57128. }());
  57129. Debug.AxesViewer = AxesViewer;
  57130. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57131. })(BABYLON || (BABYLON = {}));
  57132. //# sourceMappingURL=babylon.axesViewer.js.map
  57133. var BABYLON;
  57134. (function (BABYLON) {
  57135. var Debug;
  57136. (function (Debug) {
  57137. var BoneAxesViewer = (function (_super) {
  57138. __extends(BoneAxesViewer, _super);
  57139. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  57140. if (scaleLines === void 0) { scaleLines = 1; }
  57141. var _this = _super.call(this, scene, scaleLines) || this;
  57142. _this.pos = BABYLON.Vector3.Zero();
  57143. _this.xaxis = BABYLON.Vector3.Zero();
  57144. _this.yaxis = BABYLON.Vector3.Zero();
  57145. _this.zaxis = BABYLON.Vector3.Zero();
  57146. _this.mesh = mesh;
  57147. _this.bone = bone;
  57148. return _this;
  57149. }
  57150. BoneAxesViewer.prototype.update = function () {
  57151. var bone = this.bone;
  57152. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  57153. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  57154. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  57155. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  57156. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  57157. };
  57158. BoneAxesViewer.prototype.dispose = function () {
  57159. if (this.pos) {
  57160. this.pos = null;
  57161. this.xaxis = null;
  57162. this.yaxis = null;
  57163. this.zaxis = null;
  57164. this.mesh = null;
  57165. this.bone = null;
  57166. _super.prototype.dispose.call(this);
  57167. }
  57168. };
  57169. return BoneAxesViewer;
  57170. }(Debug.AxesViewer));
  57171. Debug.BoneAxesViewer = BoneAxesViewer;
  57172. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57173. })(BABYLON || (BABYLON = {}));
  57174. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  57175. var BABYLON;
  57176. (function (BABYLON) {
  57177. /**
  57178. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57179. * It can help converting any input color in a desired output one. This can then be used to create effects
  57180. * from sepia, black and white to sixties or futuristic rendering...
  57181. *
  57182. * The only supported format is currently 3dl.
  57183. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57184. */
  57185. var ColorGradingTexture = (function (_super) {
  57186. __extends(ColorGradingTexture, _super);
  57187. /**
  57188. * Instantiates a ColorGradingTexture from the following parameters.
  57189. *
  57190. * @param url The location of the color gradind data (currently only supporting 3dl)
  57191. * @param scene The scene the texture will be used in
  57192. */
  57193. function ColorGradingTexture(url, scene) {
  57194. var _this = _super.call(this, scene) || this;
  57195. if (!url) {
  57196. return _this;
  57197. }
  57198. _this._textureMatrix = BABYLON.Matrix.Identity();
  57199. _this.name = url;
  57200. _this.url = url;
  57201. _this.hasAlpha = false;
  57202. _this.isCube = false;
  57203. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57204. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57205. _this.anisotropicFilteringLevel = 1;
  57206. _this._texture = _this._getFromCache(url, true);
  57207. if (!_this._texture) {
  57208. if (!scene.useDelayedTextureLoading) {
  57209. _this.loadTexture();
  57210. }
  57211. else {
  57212. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57213. }
  57214. }
  57215. return _this;
  57216. }
  57217. /**
  57218. * Returns the texture matrix used in most of the material.
  57219. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57220. */
  57221. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57222. return this._textureMatrix;
  57223. };
  57224. /**
  57225. * Occurs when the file being loaded is a .3dl LUT file.
  57226. */
  57227. ColorGradingTexture.prototype.load3dlTexture = function () {
  57228. var _this = this;
  57229. var mipLevels = 0;
  57230. var floatArrayView = null;
  57231. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57232. this._texture = texture;
  57233. var callback = function (text) {
  57234. var data;
  57235. var tempData;
  57236. var line;
  57237. var lines = text.split('\n');
  57238. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57239. var maxColor = 0;
  57240. for (var i = 0; i < lines.length; i++) {
  57241. line = lines[i];
  57242. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57243. continue;
  57244. if (line.indexOf('#') === 0)
  57245. continue;
  57246. var words = line.split(" ");
  57247. if (size === 0) {
  57248. // Number of space + one
  57249. size = words.length;
  57250. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57251. tempData = new Float32Array(size * size * size * 4);
  57252. continue;
  57253. }
  57254. if (size != 0) {
  57255. var r = Math.max(parseInt(words[0]), 0);
  57256. var g = Math.max(parseInt(words[1]), 0);
  57257. var b = Math.max(parseInt(words[2]), 0);
  57258. maxColor = Math.max(r, maxColor);
  57259. maxColor = Math.max(g, maxColor);
  57260. maxColor = Math.max(b, maxColor);
  57261. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57262. tempData[pixelStorageIndex + 0] = r;
  57263. tempData[pixelStorageIndex + 1] = g;
  57264. tempData[pixelStorageIndex + 2] = b;
  57265. tempData[pixelStorageIndex + 3] = 0;
  57266. pixelIndexSlice++;
  57267. if (pixelIndexSlice % size == 0) {
  57268. pixelIndexH++;
  57269. pixelIndexSlice = 0;
  57270. if (pixelIndexH % size == 0) {
  57271. pixelIndexW++;
  57272. pixelIndexH = 0;
  57273. }
  57274. }
  57275. }
  57276. }
  57277. for (var i = 0; i < tempData.length; i++) {
  57278. var value = tempData[i];
  57279. data[i] = (value / maxColor * 255);
  57280. }
  57281. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57282. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57283. };
  57284. BABYLON.Tools.LoadFile(this.url, callback);
  57285. return this._texture;
  57286. };
  57287. /**
  57288. * Starts the loading process of the texture.
  57289. */
  57290. ColorGradingTexture.prototype.loadTexture = function () {
  57291. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57292. this.load3dlTexture();
  57293. }
  57294. };
  57295. /**
  57296. * Clones the color gradind texture.
  57297. */
  57298. ColorGradingTexture.prototype.clone = function () {
  57299. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57300. // Base texture
  57301. newTexture.level = this.level;
  57302. return newTexture;
  57303. };
  57304. /**
  57305. * Called during delayed load for textures.
  57306. */
  57307. ColorGradingTexture.prototype.delayLoad = function () {
  57308. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57309. return;
  57310. }
  57311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57312. this._texture = this._getFromCache(this.url, true);
  57313. if (!this._texture) {
  57314. this.loadTexture();
  57315. }
  57316. };
  57317. /**
  57318. * Binds the color grading to the shader.
  57319. * @param colorGrading The texture to bind
  57320. * @param effect The effect to bind to
  57321. */
  57322. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57323. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57324. var x = colorGrading.level; // Texture Level
  57325. var y = colorGrading.getSize().height; // Texture Size example with 8
  57326. var z = y - 1.0; // SizeMinusOne 8 - 1
  57327. var w = 1 / y; // Space of 1 slice 1 / 8
  57328. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57329. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57330. 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
  57331. 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
  57332. 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
  57333. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57334. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57335. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57336. };
  57337. /**
  57338. * Prepare the list of uniforms associated with the ColorGrading effects.
  57339. * @param uniformsList The list of uniforms used in the effect
  57340. * @param samplersList The list of samplers used in the effect
  57341. */
  57342. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57343. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57344. samplersList.push("cameraColorGrading2DSampler");
  57345. };
  57346. /**
  57347. * Parses a color grading texture serialized by Babylon.
  57348. * @param parsedTexture The texture information being parsedTexture
  57349. * @param scene The scene to load the texture in
  57350. * @param rootUrl The root url of the data assets to load
  57351. * @return A color gradind texture
  57352. */
  57353. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57354. var texture = null;
  57355. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57356. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57357. texture.name = parsedTexture.name;
  57358. texture.level = parsedTexture.level;
  57359. }
  57360. return texture;
  57361. };
  57362. /**
  57363. * Serializes the LUT texture to json format.
  57364. */
  57365. ColorGradingTexture.prototype.serialize = function () {
  57366. if (!this.name) {
  57367. return null;
  57368. }
  57369. var serializationObject = {};
  57370. serializationObject.name = this.name;
  57371. serializationObject.level = this.level;
  57372. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57373. return serializationObject;
  57374. };
  57375. return ColorGradingTexture;
  57376. }(BABYLON.BaseTexture));
  57377. /**
  57378. * Empty line regex stored for GC.
  57379. */
  57380. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57381. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57382. })(BABYLON || (BABYLON = {}));
  57383. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57384. var BABYLON;
  57385. (function (BABYLON) {
  57386. /**
  57387. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57388. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57389. * 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;
  57390. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57391. */
  57392. var ColorCurves = (function () {
  57393. function ColorCurves() {
  57394. this._dirty = true;
  57395. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57396. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57397. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57398. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57399. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57400. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57401. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57402. this._globalHue = 30;
  57403. this._globalDensity = 0;
  57404. this._globalSaturation = 0;
  57405. this._globalExposure = 0;
  57406. this._highlightsHue = 30;
  57407. this._highlightsDensity = 0;
  57408. this._highlightsSaturation = 0;
  57409. this._highlightsExposure = 0;
  57410. this._midtonesHue = 30;
  57411. this._midtonesDensity = 0;
  57412. this._midtonesSaturation = 0;
  57413. this._midtonesExposure = 0;
  57414. this._shadowsHue = 30;
  57415. this._shadowsDensity = 0;
  57416. this._shadowsSaturation = 0;
  57417. this._shadowsExposure = 0;
  57418. }
  57419. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57420. /**
  57421. * Gets the global Hue value.
  57422. * 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).
  57423. */
  57424. get: function () {
  57425. return this._globalHue;
  57426. },
  57427. /**
  57428. * Sets the global Hue value.
  57429. * 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).
  57430. */
  57431. set: function (value) {
  57432. this._globalHue = value;
  57433. this._dirty = true;
  57434. },
  57435. enumerable: true,
  57436. configurable: true
  57437. });
  57438. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57439. /**
  57440. * Gets the global Density value.
  57441. * 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.
  57442. * Values less than zero provide a filter of opposite hue.
  57443. */
  57444. get: function () {
  57445. return this._globalDensity;
  57446. },
  57447. /**
  57448. * Sets the global Density value.
  57449. * 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.
  57450. * Values less than zero provide a filter of opposite hue.
  57451. */
  57452. set: function (value) {
  57453. this._globalDensity = value;
  57454. this._dirty = true;
  57455. },
  57456. enumerable: true,
  57457. configurable: true
  57458. });
  57459. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57460. /**
  57461. * Gets the global Saturation value.
  57462. * 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.
  57463. */
  57464. get: function () {
  57465. return this._globalSaturation;
  57466. },
  57467. /**
  57468. * Sets the global Saturation value.
  57469. * 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.
  57470. */
  57471. set: function (value) {
  57472. this._globalSaturation = value;
  57473. this._dirty = true;
  57474. },
  57475. enumerable: true,
  57476. configurable: true
  57477. });
  57478. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57479. /**
  57480. * Gets the highlights Hue value.
  57481. * 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).
  57482. */
  57483. get: function () {
  57484. return this._highlightsHue;
  57485. },
  57486. /**
  57487. * Sets the highlights Hue value.
  57488. * 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).
  57489. */
  57490. set: function (value) {
  57491. this._highlightsHue = value;
  57492. this._dirty = true;
  57493. },
  57494. enumerable: true,
  57495. configurable: true
  57496. });
  57497. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57498. /**
  57499. * Gets the highlights Density value.
  57500. * 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.
  57501. * Values less than zero provide a filter of opposite hue.
  57502. */
  57503. get: function () {
  57504. return this._highlightsDensity;
  57505. },
  57506. /**
  57507. * Sets the highlights Density value.
  57508. * 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.
  57509. * Values less than zero provide a filter of opposite hue.
  57510. */
  57511. set: function (value) {
  57512. this._highlightsDensity = value;
  57513. this._dirty = true;
  57514. },
  57515. enumerable: true,
  57516. configurable: true
  57517. });
  57518. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57519. /**
  57520. * Gets the highlights Saturation value.
  57521. * 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.
  57522. */
  57523. get: function () {
  57524. return this._highlightsSaturation;
  57525. },
  57526. /**
  57527. * Sets the highlights Saturation value.
  57528. * 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.
  57529. */
  57530. set: function (value) {
  57531. this._highlightsSaturation = value;
  57532. this._dirty = true;
  57533. },
  57534. enumerable: true,
  57535. configurable: true
  57536. });
  57537. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57538. /**
  57539. * Gets the highlights Exposure value.
  57540. * 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.
  57541. */
  57542. get: function () {
  57543. return this._highlightsExposure;
  57544. },
  57545. /**
  57546. * Sets the highlights Exposure value.
  57547. * 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.
  57548. */
  57549. set: function (value) {
  57550. this._highlightsExposure = value;
  57551. this._dirty = true;
  57552. },
  57553. enumerable: true,
  57554. configurable: true
  57555. });
  57556. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57557. /**
  57558. * Gets the midtones Hue value.
  57559. * 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).
  57560. */
  57561. get: function () {
  57562. return this._midtonesHue;
  57563. },
  57564. /**
  57565. * Sets the midtones Hue value.
  57566. * 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).
  57567. */
  57568. set: function (value) {
  57569. this._midtonesHue = value;
  57570. this._dirty = true;
  57571. },
  57572. enumerable: true,
  57573. configurable: true
  57574. });
  57575. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57576. /**
  57577. * Gets the midtones Density value.
  57578. * 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.
  57579. * Values less than zero provide a filter of opposite hue.
  57580. */
  57581. get: function () {
  57582. return this._midtonesDensity;
  57583. },
  57584. /**
  57585. * Sets the midtones Density value.
  57586. * 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.
  57587. * Values less than zero provide a filter of opposite hue.
  57588. */
  57589. set: function (value) {
  57590. this._midtonesDensity = value;
  57591. this._dirty = true;
  57592. },
  57593. enumerable: true,
  57594. configurable: true
  57595. });
  57596. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57597. /**
  57598. * Gets the midtones Saturation value.
  57599. * 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.
  57600. */
  57601. get: function () {
  57602. return this._midtonesSaturation;
  57603. },
  57604. /**
  57605. * Sets the midtones Saturation value.
  57606. * 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.
  57607. */
  57608. set: function (value) {
  57609. this._midtonesSaturation = value;
  57610. this._dirty = true;
  57611. },
  57612. enumerable: true,
  57613. configurable: true
  57614. });
  57615. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57616. /**
  57617. * Gets the midtones Exposure value.
  57618. * 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.
  57619. */
  57620. get: function () {
  57621. return this._midtonesExposure;
  57622. },
  57623. /**
  57624. * Sets the midtones Exposure value.
  57625. * 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.
  57626. */
  57627. set: function (value) {
  57628. this._midtonesExposure = value;
  57629. this._dirty = true;
  57630. },
  57631. enumerable: true,
  57632. configurable: true
  57633. });
  57634. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57635. /**
  57636. * Gets the shadows Hue value.
  57637. * 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).
  57638. */
  57639. get: function () {
  57640. return this._shadowsHue;
  57641. },
  57642. /**
  57643. * Sets the shadows Hue value.
  57644. * 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).
  57645. */
  57646. set: function (value) {
  57647. this._shadowsHue = value;
  57648. this._dirty = true;
  57649. },
  57650. enumerable: true,
  57651. configurable: true
  57652. });
  57653. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57654. /**
  57655. * Gets the shadows Density value.
  57656. * 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.
  57657. * Values less than zero provide a filter of opposite hue.
  57658. */
  57659. get: function () {
  57660. return this._shadowsDensity;
  57661. },
  57662. /**
  57663. * Sets the shadows Density value.
  57664. * 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.
  57665. * Values less than zero provide a filter of opposite hue.
  57666. */
  57667. set: function (value) {
  57668. this._shadowsDensity = value;
  57669. this._dirty = true;
  57670. },
  57671. enumerable: true,
  57672. configurable: true
  57673. });
  57674. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57675. /**
  57676. * Gets the shadows Saturation value.
  57677. * 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.
  57678. */
  57679. get: function () {
  57680. return this._shadowsSaturation;
  57681. },
  57682. /**
  57683. * Sets the shadows Saturation value.
  57684. * 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.
  57685. */
  57686. set: function (value) {
  57687. this._shadowsSaturation = value;
  57688. this._dirty = true;
  57689. },
  57690. enumerable: true,
  57691. configurable: true
  57692. });
  57693. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57694. /**
  57695. * Gets the shadows Exposure value.
  57696. * 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.
  57697. */
  57698. get: function () {
  57699. return this._shadowsExposure;
  57700. },
  57701. /**
  57702. * Sets the shadows Exposure value.
  57703. * 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.
  57704. */
  57705. set: function (value) {
  57706. this._shadowsExposure = value;
  57707. this._dirty = true;
  57708. },
  57709. enumerable: true,
  57710. configurable: true
  57711. });
  57712. /**
  57713. * Binds the color curves to the shader.
  57714. * @param colorCurves The color curve to bind
  57715. * @param effect The effect to bind to
  57716. */
  57717. ColorCurves.Bind = function (colorCurves, effect) {
  57718. if (colorCurves._dirty) {
  57719. colorCurves._dirty = false;
  57720. // Fill in global info.
  57721. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57722. // Compute highlights info.
  57723. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57724. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57725. // Compute midtones info.
  57726. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57727. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57728. // Compute shadows info.
  57729. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57730. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57731. // Compute deltas (neutral is midtones).
  57732. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57733. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57734. }
  57735. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57736. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57737. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57738. };
  57739. /**
  57740. * Prepare the list of uniforms associated with the ColorCurves effects.
  57741. * @param uniformsList The list of uniforms used in the effect
  57742. */
  57743. ColorCurves.PrepareUniforms = function (uniformsList) {
  57744. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57745. };
  57746. /**
  57747. * Returns color grading data based on a hue, density, saturation and exposure value.
  57748. * @param filterHue The hue of the color filter.
  57749. * @param filterDensity The density of the color filter.
  57750. * @param saturation The saturation.
  57751. * @param exposure The exposure.
  57752. * @param result The result data container.
  57753. */
  57754. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57755. if (hue == null) {
  57756. return;
  57757. }
  57758. hue = ColorCurves.clamp(hue, 0, 360);
  57759. density = ColorCurves.clamp(density, -100, 100);
  57760. saturation = ColorCurves.clamp(saturation, -100, 100);
  57761. exposure = ColorCurves.clamp(exposure, -100, 100);
  57762. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57763. // so that the maximum filter density is only 50% control. This provides fine control
  57764. // for small values and reasonable range.
  57765. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57766. density *= 0.5;
  57767. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57768. if (density < 0) {
  57769. density *= -1;
  57770. hue = (hue + 180) % 360;
  57771. }
  57772. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57773. result.scaleToRef(2, result);
  57774. result.a = 1 + 0.01 * saturation;
  57775. };
  57776. /**
  57777. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57778. * @param value The input slider value in range [-100,100].
  57779. * @returns Adjusted value.
  57780. */
  57781. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57782. value /= 100;
  57783. var x = Math.abs(value);
  57784. x = Math.pow(x, 2);
  57785. if (value < 0) {
  57786. x *= -1;
  57787. }
  57788. x *= 100;
  57789. return x;
  57790. };
  57791. /**
  57792. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57793. * @param hue The hue (H) input.
  57794. * @param saturation The saturation (S) input.
  57795. * @param brightness The brightness (B) input.
  57796. * @result An RGBA color represented as Vector4.
  57797. */
  57798. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57799. var h = ColorCurves.clamp(hue, 0, 360);
  57800. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57801. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57802. if (s === 0) {
  57803. result.r = v;
  57804. result.g = v;
  57805. result.b = v;
  57806. }
  57807. else {
  57808. // sector 0 to 5
  57809. h /= 60;
  57810. var i = Math.floor(h);
  57811. // fractional part of h
  57812. var f = h - i;
  57813. var p = v * (1 - s);
  57814. var q = v * (1 - s * f);
  57815. var t = v * (1 - s * (1 - f));
  57816. switch (i) {
  57817. case 0:
  57818. result.r = v;
  57819. result.g = t;
  57820. result.b = p;
  57821. break;
  57822. case 1:
  57823. result.r = q;
  57824. result.g = v;
  57825. result.b = p;
  57826. break;
  57827. case 2:
  57828. result.r = p;
  57829. result.g = v;
  57830. result.b = t;
  57831. break;
  57832. case 3:
  57833. result.r = p;
  57834. result.g = q;
  57835. result.b = v;
  57836. break;
  57837. case 4:
  57838. result.r = t;
  57839. result.g = p;
  57840. result.b = v;
  57841. break;
  57842. default:
  57843. result.r = v;
  57844. result.g = p;
  57845. result.b = q;
  57846. break;
  57847. }
  57848. }
  57849. result.a = 1;
  57850. };
  57851. /**
  57852. * Returns a value clamped between min and max
  57853. * @param value The value to clamp
  57854. * @param min The minimum of value
  57855. * @param max The maximum of value
  57856. * @returns The clamped value.
  57857. */
  57858. ColorCurves.clamp = function (value, min, max) {
  57859. return Math.min(Math.max(value, min), max);
  57860. };
  57861. /**
  57862. * Clones the current color curve instance.
  57863. * @return The cloned curves
  57864. */
  57865. ColorCurves.prototype.clone = function () {
  57866. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57867. };
  57868. /**
  57869. * Serializes the current color curve instance to a json representation.
  57870. * @return a JSON representation
  57871. */
  57872. ColorCurves.prototype.serialize = function () {
  57873. return BABYLON.SerializationHelper.Serialize(this);
  57874. };
  57875. /**
  57876. * Parses the color curve from a json representation.
  57877. * @param source the JSON source to parse
  57878. * @return The parsed curves
  57879. */
  57880. ColorCurves.Parse = function (source) {
  57881. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57882. };
  57883. return ColorCurves;
  57884. }());
  57885. __decorate([
  57886. BABYLON.serialize()
  57887. ], ColorCurves.prototype, "_globalHue", void 0);
  57888. __decorate([
  57889. BABYLON.serialize()
  57890. ], ColorCurves.prototype, "_globalDensity", void 0);
  57891. __decorate([
  57892. BABYLON.serialize()
  57893. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57894. __decorate([
  57895. BABYLON.serialize()
  57896. ], ColorCurves.prototype, "_globalExposure", void 0);
  57897. __decorate([
  57898. BABYLON.serialize()
  57899. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57900. __decorate([
  57901. BABYLON.serialize()
  57902. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57903. __decorate([
  57904. BABYLON.serialize()
  57905. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57906. __decorate([
  57907. BABYLON.serialize()
  57908. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57909. __decorate([
  57910. BABYLON.serialize()
  57911. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57912. __decorate([
  57913. BABYLON.serialize()
  57914. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57915. __decorate([
  57916. BABYLON.serialize()
  57917. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57918. __decorate([
  57919. BABYLON.serialize()
  57920. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57921. BABYLON.ColorCurves = ColorCurves;
  57922. })(BABYLON || (BABYLON = {}));
  57923. //# sourceMappingURL=babylon.colorCurves.js.map
  57924. var BABYLON;
  57925. (function (BABYLON) {
  57926. var PBRMaterialDefines = (function (_super) {
  57927. __extends(PBRMaterialDefines, _super);
  57928. function PBRMaterialDefines() {
  57929. var _this = _super.call(this) || this;
  57930. _this.ALBEDO = false;
  57931. _this.AMBIENT = false;
  57932. _this.OPACITY = false;
  57933. _this.OPACITYRGB = false;
  57934. _this.REFLECTION = false;
  57935. _this.EMISSIVE = false;
  57936. _this.REFLECTIVITY = false;
  57937. _this.BUMP = false;
  57938. _this.PARALLAX = false;
  57939. _this.PARALLAXOCCLUSION = false;
  57940. _this.SPECULAROVERALPHA = false;
  57941. _this.CLIPPLANE = false;
  57942. _this.ALPHATEST = false;
  57943. _this.ALPHAFROMALBEDO = false;
  57944. _this.POINTSIZE = false;
  57945. _this.FOG = false;
  57946. _this.SPECULARTERM = false;
  57947. _this.OPACITYFRESNEL = false;
  57948. _this.EMISSIVEFRESNEL = false;
  57949. _this.FRESNEL = false;
  57950. _this.NORMAL = false;
  57951. _this.TANGENT = false;
  57952. _this.UV1 = false;
  57953. _this.UV2 = false;
  57954. _this.VERTEXCOLOR = false;
  57955. _this.VERTEXALPHA = false;
  57956. _this.NUM_BONE_INFLUENCERS = 0;
  57957. _this.BonesPerMesh = 0;
  57958. _this.INSTANCES = false;
  57959. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  57960. _this.MICROSURFACEAUTOMATIC = false;
  57961. _this.EMISSIVEASILLUMINATION = false;
  57962. _this.LINKEMISSIVEWITHALBEDO = false;
  57963. _this.LIGHTMAP = false;
  57964. _this.USELIGHTMAPASSHADOWMAP = false;
  57965. _this.REFLECTIONMAP_3D = false;
  57966. _this.REFLECTIONMAP_SPHERICAL = false;
  57967. _this.REFLECTIONMAP_PLANAR = false;
  57968. _this.REFLECTIONMAP_CUBIC = false;
  57969. _this.REFLECTIONMAP_PROJECTION = false;
  57970. _this.REFLECTIONMAP_SKYBOX = false;
  57971. _this.REFLECTIONMAP_EXPLICIT = false;
  57972. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  57973. _this.INVERTCUBICMAP = false;
  57974. _this.LOGARITHMICDEPTH = false;
  57975. _this.CAMERATONEMAP = false;
  57976. _this.CAMERACONTRAST = false;
  57977. _this.CAMERACOLORGRADING = false;
  57978. _this.CAMERACOLORCURVES = false;
  57979. _this.OVERLOADEDVALUES = false;
  57980. _this.OVERLOADEDSHADOWVALUES = false;
  57981. _this.USESPHERICALFROMREFLECTIONMAP = false;
  57982. _this.REFRACTION = false;
  57983. _this.REFRACTIONMAP_3D = false;
  57984. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  57985. _this.REFRACTIONMAPINLINEARSPACE = false;
  57986. _this.LODBASEDMICROSFURACE = false;
  57987. _this.USEPHYSICALLIGHTFALLOFF = false;
  57988. _this.RADIANCEOVERALPHA = false;
  57989. _this.USEPMREMREFLECTION = false;
  57990. _this.USEPMREMREFRACTION = false;
  57991. _this.INVERTNORMALMAPX = false;
  57992. _this.INVERTNORMALMAPY = false;
  57993. _this.TWOSIDEDLIGHTING = false;
  57994. _this.SHADOWFULLFLOAT = false;
  57995. _this.METALLICWORKFLOW = false;
  57996. _this.METALLICROUGHNESSMAP = false;
  57997. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  57998. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  57999. _this.rebuild();
  58000. return _this;
  58001. }
  58002. return PBRMaterialDefines;
  58003. }(BABYLON.MaterialDefines));
  58004. /**
  58005. * The Physically based material of BJS.
  58006. *
  58007. * This offers the main features of a standard PBR material.
  58008. * For more information, please refer to the documentation :
  58009. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  58010. */
  58011. var PBRMaterial = (function (_super) {
  58012. __extends(PBRMaterial, _super);
  58013. /**
  58014. * Instantiates a new PBRMaterial instance.
  58015. *
  58016. * @param name The material name
  58017. * @param scene The scene the material will be use in.
  58018. */
  58019. function PBRMaterial(name, scene) {
  58020. var _this = _super.call(this, name, scene) || this;
  58021. /**
  58022. * Intensity of the direct lights e.g. the four lights available in your scene.
  58023. * This impacts both the direct diffuse and specular highlights.
  58024. */
  58025. _this.directIntensity = 1.0;
  58026. /**
  58027. * Intensity of the emissive part of the material.
  58028. * This helps controlling the emissive effect without modifying the emissive color.
  58029. */
  58030. _this.emissiveIntensity = 1.0;
  58031. /**
  58032. * Intensity of the environment e.g. how much the environment will light the object
  58033. * either through harmonics for rough material or through the refelction for shiny ones.
  58034. */
  58035. _this.environmentIntensity = 1.0;
  58036. /**
  58037. * This is a special control allowing the reduction of the specular highlights coming from the
  58038. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  58039. */
  58040. _this.specularIntensity = 1.0;
  58041. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  58042. /**
  58043. * Debug Control allowing disabling the bump map on this material.
  58044. */
  58045. _this.disableBumpMap = false;
  58046. /**
  58047. * Debug Control helping enforcing or dropping the darkness of shadows.
  58048. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  58049. */
  58050. _this.overloadedShadowIntensity = 1.0;
  58051. /**
  58052. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  58053. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  58054. */
  58055. _this.overloadedShadeIntensity = 1.0;
  58056. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  58057. /**
  58058. * The camera exposure used on this material.
  58059. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  58060. * This corresponds to a photographic exposure.
  58061. */
  58062. _this.cameraExposure = 1.0;
  58063. /**
  58064. * The camera contrast used on this material.
  58065. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58066. */
  58067. _this.cameraContrast = 1.0;
  58068. /**
  58069. * Color Grading 2D Lookup Texture.
  58070. * This allows special effects like sepia, black and white to sixties rendering style.
  58071. */
  58072. _this.cameraColorGradingTexture = null;
  58073. /**
  58074. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58075. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58076. * 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;
  58077. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58078. */
  58079. _this.cameraColorCurves = null;
  58080. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58081. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58082. /**
  58083. * Debug Control allowing to overload the ambient color.
  58084. * This as to be use with the overloadedAmbientIntensity parameter.
  58085. */
  58086. _this.overloadedAmbient = BABYLON.Color3.White();
  58087. /**
  58088. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58089. */
  58090. _this.overloadedAmbientIntensity = 0.0;
  58091. /**
  58092. * Debug Control allowing to overload the albedo color.
  58093. * This as to be use with the overloadedAlbedoIntensity parameter.
  58094. */
  58095. _this.overloadedAlbedo = BABYLON.Color3.White();
  58096. /**
  58097. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58098. */
  58099. _this.overloadedAlbedoIntensity = 0.0;
  58100. /**
  58101. * Debug Control allowing to overload the reflectivity color.
  58102. * This as to be use with the overloadedReflectivityIntensity parameter.
  58103. */
  58104. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58105. /**
  58106. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58107. */
  58108. _this.overloadedReflectivityIntensity = 0.0;
  58109. /**
  58110. * Debug Control allowing to overload the emissive color.
  58111. * This as to be use with the overloadedEmissiveIntensity parameter.
  58112. */
  58113. _this.overloadedEmissive = BABYLON.Color3.White();
  58114. /**
  58115. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58116. */
  58117. _this.overloadedEmissiveIntensity = 0.0;
  58118. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  58119. /**
  58120. * Debug Control allowing to overload the reflection color.
  58121. * This as to be use with the overloadedReflectionIntensity parameter.
  58122. */
  58123. _this.overloadedReflection = BABYLON.Color3.White();
  58124. /**
  58125. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  58126. */
  58127. _this.overloadedReflectionIntensity = 0.0;
  58128. /**
  58129. * Debug Control allowing to overload the microsurface.
  58130. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  58131. */
  58132. _this.overloadedMicroSurface = 0.0;
  58133. /**
  58134. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  58135. */
  58136. _this.overloadedMicroSurfaceIntensity = 0.0;
  58137. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  58138. /**
  58139. * AKA Occlusion Texture Intensity in other nomenclature.
  58140. */
  58141. _this.ambientTextureStrength = 1.0;
  58142. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  58143. /**
  58144. * AKA Diffuse Color in other nomenclature.
  58145. */
  58146. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  58147. /**
  58148. * AKA Specular Color in other nomenclature.
  58149. */
  58150. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  58151. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  58152. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  58153. /**
  58154. * AKA Glossiness in other nomenclature.
  58155. */
  58156. _this.microSurface = 0.9;
  58157. /**
  58158. * source material index of refraction (IOR)' / 'destination material IOR.
  58159. */
  58160. _this.indexOfRefraction = 0.66;
  58161. /**
  58162. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  58163. */
  58164. _this.invertRefractionY = false;
  58165. /**
  58166. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  58167. * Materials half opaque for instance using refraction could benefit from this control.
  58168. */
  58169. _this.linkRefractionWithTransparency = false;
  58170. /**
  58171. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58172. */
  58173. _this.linkEmissiveWithAlbedo = false;
  58174. _this.useLightmapAsShadowmap = false;
  58175. /**
  58176. * In this mode, the emissive informtaion will always be added to the lighting once.
  58177. * A light for instance can be thought as emissive.
  58178. */
  58179. _this.useEmissiveAsIllumination = false;
  58180. /**
  58181. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58182. */
  58183. _this.useAlphaFromAlbedoTexture = false;
  58184. /**
  58185. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58186. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58187. */
  58188. _this.useSpecularOverAlpha = true;
  58189. /**
  58190. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58191. */
  58192. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58193. /**
  58194. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  58195. */
  58196. _this.useRoughnessFromMetallicTextureAlpha = true;
  58197. /**
  58198. * Specifies if the metallic texture contains the roughness information in its green channel.
  58199. */
  58200. _this.useRoughnessFromMetallicTextureGreen = false;
  58201. /**
  58202. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58203. * The material will try to infer what glossiness each pixel should be.
  58204. */
  58205. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  58206. /**
  58207. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58208. * the creation of the material.
  58209. */
  58210. _this.useScalarInLinearSpace = false;
  58211. /**
  58212. * BJS is using an harcoded light falloff based on a manually sets up range.
  58213. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58214. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58215. */
  58216. _this.usePhysicalLightFalloff = true;
  58217. /**
  58218. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58219. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58220. */
  58221. _this.useRadianceOverAlpha = true;
  58222. /**
  58223. * Allows using the bump map in parallax mode.
  58224. */
  58225. _this.useParallax = false;
  58226. /**
  58227. * Allows using the bump map in parallax occlusion mode.
  58228. */
  58229. _this.useParallaxOcclusion = false;
  58230. /**
  58231. * Controls the scale bias of the parallax mode.
  58232. */
  58233. _this.parallaxScaleBias = 0.05;
  58234. /**
  58235. * If sets to true, disables all the lights affecting the material.
  58236. */
  58237. _this.disableLighting = false;
  58238. /**
  58239. * Number of Simultaneous lights allowed on the material.
  58240. */
  58241. _this.maxSimultaneousLights = 4;
  58242. /**
  58243. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58244. */
  58245. _this.invertNormalMapX = false;
  58246. /**
  58247. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58248. */
  58249. _this.invertNormalMapY = false;
  58250. /**
  58251. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  58252. */
  58253. _this.twoSidedLighting = false;
  58254. _this._renderTargets = new BABYLON.SmartArray(16);
  58255. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58256. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58257. _this._tempColor = new BABYLON.Color3();
  58258. _this._defines = new PBRMaterialDefines();
  58259. _this._cachedDefines = new PBRMaterialDefines();
  58260. _this._myScene = null;
  58261. _this._myShadowGenerator = null;
  58262. _this._cachedDefines.BonesPerMesh = -1;
  58263. _this.getRenderTargetTextures = function () {
  58264. _this._renderTargets.reset();
  58265. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58266. _this._renderTargets.push(_this.reflectionTexture);
  58267. }
  58268. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58269. _this._renderTargets.push(_this.refractionTexture);
  58270. }
  58271. return _this._renderTargets;
  58272. };
  58273. return _this;
  58274. }
  58275. PBRMaterial.prototype.getClassName = function () {
  58276. return "PBRMaterial";
  58277. };
  58278. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58279. get: function () {
  58280. return this._useLogarithmicDepth;
  58281. },
  58282. set: function (value) {
  58283. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58284. },
  58285. enumerable: true,
  58286. configurable: true
  58287. });
  58288. PBRMaterial.prototype.needAlphaBlending = function () {
  58289. if (this.linkRefractionWithTransparency) {
  58290. return false;
  58291. }
  58292. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58293. };
  58294. PBRMaterial.prototype.needAlphaTesting = function () {
  58295. if (this.linkRefractionWithTransparency) {
  58296. return false;
  58297. }
  58298. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58299. };
  58300. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58301. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58302. };
  58303. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58304. return this.albedoTexture;
  58305. };
  58306. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58307. if (!mesh) {
  58308. return true;
  58309. }
  58310. if (this._defines.INSTANCES !== useInstances) {
  58311. return false;
  58312. }
  58313. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58314. return true;
  58315. }
  58316. return false;
  58317. };
  58318. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58319. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58320. };
  58321. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58322. if (!useScalarInLinear) {
  58323. color.toLinearSpaceToRef(ref);
  58324. }
  58325. else {
  58326. ref.r = color.r;
  58327. ref.g = color.g;
  58328. ref.b = color.b;
  58329. }
  58330. };
  58331. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58332. var lightIndex = 0;
  58333. var depthValuesAlreadySet = false;
  58334. for (var index = 0; index < scene.lights.length; index++) {
  58335. var light = scene.lights[index];
  58336. if (!light.isEnabled()) {
  58337. continue;
  58338. }
  58339. if (!light.canAffectMesh(mesh)) {
  58340. continue;
  58341. }
  58342. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58343. // GAMMA CORRECTION.
  58344. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58345. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58346. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58347. if (defines["SPECULARTERM"]) {
  58348. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58349. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58350. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58351. }
  58352. // Shadows
  58353. if (scene.shadowsEnabled) {
  58354. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58355. }
  58356. lightIndex++;
  58357. if (lightIndex === maxSimultaneousLights)
  58358. break;
  58359. }
  58360. };
  58361. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  58362. if (this.isFrozen) {
  58363. if (this._wasPreviouslyReady) {
  58364. return true;
  58365. }
  58366. }
  58367. var scene = this.getScene();
  58368. var engine = scene.getEngine();
  58369. var needNormals = false;
  58370. var needUVs = false;
  58371. this._defines.reset();
  58372. if (scene.lightsEnabled && !this.disableLighting) {
  58373. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  58374. }
  58375. if (!this.checkReadyOnEveryCall) {
  58376. if (this._renderId === scene.getRenderId()) {
  58377. if (this._checkCache(scene, mesh, useInstances)) {
  58378. return true;
  58379. }
  58380. }
  58381. }
  58382. if (scene.texturesEnabled) {
  58383. if (scene.getEngine().getCaps().textureLOD) {
  58384. this._defines.LODBASEDMICROSFURACE = true;
  58385. }
  58386. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58387. if (!this.albedoTexture.isReady()) {
  58388. return false;
  58389. }
  58390. else {
  58391. needUVs = true;
  58392. this._defines.ALBEDO = true;
  58393. }
  58394. }
  58395. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58396. if (!this.ambientTexture.isReady()) {
  58397. return false;
  58398. }
  58399. else {
  58400. needUVs = true;
  58401. this._defines.AMBIENT = true;
  58402. }
  58403. }
  58404. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58405. if (!this.opacityTexture.isReady()) {
  58406. return false;
  58407. }
  58408. else {
  58409. needUVs = true;
  58410. this._defines.OPACITY = true;
  58411. if (this.opacityTexture.getAlphaFromRGB) {
  58412. this._defines.OPACITYRGB = true;
  58413. }
  58414. }
  58415. }
  58416. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58417. if (!this.reflectionTexture.isReady()) {
  58418. return false;
  58419. }
  58420. else {
  58421. needNormals = true;
  58422. this._defines.REFLECTION = true;
  58423. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  58424. this._defines.INVERTCUBICMAP = true;
  58425. }
  58426. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  58427. switch (this.reflectionTexture.coordinatesMode) {
  58428. case BABYLON.Texture.CUBIC_MODE:
  58429. case BABYLON.Texture.INVCUBIC_MODE:
  58430. this._defines.REFLECTIONMAP_CUBIC = true;
  58431. break;
  58432. case BABYLON.Texture.EXPLICIT_MODE:
  58433. this._defines.REFLECTIONMAP_EXPLICIT = true;
  58434. break;
  58435. case BABYLON.Texture.PLANAR_MODE:
  58436. this._defines.REFLECTIONMAP_PLANAR = true;
  58437. break;
  58438. case BABYLON.Texture.PROJECTION_MODE:
  58439. this._defines.REFLECTIONMAP_PROJECTION = true;
  58440. break;
  58441. case BABYLON.Texture.SKYBOX_MODE:
  58442. this._defines.REFLECTIONMAP_SKYBOX = true;
  58443. break;
  58444. case BABYLON.Texture.SPHERICAL_MODE:
  58445. this._defines.REFLECTIONMAP_SPHERICAL = true;
  58446. break;
  58447. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  58448. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  58449. break;
  58450. }
  58451. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  58452. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  58453. needNormals = true;
  58454. if (this.reflectionTexture.isPMREM) {
  58455. this._defines.USEPMREMREFLECTION = true;
  58456. }
  58457. }
  58458. }
  58459. }
  58460. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58461. if (!this.lightmapTexture.isReady()) {
  58462. return false;
  58463. }
  58464. else {
  58465. needUVs = true;
  58466. this._defines.LIGHTMAP = true;
  58467. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  58468. }
  58469. }
  58470. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58471. if (!this.emissiveTexture.isReady()) {
  58472. return false;
  58473. }
  58474. else {
  58475. needUVs = true;
  58476. this._defines.EMISSIVE = true;
  58477. }
  58478. }
  58479. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58480. if (this.metallicTexture) {
  58481. if (!this.metallicTexture.isReady()) {
  58482. return false;
  58483. }
  58484. else {
  58485. needUVs = true;
  58486. this._defines.METALLICWORKFLOW = true;
  58487. this._defines.METALLICROUGHNESSMAP = true;
  58488. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  58489. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  58490. }
  58491. }
  58492. else if (this.reflectivityTexture) {
  58493. if (!this.reflectivityTexture.isReady()) {
  58494. return false;
  58495. }
  58496. else {
  58497. needUVs = true;
  58498. this._defines.REFLECTIVITY = true;
  58499. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  58500. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  58501. }
  58502. }
  58503. }
  58504. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58505. if (!this.bumpTexture.isReady()) {
  58506. return false;
  58507. }
  58508. else {
  58509. needUVs = true;
  58510. this._defines.BUMP = true;
  58511. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58512. this._defines.PARALLAX = true;
  58513. if (this.useParallaxOcclusion) {
  58514. this._defines.PARALLAXOCCLUSION = true;
  58515. }
  58516. }
  58517. if (this.invertNormalMapX) {
  58518. this._defines.INVERTNORMALMAPX = true;
  58519. }
  58520. if (this.invertNormalMapY) {
  58521. this._defines.INVERTNORMALMAPY = true;
  58522. }
  58523. if (scene._mirroredCameraPosition) {
  58524. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  58525. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  58526. }
  58527. }
  58528. }
  58529. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58530. if (!this.refractionTexture.isReady()) {
  58531. return false;
  58532. }
  58533. else {
  58534. needUVs = true;
  58535. this._defines.REFRACTION = true;
  58536. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  58537. if (this.linkRefractionWithTransparency) {
  58538. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  58539. }
  58540. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  58541. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  58542. if (this.refractionTexture.isPMREM) {
  58543. this._defines.USEPMREMREFRACTION = true;
  58544. }
  58545. }
  58546. }
  58547. }
  58548. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58549. if (!this.cameraColorGradingTexture.isReady()) {
  58550. return false;
  58551. }
  58552. else {
  58553. this._defines.CAMERACOLORGRADING = true;
  58554. }
  58555. }
  58556. if (!this.backFaceCulling && this.twoSidedLighting) {
  58557. this._defines.TWOSIDEDLIGHTING = true;
  58558. }
  58559. }
  58560. // Effect
  58561. if (scene.clipPlane) {
  58562. this._defines.CLIPPLANE = true;
  58563. }
  58564. if (engine.getAlphaTesting()) {
  58565. this._defines.ALPHATEST = true;
  58566. }
  58567. if (this._shouldUseAlphaFromAlbedoTexture()) {
  58568. this._defines.ALPHAFROMALBEDO = true;
  58569. }
  58570. if (this.useEmissiveAsIllumination) {
  58571. this._defines.EMISSIVEASILLUMINATION = true;
  58572. }
  58573. if (this.linkEmissiveWithAlbedo) {
  58574. this._defines.LINKEMISSIVEWITHALBEDO = true;
  58575. }
  58576. if (this.useLogarithmicDepth) {
  58577. this._defines.LOGARITHMICDEPTH = true;
  58578. }
  58579. if (this.cameraContrast != 1) {
  58580. this._defines.CAMERACONTRAST = true;
  58581. }
  58582. if (this.cameraExposure != 1) {
  58583. this._defines.CAMERATONEMAP = true;
  58584. }
  58585. if (this.cameraColorCurves) {
  58586. this._defines.CAMERACOLORCURVES = true;
  58587. }
  58588. if (this.overloadedShadeIntensity != 1 ||
  58589. this.overloadedShadowIntensity != 1) {
  58590. this._defines.OVERLOADEDSHADOWVALUES = true;
  58591. }
  58592. if (this.overloadedMicroSurfaceIntensity > 0 ||
  58593. this.overloadedEmissiveIntensity > 0 ||
  58594. this.overloadedReflectivityIntensity > 0 ||
  58595. this.overloadedAlbedoIntensity > 0 ||
  58596. this.overloadedAmbientIntensity > 0 ||
  58597. this.overloadedReflectionIntensity > 0) {
  58598. this._defines.OVERLOADEDVALUES = true;
  58599. }
  58600. // Point size
  58601. if (this.pointsCloud || scene.forcePointsCloud) {
  58602. this._defines.POINTSIZE = true;
  58603. }
  58604. // Fog
  58605. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58606. this._defines.FOG = true;
  58607. }
  58608. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58609. // Fresnel
  58610. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  58611. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58612. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58613. this._defines.OPACITYFRESNEL = true;
  58614. }
  58615. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58616. this._defines.EMISSIVEFRESNEL = true;
  58617. }
  58618. needNormals = true;
  58619. this._defines.FRESNEL = true;
  58620. }
  58621. }
  58622. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  58623. this._defines.SPECULAROVERALPHA = true;
  58624. }
  58625. if (this.usePhysicalLightFalloff) {
  58626. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  58627. }
  58628. if (this.useRadianceOverAlpha) {
  58629. this._defines.RADIANCEOVERALPHA = true;
  58630. }
  58631. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  58632. this._defines.METALLICWORKFLOW = true;
  58633. }
  58634. // Attribs
  58635. if (mesh) {
  58636. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58637. this._defines.NORMAL = true;
  58638. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  58639. this._defines.TANGENT = true;
  58640. }
  58641. }
  58642. if (needUVs) {
  58643. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58644. this._defines.UV1 = true;
  58645. }
  58646. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58647. this._defines.UV2 = true;
  58648. }
  58649. }
  58650. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58651. this._defines.VERTEXCOLOR = true;
  58652. if (mesh.hasVertexAlpha) {
  58653. this._defines.VERTEXALPHA = true;
  58654. }
  58655. }
  58656. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58657. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  58658. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  58659. }
  58660. // Instances
  58661. if (useInstances) {
  58662. this._defines.INSTANCES = true;
  58663. }
  58664. }
  58665. // Get correct effect
  58666. if (!this._defines.isEqual(this._cachedDefines)) {
  58667. this._defines.cloneTo(this._cachedDefines);
  58668. scene.resetCachedMaterial();
  58669. // Fallbacks
  58670. var fallbacks = new BABYLON.EffectFallbacks();
  58671. if (this._defines.REFLECTION) {
  58672. fallbacks.addFallback(0, "REFLECTION");
  58673. }
  58674. if (this._defines.REFRACTION) {
  58675. fallbacks.addFallback(0, "REFRACTION");
  58676. }
  58677. if (this._defines.REFLECTIVITY) {
  58678. fallbacks.addFallback(0, "REFLECTIVITY");
  58679. }
  58680. if (this._defines.BUMP) {
  58681. fallbacks.addFallback(0, "BUMP");
  58682. }
  58683. if (this._defines.PARALLAX) {
  58684. fallbacks.addFallback(1, "PARALLAX");
  58685. }
  58686. if (this._defines.PARALLAXOCCLUSION) {
  58687. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  58688. }
  58689. if (this._defines.SPECULAROVERALPHA) {
  58690. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  58691. }
  58692. if (this._defines.FOG) {
  58693. fallbacks.addFallback(1, "FOG");
  58694. }
  58695. if (this._defines.POINTSIZE) {
  58696. fallbacks.addFallback(0, "POINTSIZE");
  58697. }
  58698. if (this._defines.LOGARITHMICDEPTH) {
  58699. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  58700. }
  58701. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  58702. if (this._defines.SPECULARTERM) {
  58703. fallbacks.addFallback(0, "SPECULARTERM");
  58704. }
  58705. if (this._defines.OPACITYFRESNEL) {
  58706. fallbacks.addFallback(1, "OPACITYFRESNEL");
  58707. }
  58708. if (this._defines.EMISSIVEFRESNEL) {
  58709. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  58710. }
  58711. if (this._defines.FRESNEL) {
  58712. fallbacks.addFallback(3, "FRESNEL");
  58713. }
  58714. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  58715. fallbacks.addCPUSkinningFallback(0, mesh);
  58716. }
  58717. //Attributes
  58718. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58719. if (this._defines.NORMAL) {
  58720. attribs.push(BABYLON.VertexBuffer.NormalKind);
  58721. }
  58722. if (this._defines.TANGENT) {
  58723. attribs.push(BABYLON.VertexBuffer.TangentKind);
  58724. }
  58725. if (this._defines.UV1) {
  58726. attribs.push(BABYLON.VertexBuffer.UVKind);
  58727. }
  58728. if (this._defines.UV2) {
  58729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58730. }
  58731. if (this._defines.VERTEXCOLOR) {
  58732. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58733. }
  58734. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  58735. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  58736. // Legacy browser patch
  58737. var join = this._defines.toString();
  58738. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  58739. "vFogInfos", "vFogColor", "pointSize",
  58740. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  58741. "mBones",
  58742. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  58743. "depthValues",
  58744. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  58745. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  58746. "logarithmicDepthConstant",
  58747. "vSphericalX", "vSphericalY", "vSphericalZ",
  58748. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  58749. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  58750. "vMicrosurfaceTextureLods",
  58751. "vCameraInfos"
  58752. ];
  58753. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  58754. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  58755. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  58756. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  58757. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  58758. }
  58759. if (!this._effect.isReady()) {
  58760. return false;
  58761. }
  58762. this._renderId = scene.getRenderId();
  58763. this._wasPreviouslyReady = true;
  58764. if (mesh) {
  58765. if (!mesh._materialDefines) {
  58766. mesh._materialDefines = new PBRMaterialDefines();
  58767. }
  58768. this._defines.cloneTo(mesh._materialDefines);
  58769. }
  58770. return true;
  58771. };
  58772. PBRMaterial.prototype.unbind = function () {
  58773. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  58774. this._effect.setTexture("reflection2DSampler", null);
  58775. }
  58776. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  58777. this._effect.setTexture("refraction2DSampler", null);
  58778. }
  58779. _super.prototype.unbind.call(this);
  58780. };
  58781. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58782. this._effect.setMatrix("world", world);
  58783. };
  58784. PBRMaterial.prototype.bind = function (world, mesh) {
  58785. this._myScene = this.getScene();
  58786. // Matrices
  58787. this.bindOnlyWorldMatrix(world);
  58788. // Bones
  58789. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58790. if (this._myScene.getCachedMaterial() !== this) {
  58791. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  58792. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58793. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58794. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  58795. }
  58796. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58797. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  58798. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  58799. }
  58800. }
  58801. // Textures
  58802. if (this._myScene.texturesEnabled) {
  58803. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58804. this._effect.setTexture("albedoSampler", this.albedoTexture);
  58805. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  58806. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  58807. }
  58808. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58809. this._effect.setTexture("ambientSampler", this.ambientTexture);
  58810. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  58811. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  58812. }
  58813. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58814. this._effect.setTexture("opacitySampler", this.opacityTexture);
  58815. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  58816. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  58817. }
  58818. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58819. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  58820. if (this.reflectionTexture.isCube) {
  58821. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  58822. }
  58823. else {
  58824. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  58825. }
  58826. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  58827. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  58828. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  58829. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  58830. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  58831. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  58832. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  58833. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  58834. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  58835. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  58836. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  58837. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  58838. }
  58839. }
  58840. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58841. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  58842. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  58843. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  58844. }
  58845. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58846. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  58847. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  58848. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  58849. }
  58850. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58851. if (this.metallicTexture) {
  58852. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  58853. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  58854. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  58855. }
  58856. else if (this.reflectivityTexture) {
  58857. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  58858. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  58859. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  58860. }
  58861. }
  58862. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58863. this._effect.setTexture("bumpSampler", this.bumpTexture);
  58864. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  58865. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  58866. }
  58867. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58868. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  58869. var depth = 1.0;
  58870. if (this.refractionTexture.isCube) {
  58871. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58872. }
  58873. else {
  58874. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58875. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58876. if (this.refractionTexture.depth) {
  58877. depth = this.refractionTexture.depth;
  58878. }
  58879. }
  58880. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  58881. }
  58882. if ((this.reflectionTexture || this.refractionTexture)) {
  58883. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  58884. }
  58885. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58886. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  58887. }
  58888. }
  58889. // Clip plane
  58890. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  58891. // Point size
  58892. if (this.pointsCloud) {
  58893. this._effect.setFloat("pointSize", this.pointSize);
  58894. }
  58895. // Colors
  58896. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  58897. if (this._defines.METALLICWORKFLOW) {
  58898. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  58899. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  58900. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  58901. }
  58902. else {
  58903. // GAMMA CORRECTION.
  58904. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  58905. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  58906. }
  58907. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  58908. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  58909. // GAMMA CORRECTION.
  58910. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  58911. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  58912. // GAMMA CORRECTION.
  58913. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  58914. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  58915. }
  58916. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  58917. // GAMMA CORRECTION.
  58918. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  58919. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  58920. // Lights
  58921. if (this._myScene.lightsEnabled && !this.disableLighting) {
  58922. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  58923. }
  58924. // View
  58925. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  58926. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  58927. }
  58928. // Fog
  58929. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  58930. this._lightingInfos.x = this.directIntensity;
  58931. this._lightingInfos.y = this.emissiveIntensity;
  58932. this._lightingInfos.z = this.environmentIntensity;
  58933. this._lightingInfos.w = this.specularIntensity;
  58934. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  58935. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  58936. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  58937. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  58938. this._cameraInfos.x = this.cameraExposure;
  58939. this._cameraInfos.y = this.cameraContrast;
  58940. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  58941. if (this.cameraColorCurves) {
  58942. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  58943. }
  58944. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  58945. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  58946. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  58947. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  58948. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  58949. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  58950. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  58951. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  58952. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  58953. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  58954. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  58955. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  58956. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  58957. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  58958. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  58959. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  58960. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  58961. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  58962. // Log. depth
  58963. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  58964. }
  58965. _super.prototype.bind.call(this, world, mesh);
  58966. this._myScene = null;
  58967. };
  58968. PBRMaterial.prototype.getAnimatables = function () {
  58969. var results = [];
  58970. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  58971. results.push(this.albedoTexture);
  58972. }
  58973. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  58974. results.push(this.ambientTexture);
  58975. }
  58976. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  58977. results.push(this.opacityTexture);
  58978. }
  58979. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  58980. results.push(this.reflectionTexture);
  58981. }
  58982. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  58983. results.push(this.emissiveTexture);
  58984. }
  58985. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  58986. results.push(this.metallicTexture);
  58987. }
  58988. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  58989. results.push(this.reflectivityTexture);
  58990. }
  58991. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  58992. results.push(this.bumpTexture);
  58993. }
  58994. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  58995. results.push(this.lightmapTexture);
  58996. }
  58997. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  58998. results.push(this.refractionTexture);
  58999. }
  59000. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59001. results.push(this.cameraColorGradingTexture);
  59002. }
  59003. return results;
  59004. };
  59005. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59006. if (forceDisposeTextures) {
  59007. if (this.albedoTexture) {
  59008. this.albedoTexture.dispose();
  59009. }
  59010. if (this.ambientTexture) {
  59011. this.ambientTexture.dispose();
  59012. }
  59013. if (this.opacityTexture) {
  59014. this.opacityTexture.dispose();
  59015. }
  59016. if (this.reflectionTexture) {
  59017. this.reflectionTexture.dispose();
  59018. }
  59019. if (this.emissiveTexture) {
  59020. this.emissiveTexture.dispose();
  59021. }
  59022. if (this.metallicTexture) {
  59023. this.metallicTexture.dispose();
  59024. }
  59025. if (this.reflectivityTexture) {
  59026. this.reflectivityTexture.dispose();
  59027. }
  59028. if (this.bumpTexture) {
  59029. this.bumpTexture.dispose();
  59030. }
  59031. if (this.lightmapTexture) {
  59032. this.lightmapTexture.dispose();
  59033. }
  59034. if (this.refractionTexture) {
  59035. this.refractionTexture.dispose();
  59036. }
  59037. if (this.cameraColorGradingTexture) {
  59038. this.cameraColorGradingTexture.dispose();
  59039. }
  59040. }
  59041. this._renderTargets.dispose();
  59042. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59043. };
  59044. PBRMaterial.prototype.clone = function (name) {
  59045. var _this = this;
  59046. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59047. };
  59048. PBRMaterial.prototype.serialize = function () {
  59049. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59050. serializationObject.customType = "BABYLON.PBRMaterial";
  59051. return serializationObject;
  59052. };
  59053. // Statics
  59054. PBRMaterial.Parse = function (source, scene, rootUrl) {
  59055. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  59056. };
  59057. return PBRMaterial;
  59058. }(BABYLON.Material));
  59059. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  59060. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  59061. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  59062. PBRMaterial._scaledReflection = new BABYLON.Color3();
  59063. __decorate([
  59064. BABYLON.serialize()
  59065. ], PBRMaterial.prototype, "directIntensity", void 0);
  59066. __decorate([
  59067. BABYLON.serialize()
  59068. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  59069. __decorate([
  59070. BABYLON.serialize()
  59071. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59072. __decorate([
  59073. BABYLON.serialize()
  59074. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59075. __decorate([
  59076. BABYLON.serialize()
  59077. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59078. __decorate([
  59079. BABYLON.serialize()
  59080. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59081. __decorate([
  59082. BABYLON.serialize()
  59083. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59084. __decorate([
  59085. BABYLON.serialize()
  59086. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59087. __decorate([
  59088. BABYLON.serialize()
  59089. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59090. __decorate([
  59091. BABYLON.serializeAsTexture()
  59092. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59093. __decorate([
  59094. BABYLON.serializeAsColorCurves()
  59095. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59096. __decorate([
  59097. BABYLON.serializeAsColor3()
  59098. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59099. __decorate([
  59100. BABYLON.serialize()
  59101. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59102. __decorate([
  59103. BABYLON.serializeAsColor3()
  59104. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59105. __decorate([
  59106. BABYLON.serialize()
  59107. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59108. __decorate([
  59109. BABYLON.serializeAsColor3()
  59110. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59111. __decorate([
  59112. BABYLON.serialize()
  59113. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59114. __decorate([
  59115. BABYLON.serializeAsColor3()
  59116. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59117. __decorate([
  59118. BABYLON.serialize()
  59119. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59120. __decorate([
  59121. BABYLON.serializeAsColor3()
  59122. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59123. __decorate([
  59124. BABYLON.serialize()
  59125. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59126. __decorate([
  59127. BABYLON.serialize()
  59128. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59129. __decorate([
  59130. BABYLON.serialize()
  59131. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59132. __decorate([
  59133. BABYLON.serializeAsTexture()
  59134. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59135. __decorate([
  59136. BABYLON.serializeAsTexture()
  59137. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59138. __decorate([
  59139. BABYLON.serialize()
  59140. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  59141. __decorate([
  59142. BABYLON.serializeAsTexture()
  59143. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59144. __decorate([
  59145. BABYLON.serializeAsTexture()
  59146. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59147. __decorate([
  59148. BABYLON.serializeAsTexture()
  59149. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59150. __decorate([
  59151. BABYLON.serializeAsTexture()
  59152. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59153. __decorate([
  59154. BABYLON.serializeAsTexture()
  59155. ], PBRMaterial.prototype, "metallicTexture", void 0);
  59156. __decorate([
  59157. BABYLON.serialize()
  59158. ], PBRMaterial.prototype, "metallic", void 0);
  59159. __decorate([
  59160. BABYLON.serialize()
  59161. ], PBRMaterial.prototype, "roughness", void 0);
  59162. __decorate([
  59163. BABYLON.serializeAsTexture()
  59164. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59165. __decorate([
  59166. BABYLON.serializeAsTexture()
  59167. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59168. __decorate([
  59169. BABYLON.serializeAsTexture()
  59170. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59171. __decorate([
  59172. BABYLON.serializeAsColor3("ambient")
  59173. ], PBRMaterial.prototype, "ambientColor", void 0);
  59174. __decorate([
  59175. BABYLON.serializeAsColor3("albedo")
  59176. ], PBRMaterial.prototype, "albedoColor", void 0);
  59177. __decorate([
  59178. BABYLON.serializeAsColor3("reflectivity")
  59179. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59180. __decorate([
  59181. BABYLON.serializeAsColor3("reflection")
  59182. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59183. __decorate([
  59184. BABYLON.serializeAsColor3("emissive")
  59185. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59186. __decorate([
  59187. BABYLON.serialize()
  59188. ], PBRMaterial.prototype, "microSurface", void 0);
  59189. __decorate([
  59190. BABYLON.serialize()
  59191. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59192. __decorate([
  59193. BABYLON.serialize()
  59194. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59195. __decorate([
  59196. BABYLON.serializeAsFresnelParameters()
  59197. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  59198. __decorate([
  59199. BABYLON.serializeAsFresnelParameters()
  59200. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  59201. __decorate([
  59202. BABYLON.serialize()
  59203. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  59204. __decorate([
  59205. BABYLON.serialize()
  59206. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  59207. __decorate([
  59208. BABYLON.serialize()
  59209. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  59210. __decorate([
  59211. BABYLON.serialize()
  59212. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  59213. __decorate([
  59214. BABYLON.serialize()
  59215. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  59216. __decorate([
  59217. BABYLON.serialize()
  59218. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  59219. __decorate([
  59220. BABYLON.serialize()
  59221. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  59222. __decorate([
  59223. BABYLON.serialize()
  59224. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  59225. __decorate([
  59226. BABYLON.serialize()
  59227. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  59228. __decorate([
  59229. BABYLON.serialize()
  59230. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  59231. __decorate([
  59232. BABYLON.serialize()
  59233. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  59234. __decorate([
  59235. BABYLON.serialize()
  59236. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59237. __decorate([
  59238. BABYLON.serialize()
  59239. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59240. __decorate([
  59241. BABYLON.serialize()
  59242. ], PBRMaterial.prototype, "useParallax", void 0);
  59243. __decorate([
  59244. BABYLON.serialize()
  59245. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59246. __decorate([
  59247. BABYLON.serialize()
  59248. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59249. __decorate([
  59250. BABYLON.serialize()
  59251. ], PBRMaterial.prototype, "disableLighting", void 0);
  59252. __decorate([
  59253. BABYLON.serialize()
  59254. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59255. __decorate([
  59256. BABYLON.serialize()
  59257. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59258. __decorate([
  59259. BABYLON.serialize()
  59260. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59261. __decorate([
  59262. BABYLON.serialize()
  59263. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  59264. __decorate([
  59265. BABYLON.serialize()
  59266. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59267. BABYLON.PBRMaterial = PBRMaterial;
  59268. })(BABYLON || (BABYLON = {}));
  59269. //# sourceMappingURL=babylon.pbrMaterial.js.map
  59270. var BABYLON;
  59271. (function (BABYLON) {
  59272. var DebugLayer = (function () {
  59273. function DebugLayer(scene) {
  59274. this._scene = scene;
  59275. }
  59276. /** Creates the inspector window. */
  59277. DebugLayer.prototype._createInspector = function (config) {
  59278. if (config === void 0) { config = {}; }
  59279. var popup = config.popup || false;
  59280. var initialTab = config.initialTab || 0;
  59281. var parentElement = config.parentElement || null;
  59282. if (!this._inspector) {
  59283. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement);
  59284. } // else nothing to do,; instance is already existing
  59285. };
  59286. DebugLayer.prototype.isVisible = function () {
  59287. if (!this._inspector) {
  59288. return false;
  59289. }
  59290. return true;
  59291. };
  59292. DebugLayer.prototype.hide = function () {
  59293. if (this._inspector) {
  59294. this._inspector.dispose();
  59295. this._inspector = null;
  59296. }
  59297. };
  59298. DebugLayer.prototype.show = function (config) {
  59299. if (config === void 0) { config = {}; }
  59300. if (typeof INSPECTOR == 'undefined') {
  59301. // Load inspector and add it to the DOM
  59302. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59303. }
  59304. else {
  59305. // Otherwise creates the inspector
  59306. this._createInspector(config);
  59307. }
  59308. };
  59309. return DebugLayer;
  59310. }());
  59311. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  59312. BABYLON.DebugLayer = DebugLayer;
  59313. })(BABYLON || (BABYLON = {}));
  59314. //# sourceMappingURL=babylon.debugLayer.js.map
  59315. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  59316. var BABYLON;
  59317. (function (BABYLON) {
  59318. var StandardRenderingPipeline = (function (_super) {
  59319. __extends(StandardRenderingPipeline, _super);
  59320. /**
  59321. * @constructor
  59322. * @param {string} name - The rendering pipeline name
  59323. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59324. * @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)
  59325. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59326. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59327. */
  59328. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59329. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59330. var _this = _super.call(this, scene.getEngine(), name) || this;
  59331. _this.downSampleX4PostProcess = null;
  59332. _this.brightPassPostProcess = null;
  59333. _this.gaussianBlurHPostProcesses = [];
  59334. _this.gaussianBlurVPostProcesses = [];
  59335. _this.textureAdderPostProcess = null;
  59336. _this.textureAdderFinalPostProcess = null;
  59337. _this.lensFlareFinalPostProcess = null;
  59338. _this.lensFlarePostProcess = null;
  59339. _this.lensFlareComposePostProcess = null;
  59340. _this.depthOfFieldPostProcess = null;
  59341. // Values
  59342. _this.brightThreshold = 1.0;
  59343. _this.blurWidth = 2.0;
  59344. _this.horizontalBlur = false;
  59345. _this.gaussianCoefficient = 0.25;
  59346. _this.gaussianMean = 1.0;
  59347. _this.gaussianStandardDeviation = 1.0;
  59348. _this.exposure = 1.0;
  59349. _this.lensTexture = null;
  59350. _this.lensColorTexture = null;
  59351. _this.lensFlareStrength = 20.0;
  59352. _this.lensFlareGhostDispersal = 1.4;
  59353. _this.lensFlareHaloWidth = 0.7;
  59354. _this.lensFlareDistortionStrength = 16.0;
  59355. _this.lensStarTexture = null;
  59356. _this.lensFlareDirtTexture = null;
  59357. _this.depthOfFieldDistance = 10.0;
  59358. _this.depthOfFieldBlurWidth = 2.0;
  59359. // IAnimatable
  59360. _this.animations = [];
  59361. _this._depthRenderer = null;
  59362. _this._currentDepthOfFieldSource = null;
  59363. // Getters and setters
  59364. _this._depthOfFieldEnabled = true;
  59365. _this._lensFlareEnabled = true;
  59366. // Initialize
  59367. _this._scene = scene;
  59368. // Create pass post-processe
  59369. if (!originalPostProcess) {
  59370. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  59371. }
  59372. else {
  59373. _this.originalPostProcess = originalPostProcess;
  59374. }
  59375. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59376. // Create down sample X4 post-process
  59377. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  59378. // Create bright pass post-process
  59379. _this._createBrightPassPostProcess(scene, ratio / 2);
  59380. // Create gaussian blur post-processes (down sampling blurs)
  59381. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  59382. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  59383. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  59384. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  59385. // Create texture adder post-process
  59386. _this._createTextureAdderPostProcess(scene, ratio);
  59387. // Create depth-of-field source post-process
  59388. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59390. // Create lens flare post-process
  59391. _this._createLensFlarePostProcess(scene, ratio);
  59392. // Create depth-of-field source post-process post lens-flare and disable it now
  59393. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59394. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59395. // Create gaussian blur used by depth-of-field
  59396. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  59397. // Create depth-of-field post-process
  59398. _this._createDepthOfFieldPostProcess(scene, ratio);
  59399. // Finish
  59400. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59401. if (cameras !== null) {
  59402. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59403. }
  59404. // Deactivate
  59405. _this.LensFlareEnabled = false;
  59406. _this.DepthOfFieldEnabled = false;
  59407. return _this;
  59408. }
  59409. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59410. get: function () {
  59411. return this._depthOfFieldEnabled;
  59412. },
  59413. set: function (enabled) {
  59414. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  59415. if (enabled && !this._depthOfFieldEnabled) {
  59416. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59417. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59418. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59419. this._depthRenderer = this._scene.enableDepthRenderer();
  59420. }
  59421. else if (!enabled && this._depthOfFieldEnabled) {
  59422. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59423. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59424. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59425. }
  59426. this._depthOfFieldEnabled = enabled;
  59427. },
  59428. enumerable: true,
  59429. configurable: true
  59430. });
  59431. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59432. get: function () {
  59433. return this._lensFlareEnabled;
  59434. },
  59435. set: function (enabled) {
  59436. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  59437. if (enabled && !this._lensFlareEnabled) {
  59438. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59439. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59440. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59441. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59442. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59443. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  59444. }
  59445. else if (!enabled && this._lensFlareEnabled) {
  59446. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59447. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59448. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59449. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59450. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59451. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  59452. }
  59453. this._lensFlareEnabled = enabled;
  59454. },
  59455. enumerable: true,
  59456. configurable: true
  59457. });
  59458. // Sets depth-of-field save post-process
  59459. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  59460. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  59461. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  59462. switch (name) {
  59463. case "HDRBaseDepthOfFieldSource":
  59464. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  59465. break;
  59466. case "HDRPostLensFlareDepthOfFieldSource":
  59467. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  59468. break;
  59469. default: break;
  59470. }
  59471. };
  59472. // Down Sample X4 Post-Processs
  59473. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59474. var _this = this;
  59475. var downSampleX4Offsets = new Array(32);
  59476. 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);
  59477. this.downSampleX4PostProcess.onApply = function (effect) {
  59478. var id = 0;
  59479. for (var i = -2; i < 2; i++) {
  59480. for (var j = -2; j < 2; j++) {
  59481. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  59482. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  59483. id += 2;
  59484. }
  59485. }
  59486. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59487. };
  59488. // Add to pipeline
  59489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59490. };
  59491. // Brightpass Post-Process
  59492. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59493. var _this = this;
  59494. var brightOffsets = new Array(8);
  59495. 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);
  59496. this.brightPassPostProcess.onApply = function (effect) {
  59497. var sU = (1.0 / _this.brightPassPostProcess.width);
  59498. var sV = (1.0 / _this.brightPassPostProcess.height);
  59499. brightOffsets[0] = -0.5 * sU;
  59500. brightOffsets[1] = 0.5 * sV;
  59501. brightOffsets[2] = 0.5 * sU;
  59502. brightOffsets[3] = 0.5 * sV;
  59503. brightOffsets[4] = -0.5 * sU;
  59504. brightOffsets[5] = -0.5 * sV;
  59505. brightOffsets[6] = 0.5 * sU;
  59506. brightOffsets[7] = -0.5 * sV;
  59507. effect.setArray2("dsOffsets", brightOffsets);
  59508. effect.setFloat("brightThreshold", _this.brightThreshold);
  59509. };
  59510. // Add to pipeline
  59511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59512. };
  59513. // Create gaussian blur H&V post-processes
  59514. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59515. var _this = this;
  59516. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59517. var blurOffsets = new Array(9);
  59518. var blurWeights = new Array(9);
  59519. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  59520. var callback = function (height) {
  59521. return function (effect) {
  59522. // Weights
  59523. var x = 0.0;
  59524. for (var i = 0; i < 9; i++) {
  59525. x = (i - 4.0) / 4.0;
  59526. blurWeights[i] =
  59527. _this.gaussianCoefficient
  59528. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  59529. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  59530. }
  59531. var lastOutputDimensions = {
  59532. width: scene.getEngine().getRenderWidth(),
  59533. height: scene.getEngine().getRenderHeight()
  59534. };
  59535. for (var i = 0; i < 9; i++) {
  59536. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  59537. blurOffsets[i] = value;
  59538. }
  59539. effect.setArray("blurOffsets", blurOffsets);
  59540. effect.setArray("blurWeights", blurWeights);
  59541. if (height) {
  59542. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  59543. }
  59544. else {
  59545. effect.setFloat("blurWidth", _this[blurWidthKey]);
  59546. }
  59547. };
  59548. };
  59549. // Create horizontal gaussian blur post-processes
  59550. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59551. gaussianBlurHPostProcess.onApply = callback(false);
  59552. // Create vertical gaussian blur post-process
  59553. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59554. gaussianBlurVPostProcess.onApply = callback(true);
  59555. // Add to pipeline
  59556. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  59557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  59558. // Finish
  59559. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  59560. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  59561. };
  59562. // Create texture adder post-process
  59563. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59564. var _this = this;
  59565. 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);
  59566. this.textureAdderPostProcess.onApply = function (effect) {
  59567. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  59568. effect.setTexture("lensSampler", _this.lensTexture);
  59569. effect.setFloat("exposure", _this.exposure);
  59570. };
  59571. // Add to pipeline
  59572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59573. };
  59574. // Create lens flare post-process
  59575. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59576. var _this = this;
  59577. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59578. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59579. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  59580. 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);
  59581. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59582. var resolution = new BABYLON.Vector2(0, 0);
  59583. // Lens flare
  59584. this.lensFlarePostProcess.onApply = function (effect) {
  59585. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  59586. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59587. effect.setFloat("strength", _this.lensFlareStrength);
  59588. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59589. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59590. // Shift
  59591. resolution.x = _this.lensFlarePostProcess.width;
  59592. resolution.y = _this.lensFlarePostProcess.height;
  59593. effect.setVector2("resolution", resolution);
  59594. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59595. };
  59596. // Compose
  59597. 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);
  59598. 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);
  59599. this.lensFlareComposePostProcess.onApply = function (effect) {
  59600. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  59601. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59602. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59603. // Lens start rotation matrix
  59604. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59605. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59606. 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));
  59607. camRot *= 4.0;
  59608. 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);
  59609. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59610. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59611. };
  59612. };
  59613. // Create depth-of-field post-process
  59614. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59615. var _this = this;
  59616. 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);
  59617. this.depthOfFieldPostProcess.onApply = function (effect) {
  59618. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59619. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  59620. effect.setFloat("distance", _this.depthOfFieldDistance);
  59621. };
  59622. // Add to pipeline
  59623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59624. };
  59625. // Dispose
  59626. StandardRenderingPipeline.prototype.dispose = function () {
  59627. for (var i = 0; i < this._scene.cameras.length; i++) {
  59628. var camera = this._scene.cameras[i];
  59629. this.originalPostProcess.dispose(camera);
  59630. this.downSampleX4PostProcess.dispose(camera);
  59631. this.brightPassPostProcess.dispose(camera);
  59632. this.textureAdderPostProcess.dispose(camera);
  59633. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  59634. this.gaussianBlurHPostProcesses[j].dispose(camera);
  59635. }
  59636. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  59637. this.gaussianBlurVPostProcesses[j].dispose(camera);
  59638. }
  59639. this.textureAdderFinalPostProcess.dispose(camera);
  59640. this.lensFlarePostProcess.dispose(camera);
  59641. this.lensFlareComposePostProcess.dispose(camera);
  59642. this.depthOfFieldPostProcess.dispose(camera);
  59643. }
  59644. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59645. _super.prototype.dispose.call(this);
  59646. };
  59647. // Serialize rendering pipeline
  59648. StandardRenderingPipeline.prototype.serialize = function () {
  59649. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59650. serializationObject.customType = "StandardRenderingPipeline";
  59651. return serializationObject;
  59652. };
  59653. // Parse serialized pipeline
  59654. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59655. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59656. };
  59657. return StandardRenderingPipeline;
  59658. }(BABYLON.PostProcessRenderPipeline));
  59659. __decorate([
  59660. BABYLON.serialize()
  59661. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59662. __decorate([
  59663. BABYLON.serialize()
  59664. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59665. __decorate([
  59666. BABYLON.serialize()
  59667. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59668. __decorate([
  59669. BABYLON.serialize()
  59670. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  59671. __decorate([
  59672. BABYLON.serialize()
  59673. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  59674. __decorate([
  59675. BABYLON.serialize()
  59676. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  59677. __decorate([
  59678. BABYLON.serialize()
  59679. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59680. __decorate([
  59681. BABYLON.serializeAsTexture("lensTexture")
  59682. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59683. __decorate([
  59684. BABYLON.serializeAsTexture("lensColorTexture")
  59685. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59686. __decorate([
  59687. BABYLON.serialize()
  59688. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59689. __decorate([
  59690. BABYLON.serialize()
  59691. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59692. __decorate([
  59693. BABYLON.serialize()
  59694. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59695. __decorate([
  59696. BABYLON.serialize()
  59697. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59698. __decorate([
  59699. BABYLON.serializeAsTexture("lensStarTexture")
  59700. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59701. __decorate([
  59702. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59703. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59704. __decorate([
  59705. BABYLON.serialize()
  59706. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59707. __decorate([
  59708. BABYLON.serialize()
  59709. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59710. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59711. })(BABYLON || (BABYLON = {}));
  59712. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59713. 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 TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\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 TANGENT\nattribute vec4 tangent;\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<bumpVertexDeclaration>\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<bumpVertex>\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":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\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<shadowsFragmentFunctions>\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#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\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 TANGENT\nattribute vec4 tangent;\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<bumpVertexDeclaration>\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<bumpVertex>\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#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\nuniform vec2 biasAndScale;\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\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  59714. 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)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,vPositionW,vBumpUV);\n#endif\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(TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\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(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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangent.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangent.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\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,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}\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+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\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 SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\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","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)\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));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\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 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\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) 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 computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nconst float shadowStrength=80.;\nfloat visibility=1.0-clamp(exp(shadowStrength*shadowPixelDepth)*shadowMapSample-darkness,0.,1.);\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,visibility,vOverloadedShadowIntensity.x);\n#else\nreturn visibility;\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\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 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\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\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"};
  59715. 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(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),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(e){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(o){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);var d=n?n.collisionMask:t.collisionMask;t._initialize(o,i,a);for(var l=0;l<this._scene.meshes.length;l++){var c=this._scene.meshes[l];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==n&&0!==(d&c.collisionGroup)&&c._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.set=function(t,i,r){return this.copyFromFloats(t,i,r)},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.copyFromFloats=function(t,i,r,n){return this.r=t,this.g=i,this.b=r,this.a=n,this},t.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.set=function(t,i){return this.copyFromFloats(t,i)},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){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},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.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r(-1,0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(t,i,r,n){var o=A.Quaternion[0];a.RotationQuaternionFromAxisToRef(t,i,r,o),o.toEulerAnglesToRef(n)},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){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t,this},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.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.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.w=t.w},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o,e){e.x=t*o.m[0]+i*o.m[4]+r*o.m[8],e.y=t*o.m[1]+i*o.m[5]+r*o.m[9],e.z=t*o.m[2]+i*o.m[6]+r*o.m[10],e.w=n},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){return this.width=t,this.height=i,this},t.prototype.set=function(t,i){return this.copyFromFloats(t,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 i(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 i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.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)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.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},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){var t=new i(-this.x,-this.y,-this.z,this.w);return t},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.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},i.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},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.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)},i.Zero=function(){return new i(0,0,0,0)},i.Inverse=function(t){return new i(-t.x,-t.y,-t.z,t.w)},i.Identity=function(){return new i(0,0,0,1)},i.IsIdentity=function(t){return t&&0===t.x&&0===t.y&&0===t.z&&1===t.w},i.RotationAxis=function(t,r){return i.RotationAxisToRef(t,r,new i)},i.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},i.FromArray=function(t,r){return r||(r=0),new i(t[r],t[r+1],t[r+2],t[r+3])},i.RotationYawPitchRoll=function(t,r,n){var o=new i;return i.RotationYawPitchRollToRef(t,r,n,o),o},i.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},i.RotationAlphaBetaGamma=function(t,r,n){var o=new i;return i.RotationAlphaBetaGammaToRef(t,r,n,o),o},i.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)},i.RotationQuaternionFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.RotationQuaternionFromAxisToRef(t,r,n,e),e},i.RotationQuaternionFromAxisToRef=function(i,r,n,o){var e=A.Matrix[0];t.Matrix.FromXYZAxesToRef(i.normalize(),r.normalize(),n.normalize(),e),t.Quaternion.FromRotationMatrixToRef(e,o)},i.Slerp=function(t,r,n){var o=i.Identity();return i.SlerpToRef(t,r,n,o),o},i.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},i}();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),F=e*w-s*d+a*R,M=-(e*v-s*g+h*R),A=1/(i*T+r*_+n*F+o*M),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,N=s*y-h*m,V=e*c-a*u,q=e*y-h*u,D=e*m-s*u;return t.m[0]=T*A,t.m[4]=_*A,\nt.m[8]=F*A,t.m[12]=M*A,t.m[1]=-(r*z-n*w+o*v)*A,t.m[5]=(i*z-n*d+o*g)*A,t.m[9]=-(i*w-r*d+o*R)*A,t.m[13]=(i*v-r*g+n*R)*A,t.m[2]=(r*b-n*L+o*C)*A,t.m[6]=-(i*b-n*P+o*Z)*A,t.m[10]=(i*L-r*P+o*S)*A,t.m[14]=-(i*C-r*Z+n*S)*A,t.m[3]=-(r*I-n*H+o*N)*A,t.m[7]=(i*I-n*V+o*q)*A,t.m[11]=-(i*H-r*V+o*D)*A,t.m[15]=(i*N-r*q+n*D)*A,this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,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.getTranslationToRef=function(t){return t.x=this.m[12],t.y=this.m[13],t.z=this.m[14],this},r.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},r.prototype.multiply=function(t){var 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],F=t.m[6],M=t.m[7],A=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*A+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*F+e*L+s*S,i[r+3]=n*R+o*M+e*C+s*I,i[r+4]=h*v+a*T+u*A+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*F+u*L+m*S,i[r+7]=h*R+a*M+u*C+m*I,i[r+8]=y*v+c*T+p*A+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*F+p*L+f*S,i[r+11]=y*R+c*M+p*C+f*I,i[r+12]=x*v+l*T+z*A+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*F+z*L+w*S,i[r+15]=x*R+l*M+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]);return 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),this},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.prototype.setRowFromFloats=function(t,i,r,n,o){if(t<0||t>3)return this;var e=4*t;return this.m[e+0]=i,this.m[e+1]=r,this.m[e+2]=n,this.m[e+3]=o,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.Identity();return r.ComposeToRef(t,i,n,o),o},r.ComposeToRef=function(t,i,n,o){r.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,A.Matrix[1]),i.toRotationMatrix(A.Matrix[0]),A.Matrix[1].multiplyToRef(A.Matrix[0],o),o.setTranslation(n)},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=!1);var e=o?-1:1,s=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),u=Math.tan(t.rightDegrees*Math.PI/180),m=2/(a+u),y=2/(s+h);n.m[0]=m,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=y,n.m[6]=n.m[7]=0,n.m[8]=(a-u)*m*.5*e,n.m[9]=-((s-h)*y*.5)*e,n.m[10]=-(i+r)/(r-i)*e,n.m[11]=1*e,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.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},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\",t[t.BONE=2]=\"BONE\"}(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.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},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 F=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=F;var M=function(){function t(){}return t}();M.Color3=[r.Black(),r.Black(),r.Black()],M.Vector2=[o.Zero(),o.Zero(),o.Zero()],M.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],M.Vector4=[s.Zero(),s.Zero(),s.Zero()],M.Quaternion=[a.Zero(),a.Zero()],M.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=M;var A=function(){function t(){}return t}();A.Vector3=[e.Zero()],A.Matrix=[u.Zero(),u.Zero()],A.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  59716. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59717. module.exports = BABYLON;
  59718. };